p2party 0.14.2 → 0.14.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.mjs CHANGED
@@ -1 +1 @@
1
- import{isUUID as e,isHexadecimal as t}from"class-validator";import{createSlice as n,nanoid as r,formatProdErrorMessage as a,createSelector as o,createAction as i,createAsyncThunk as s,prepareAutoBatched as c,isAnyOf as l,isFulfilled as d,isRejectedWithValue as u,combineReducers as h,isPlainObject as f,SHOULD_AUTOBATCH as p,isAllOf as m,isRejected as y,isPending as g,isAction as w,createNextState as b,isAsyncThunkAction as v,createListenerMiddleware as k,configureStore as I}from"@reduxjs/toolkit";var S="0.14.2";const C=n({name:"commonState",initialState:{currentRoomUrl:""},reducers:{setCurrentRoomUrl:(e,t)=>{e.currentRoomUrl=t.payload}}}),{setCurrentRoomUrl:A}=C.actions;var E=C.reducer;const P={peerId:localStorage.getItem("peerId")??"",challengeId:localStorage.getItem("challengeId")??"",publicKey:localStorage.getItem("publicKey")??"",secretKey:"",challenge:localStorage.getItem("challenge")??"",signature:localStorage.getItem("signature")??""},x=n({name:"keyPair",initialState:P,reducers:{setKeyPair:(e,t)=>{const{publicKey:n,secretKey:r}=t.payload;64===n.length&&128===r.length&&(e.publicKey=t.payload.publicKey,e.secretKey=t.payload.secretKey)},setReconnectData:(n,r)=>{const{peerId:a,challenge:o,signature:i,challengeId:s}=r.payload;e(a,4)&&e(s)&&t(o)&&t(i)&&64===o.length&&128===i.length&&(n.peerId=a,n.challenge=o,n.signature=i,n.challengeId=s)},setPeerData:(n,r)=>{const{peerId:a,challenge:o,signature:i}=r.payload;e(a,4)&&t(o)&&t(i)&&64===o.length&&128===i.length&&(n.peerId=a,n.challenge=o,n.signature=i)},setChallengeId:(t,n)=>{const{challengeId:r}=n.payload;e(r)&&(t.challengeId=r)},resetIdentity:()=>({peerId:"",challengeId:"",publicKey:"",secretKey:"",challenge:"",signature:""})}}),{setKeyPair:K,setReconnectData:R,setPeerData:M,setChallengeId:_,resetIdentity:U}=x.actions;var D=x.reducer;const T=64*Uint8Array.BYTES_PER_ELEMENT,N=64*Uint8Array.BYTES_PER_ELEMENT,q=208,O=64*Uint8Array.BYTES_PER_ELEMENT,B=32*Uint8Array.BYTES_PER_ELEMENT,L=32*Uint8Array.BYTES_PER_ELEMENT,F=64*Uint8Array.BYTES_PER_ELEMENT,z=32*Uint8Array.BYTES_PER_ELEMENT,j=12*Uint8Array.BYTES_PER_ELEMENT,H=16*Uint8Array.BYTES_PER_ELEMENT,V=16*Uint8Array.BYTES_PER_ELEMENT,$=32*Uint8Array.BYTES_PER_ELEMENT,Q=64*Uint8Array.BYTES_PER_ELEMENT,W=32*Uint8Array.BYTES_PER_ELEMENT,X=32*Uint8Array.BYTES_PER_ELEMENT,G=32*Uint8Array.BYTES_PER_ELEMENT,J=65536,Y=10737418240,Z=1048576,ee=9+N+8+8+256+8+8+8,te=4+48*(N+1),ne=65405-(ee+te),re=J-ne,ae=65405,oe=N,ie=1+oe,se=new Uint8Array([1]),ce=32,le=12,de=65474+H,ue=(new TextEncoder).encode("p2party-x25519-idsig-v1"),he="hybrid-3dh-mlkem512-cpace21-v4",fe="hybrid-3dh-mlkem768-cpace21-v4",pe="hybrid-3dh-mlkem1024-cpace21-v4",me=[he,fe,pe],ye=fe,ge=2e3,we=1048576,be=65536,ve=e=>{if("hybrid-mlkem512"===e)return 512;if("hybrid-mlkem768"===e)return 768;if("hybrid-mlkem1024"===e)return 1024;throw new Error("roomPolicy: unsupported PQ mode")},ke=e=>{if("hybrid-mlkem512"===e)return he;if("hybrid-mlkem768"===e)return fe;if("hybrid-mlkem1024"===e)return pe;throw new Error("roomPolicy: unsupported PQ mode")},Ie=e=>{if(e===he)return"hybrid-mlkem512";if(e===fe)return"hybrid-mlkem768";if(e===pe)return"hybrid-mlkem1024";throw new Error("roomPolicy: unsupported ratchet root suite")},Se=1e3,Ce=36e5,Ae=16,Ee=1024,Pe=25,xe=new Uint8Array([80,50,82,80]),Ke=(new TextEncoder).encode("p2party/room-policy/v1\0"),Re=new Set(["version","revision","wireVersion","authMode","pqMode","rendezvousMode","coverMode","coverCadenceMs","coverLanes","coverFramesPerCell","coverDurationEpochs"]),Me={nopin:0,pin:1},_e={"hybrid-mlkem768":1,"hybrid-mlkem512":2,"hybrid-mlkem1024":3},Ue={"legacy-signaling":0,"opaque-token":1,"blind-meeting-point":2},De={immediate:0,scheduled:1},Te=e=>{if(0===e)return"nopin";if(1===e)return"pin";throw new Error("roomPolicy: unsupported auth mode")},Ne=e=>{if(1===e)return"hybrid-mlkem768";if(2===e)return"hybrid-mlkem512";if(3===e)return"hybrid-mlkem1024";if(0===e)throw new Error("roomPolicy: v3 requires a hybrid ML-KEM suite");throw new Error("roomPolicy: unsupported PQ mode")},qe=e=>{if(0===e)return"legacy-signaling";if(1===e)return"opaque-token";if(2===e)return"blind-meeting-point";throw new Error("roomPolicy: unsupported rendezvous mode")},Oe=e=>{if(0===e)return"immediate";if(1===e)return"scheduled";throw new Error("roomPolicy: unsupported cover mode")},Be=(e,t,n)=>{if(!Number.isSafeInteger(t)||t<0||t>n)throw new Error(`roomPolicy: ${e} is out of range`)};function Le(e,t,n){if("string"!=typeof t||!Object.hasOwn(n,t))throw new Error(`roomPolicy: unsupported ${e}`)}const Fe=e=>{if((e=>{if(null===e||"object"!=typeof e||Array.isArray(e))throw new Error("roomPolicy: policy must be an object");const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)throw new Error("roomPolicy: policy must be a plain record");const n=Reflect.ownKeys(e);if(n.length!==Re.size||n.some(e=>"string"!=typeof e||!Re.has(e)))throw new Error("roomPolicy: policy has missing or unexpected fields (PIN bytes are never policy fields)");for(const t of Re){const n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n||!("value"in n)||!n.enumerable)throw new Error("roomPolicy: policy fields must be enumerable data properties")}})(e),1!==e.version)throw new Error("roomPolicy: unsupported policy version");if(4!==e.wireVersion)throw new Error("roomPolicy: unsupported wire version");if(Be("revision",e.revision,4294967295),Le("auth mode",e.authMode,Me),Le("PQ mode",e.pqMode,_e),Le("rendezvous mode",e.rendezvousMode,Ue),Le("cover mode",e.coverMode,De),Be("cover cadence",e.coverCadenceMs,4294967295),Be("cover lanes",e.coverLanes,65535),Be("cover frames per cell",e.coverFramesPerCell,65535),Be("cover duration epochs",e.coverDurationEpochs,65535),"immediate"!==e.coverMode){if(e.coverCadenceMs<Se||e.coverCadenceMs>Ce)throw new Error("roomPolicy: scheduled cover cadence is out of range");if(e.coverLanes<1||e.coverLanes>16)throw new Error("roomPolicy: scheduled cover lanes are out of range");if(e.coverFramesPerCell<1||e.coverFramesPerCell>Ee)throw new Error("roomPolicy: scheduled cover frames per cell are out of range");if(e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell)<25)throw new Error("roomPolicy: scheduled cover slots are below the transport timer granularity");if(e.coverDurationEpochs<1)throw new Error("roomPolicy: scheduled cover duration epochs are out of range")}else if(0!==e.coverCadenceMs||0!==e.coverLanes||0!==e.coverFramesPerCell||0!==e.coverDurationEpochs)throw new Error("roomPolicy: immediate cover mode requires zero schedule fields")},ze=e=>{Fe(e);const t=new Uint8Array(32);t.set(xe,0),t[4]=1,t[5]=e.wireVersion,t[6]=Me[e.authMode],t[7]=_e[e.pqMode],t[8]=Ue[e.rendezvousMode],t[9]=De[e.coverMode];const n=new DataView(t.buffer,t.byteOffset,t.byteLength);return n.setUint32(10,e.revision,!1),n.setUint32(14,e.coverCadenceMs,!1),n.setUint16(18,e.coverLanes,!1),n.setUint16(20,e.coverFramesPerCell,!1),n.setUint16(22,e.coverDurationEpochs,!1),t},je=e=>{if(!(e instanceof Uint8Array))throw new Error("roomPolicy: encoded policy must be a Uint8Array");if(32!==e.length)throw new Error("roomPolicy: invalid encoded policy length");for(let t=0;t<xe.length;t++)if(e[t]!==xe[t])throw new Error("roomPolicy: invalid policy magic");for(let t=24;t<e.length;t++)if(0!==e[t])throw new Error("roomPolicy: non-zero reserved policy byte");const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[4],wireVersion:e[5],authMode:Te(e[6]),pqMode:Ne(e[7]),rendezvousMode:qe(e[8]),coverMode:Oe(e[9]),revision:t.getUint32(10,!1),coverCadenceMs:t.getUint32(14,!1),coverLanes:t.getUint16(18,!1),coverFramesPerCell:t.getUint16(20,!1),coverDurationEpochs:t.getUint16(22,!1)};return Fe(n),n},He=e=>je(ze(e)),Ve=(e,t)=>{const n=ze(e),r=ze(t);let a=0;for(let e=0;e<n.length;e++)a|=n[e]^r[e];return 0===a},$e=async e=>{const t=ze(e),n=new Uint8Array(Ke.length+t.length);n.set(Ke,0),n.set(t,Ke.length);const r=await globalThis.crypto.subtle.digest("SHA-256",n);return new Uint8Array(r)},Qe=Object.freeze({version:1,revision:0,wireVersion:4,authMode:"nopin",pqMode:"hybrid-mlkem768",rendezvousMode:"legacy-signaling",coverMode:"immediate",coverCadenceMs:0,coverLanes:0,coverFramesPerCell:0,coverDurationEpochs:0}),We={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},Xe=(e,t)=>{const n=He(t);if(!Ve(e,n))throw new Error("roomSlice: room policy is immutable after creation")},Ge=n({name:"rooms",initialState:[],reducers:{setRoom:(t,n)=>{const{url:r,id:a,canBeConnectionRelay:o,rtcConfig:i,onlyConnectWithKnownPeers:s,policy:c}=n.payload;if(64===r.length&&e(a)){const e=t.findIndex(e=>e.url===r||e.id===a);e>-1?(c&&Xe(t[e].policy,c),t[e].url=r,t[e].id=a,null!=o&&(t[e].canBeConnectionRelay=o),i&&(t[e].rtcConfig=i),t[e].onlyConnectWithKnownAddresses=null!=s?s:"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers")):t.push({url:r,id:a,connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:o??!0,onlyConnectWithKnownAddresses:s??"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers"),rtcConfig:i??We,policy:He(c??Qe),peers:[],channels:[],messages:[]})}else if(64===r.length){const e=t.findIndex(e=>e.url===r);e>-1?(c&&Xe(t[e].policy,c),t[e].url=r,t[e].id="",null!=o&&(t[e].canBeConnectionRelay=o),i&&(t[e].rtcConfig=i),t[e].onlyConnectWithKnownAddresses=null!=s?s:"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers")):t.push({url:r,id:"",connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:o??!0,onlyConnectWithKnownAddresses:s??"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers"),rtcConfig:i??We,policy:He(c??Qe),peers:[],channels:[],messages:[]})}},setRoomPolicy:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload.roomContext||e.id===t.payload.roomContext);n>-1&&Xe(e[n].policy,t.payload.policy)},setConnectingToPeers:(e,t)=>{const{roomId:n,connectingToPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].connectingToPeers=r)},setConnectedToPeers:(e,t)=>{const{roomId:n,connectedToPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].connectingToPeers=!1,e[a].connectedToPeers=r)},setConnectionRelay:(e,t)=>{const{roomId:n,canBeConnectionRelay:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].canBeConnectionRelay=r)},setPeer:(e,t)=>{const{roomId:n,peerId:r,peerPublicKey:a}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){-1===e[o].peers.findIndex(e=>e.peerId===r)&&e[o].peers.push({peerId:r,peerPublicKey:a})}},deletePeer:(e,t)=>{const n=e.length;for(let r=0;r<n;r++){if(void 0!==t.payload.roomId&&e[r].id!==t.payload.roomId)continue;const n=e[r].peers.findIndex(e=>e.peerId===t.payload.peerId);n>-1&&e[r].peers.splice(n,1);const a=e[r].coverStatusByPeer;a&&delete a[t.payload.peerId];const o=e[r].handshakeStatusByPeer;o&&"failed"!==o[t.payload.peerId]?.status&&delete o[t.payload.peerId]}},setPeerCoverStatus:(e,t)=>{const{roomId:n,peerId:r,status:a}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){const t=e[o];t.coverStatusByPeer??={},t.coverStatusByPeer[r]=a}},setPeerHandshakeStatus:(e,t)=>{const{roomId:n,peerId:r,status:a,reason:o,retryAfter:i}=t.payload,s=e.findIndex(e=>e.id===n);if(s>-1){const t=e[s];t.handshakeStatusByPeer??={},t.handshakeStatusByPeer[r]={status:a,reason:o,retryAfter:i}}},setChannel:(e,t)=>{const{roomId:n,label:r,peerId:a}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){const t=e[o].channels.findIndex(e=>e.label===r);if(t>-1){-1===e[o].channels[t].peerIds.findIndex(e=>e===a)&&e[o].channels[t].peerIds.push(a)}else e[o].channels.push({label:r,peerIds:[a]})}},deleteChannel:(e,t)=>{const{roomId:n,peerId:r,label:a}=t.payload,o=e.length;for(let t=0;t<o;t++)if(void 0===n||e[t].id===n)if(a&&!r){const n=e[t].channels.findIndex(e=>e.label===a);n>-1&&e[t].channels.splice(n,1)}else if(!a&&r)for(let n=e[t].channels.length-1;n>=0;n--){const a=e[t].channels[n].peerIds.findIndex(e=>e===r);a>-1&&(e[t].channels[n].peerIds.splice(a,1),0===e[t].channels[n].peerIds.length&&e[t].channels.splice(n,1))}else if(r&&a){const n=e[t].channels.findIndex(e=>e.label===a&&e.peerIds.includes(r));if(n>-1){const a=e[t].channels[n].peerIds.findIndex(e=>e===r);e[t].channels[n].peerIds.splice(a,1),0===e[t].channels[n].peerIds.length&&e[t].channels.splice(n,1)}}},setIceServers:(e,t)=>{const{roomId:n,iceServers:r}=t.payload,a=e.findIndex(e=>e.id===n);if(a>-1){const t=r.length,n=e[a].rtcConfig.iceServers?.flatMap(e=>Array.isArray(e.urls)?e.urls:[e.urls])??[];for(let o=0;o<t;o++){const t=r[o].urls.length;let i=!1;for(let e=0;e<t;e++)if(!n.includes(r[o].urls[e])){i=!0;break}i&&e[a].rtcConfig.iceServers?.push(r[o])}}},setMessage:(t,n)=>{const{roomId:r,transferId:a,merkleRootHex:o,sha512Hex:i,filename:s,channelLabel:c,fromPeerId:l,messageType:d,chunkSize:u,totalSize:h,chunksCreated:f,totalChunks:p,timestamp:m}=n.payload,y=t.findIndex(e=>e.id===r);if(y>-1){const n=t[y].messages.findLastIndex(e=>(void 0!==a?e.transferId===a:e.merkleRootHex===o)||void 0===a&&e.sha512Hex===i&&0===e.merkleRootHex.length);-1===n?c&&l&&e(l)&&d&&h&&t[y].messages.push({transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:c,filename:s.length>0?s:"txt",messageType:d,fromPeerId:l,timestamp:m??Date.now(),savedSize:u>0?u:0,totalSize:h,chunksCreated:f??0,totalChunks:p??0}):t[y].messages[n].timestamp!==m&&t[y].messages[n].sha512Hex===i&&t[y].messages[n].savedSize===t[y].messages[n].totalSize?t[y].messages.push({transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:c,filename:s.length>0?s:"txt",messageType:d,fromPeerId:l,timestamp:m??Date.now(),savedSize:u,totalSize:h,chunksCreated:f??0,totalChunks:p??0}):(o.length===2*N&&""===t[y].messages[n].merkleRootHex&&(t[y].messages[n].merkleRootHex=o),h>0&&t[y].messages[n].totalSize!==h&&(t[y].messages[n].totalSize=h),u>0&&t[y].messages[n].totalSize>=t[y].messages[n].savedSize+u&&(t[y].messages[n].savedSize+=u),f&&f<=t[y].messages[n].totalChunks&&(t[y].messages[n].chunksCreated=f+1))}},setMessageAllChunks:(t,n)=>{const{roomId:r,transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:s,filename:c,messageType:l,fromPeerId:d,timestamp:u,totalSize:h}=n.payload,f=t.findIndex(e=>e.id===r);if(f>-1){const n=t[f].messages.findLastIndex(e=>e.merkleRootHex===o);-1===n&&s&&d&&e(d)&&l&&h||n>-1&&t[f].messages[n].timestamp<u?t[f].messages.push({transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:s,filename:c.length>0?c:"txt",messageType:l,fromPeerId:d,timestamp:u,savedSize:h,totalSize:h,chunksCreated:0,totalChunks:0}):n>-1&&t[f].messages[n].savedSize!==h&&(t[f].messages[n].savedSize=h)}},deleteMessage:(e,t)=>{const{roomId:n,transferId:r,merkleRootHex:a,hashHex:o}=t.payload;if(!r&&!a&&!o)return;if(r&&!/^[0-9a-f]{64}$/.test(r))return;if(a&&a.length!==2*N)return;if(o&&o.length!==2*N)return;const i=e.findIndex(e=>e.id===n);if(-1!==i)if(r){const t=e[i].messages.findIndex(e=>e.transferId===r);t>-1&&e[i].messages.splice(t,1)}else if(a){const t=e[i].messages.findIndex(e=>e.merkleRootHex===a);t>-1&&e[i].messages.splice(t,1)}else if(o){const t=e[i].messages.findLastIndex(e=>e.sha512Hex===o);t>-1&&e[i].messages.splice(t,1)}},setOnlyConnectWithKnownPeers:(e,t)=>{const{roomId:n,onlyConnectWithKnownPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].onlyConnectWithKnownAddresses=r)},deleteRoom:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload||e.id===t.payload);if(n>-1){const t=e[n].url,r=e[n].policy;e[n]={url:t,id:"",connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:!0,onlyConnectWithKnownAddresses:!1,rtcConfig:We,policy:He(r),peers:[],channels:[],messages:[]}}},incrementMessageStats:(e,t)=>{const{roomId:n,merkleRootHex:r,sha512Hex:a,real:o,retransmit:i}=t.payload,s=e.findIndex(e=>e.id===n);if(s<0)return;const c=e[s].messages.findLastIndex(e=>void 0!==r&&e.merkleRootHex===r||void 0!==a&&e.sha512Hex===a);if(c<0)return;const l=e[s].messages[c];i?l.retransmits=(l.retransmits??0)+1:(l.chunksReceivedTotal=(l.chunksReceivedTotal??0)+1,o&&(l.chunksReceivedReal=(l.chunksReceivedReal??0)+1))}}}),{setRoom:Je,setRoomPolicy:Ye,setConnectingToPeers:Ze,setConnectedToPeers:et,setConnectionRelay:tt,setOnlyConnectWithKnownPeers:nt,setPeer:rt,setPeerCoverStatus:at,setPeerHandshakeStatus:ot,setChannel:it,setIceServers:st,setMessage:ct,setMessageAllChunks:lt,incrementMessageStats:dt,deletePeer:ut,deleteChannel:ht,deleteMessage:ft,deleteRoom:pt}=Ge.actions,mt=e=>e.rooms;var yt=Ge.reducer;const gt="wss://signaling.p2party.com/ws",wt=n({name:"signalingServer",initialState:{isEstablishingConnection:!1,isConnected:!1,isVerified:!1,serverUrl:gt},reducers:{startConnecting:(e,t)=>{e.isEstablishingConnection=!0,e.serverUrl=t.payload??gt},connectionEstablished:e=>{e.isConnected=!0,e.isEstablishingConnection=!1,e.isVerified=!1},connectionVerified:e=>{e.isConnected=!0,e.isEstablishingConnection=!1,e.isVerified=!0},disconnect:e=>{e.isConnected=!1,e.isEstablishingConnection=!1,e.isVerified=!1}}}),bt=wt.actions;var vt=wt.reducer;let kt=!1;kt=(()=>{try{return"1"===globalThis.localStorage?.getItem("p2party:debug")}catch{return!1}})();const It=e=>{kt=e},St=(...e)=>{kt&&console.log(...e)};var Ct=Symbol.for("immer-nothing"),At=Symbol.for("immer-draftable"),Et=Symbol.for("immer-state");function Pt(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var xt=Object,Kt=xt.getPrototypeOf,Rt="constructor",Mt="prototype",_t="configurable",Ut="enumerable",Dt="writable",Tt="value",Nt=e=>!!e&&!!e[Et];function qt(e){return!!e&&(Lt(e)||$t(e)||!!e[At]||!!e[Rt]?.[At]||Qt(e)||Wt(e))}var Ot=xt[Mt][Rt].toString(),Bt=new WeakMap;function Lt(e){if(!e||!Xt(e))return!1;const t=Kt(e);if(null===t||t===xt[Mt])return!0;const n=xt.hasOwnProperty.call(t,Rt)&&t[Rt];if(n===Object)return!0;if(!Gt(n))return!1;let r=Bt.get(n);return void 0===r&&(r=Function.toString.call(n),Bt.set(n,r)),r===Ot}function Ft(e,t,n=!0){if(0===zt(e)){(n?Reflect.ownKeys(e):xt.keys(e)).forEach(n=>{t(n,e[n],e)})}else e.forEach((n,r)=>t(r,n,e))}function zt(e){const t=e[Et];return t?t.type_:$t(e)?1:Qt(e)?2:Wt(e)?3:0}var jt=(e,t,n=zt(e))=>2===n?e.has(t):xt[Mt].hasOwnProperty.call(e,t),Ht=(e,t,n=zt(e))=>2===n?e.get(t):e[t],Vt=(e,t,n,r=zt(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n};var $t=Array.isArray,Qt=e=>e instanceof Map,Wt=e=>e instanceof Set,Xt=e=>"object"==typeof e,Gt=e=>"function"==typeof e,Jt=e=>"boolean"==typeof e;var Yt=e=>e.copy_||e.base_,Zt=e=>e.modified_?e.copy_:e.base_;function en(e,t){if(Qt(e))return new Map(e);if(Wt(e))return new Set(e);if($t(e))return Array[Mt].slice.call(e);const n=Lt(e);if(!0===t||"class_only"===t&&!n){const t=xt.getOwnPropertyDescriptors(e);delete t[Et];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const a=n[r],o=t[a];!1===o[Dt]&&(o[Dt]=!0,o[_t]=!0),(o.get||o.set)&&(t[a]={[_t]:!0,[Dt]:!0,[Ut]:o[Ut],[Tt]:e[a]})}return xt.create(Kt(e),t)}{const t=Kt(e);if(null!==t&&n)return{...e};const r=xt.create(t);return xt.assign(r,e)}}function tn(e,t=!1){return rn(e)||Nt(e)||!qt(e)||(zt(e)>1&&xt.defineProperties(e,{set:nn,add:nn,clear:nn,delete:nn}),xt.freeze(e),t&&Ft(e,(e,t)=>{tn(t,!0)},!1)),e}var nn={[Tt]:function(){Pt(2)}};function rn(e){return null===e||!Xt(e)||xt.isFrozen(e)}var an="MapSet",on="Patches",sn="ArrayMethods",cn={};function ln(e){const t=cn[e];return t||Pt(0),t}var dn,un=e=>!!cn[e];var hn=()=>dn;function fn(e,t){t&&(e.patchPlugin_=ln(on),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function pn(e){mn(e),e.drafts_.forEach(gn),e.drafts_=null}function mn(e){e===dn&&(dn=e.parent_)}var yn=e=>dn={drafts_:[],parent_:dn,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:un(an)?ln(an):void 0,arrayMethodsPlugin_:un(sn)?ln(sn):void 0};function gn(e){const t=e[Et];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function wn(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[Et].modified_&&(pn(t),Pt(4)),qt(e)&&(e=bn(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[Et].base_,e,t)}else e=bn(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&tn(t,n)}(t,e,!0),pn(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ct?e:void 0}function bn(e,t){if(rn(t))return t;const n=t[Et];if(!n){return An(t,e.handledSet_,e)}if(!kn(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:t}=n;if(t)for(;t.length>0;){t.pop()(e)}Cn(n,e)}return n.copy_}function vn(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var kn=(e,t)=>e.scope_===t,In=[];function Sn(e,t,n,r){const a=Yt(e),o=e.type_;if(void 0!==r){if(Ht(a,r,o)===t)return void Vt(a,r,n,o)}if(!e.draftLocations_){const t=e.draftLocations_=new Map;Ft(a,(e,n)=>{if(Nt(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const i=e.draftLocations_.get(t)??In;for(const e of i)Vt(a,e,n,o)}function Cn(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||1===e.type_&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){const{patchPlugin_:n}=t;if(n){const r=n.getPath(e);r&&n.generatePatches_(e,r,t)}vn(e)}}function An(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||Nt(e)||t.has(e)||!qt(e)||rn(e)||(t.add(e),Ft(e,(r,a)=>{if(Nt(a)){const t=a[Et];if(kn(t,n)){const n=Zt(t);Vt(e,r,n,e.type_),vn(t)}}else qt(a)&&An(a,t,n)})),e}var En={get(e,t){if(t===Et)return e;let n=e.scope_.arrayMethodsPlugin_;const r=1===e.type_&&"string"==typeof t;if(r&&n?.isArrayOperationMethod(t))return n.createMethodInterceptor(e,t);const a=Yt(e);if(!jt(a,t,e.type_))return function(e,t,n){const r=Kn(t,n);return r?Tt in r?r[Tt]:r.get?.call(e.draft_):void 0}(e,a,t);const o=a[t];if(e.finalized_||!qt(o))return o;if(r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&function(e){const t=+e;return Number.isInteger(t)&&String(t)===e}(t))return o;if(o===xn(e.base_,t)||function(e,t,n){if(1!==e.type_||!e.allIndicesReassigned_||e.assigned_?.get(t)||!qt(n)||n[Et])return!1;return e.baseRefs_.has(n)}(e,t,o)){Mn(e);const n=1===e.type_?+t:t,r=_n(e.scope_,o,e,n);return e.copy_[n]=r}return o},has:(e,t)=>t in Yt(e),ownKeys:e=>Reflect.ownKeys(Yt(e)),set(e,t,n){const r=Kn(Yt(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=xn(Yt(e),t),i=r?.[Et];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(((a=n)===(o=r)?0!==a||1/a==1/o:a!=a&&o!=o)&&(void 0!==n||jt(e.base_,t,e.type_)))return!0;Mn(e),Rn(e)}var a,o;return e.copy_[t]===n&&(void 0!==n||jt(e.copy_,t,e.type_))||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),function(e,t,n){const{scope_:r}=e;if(Nt(n)){const a=n[Et];kn(a,r)&&a.callbacks_.push(function(){Mn(e);const r=Zt(a);Sn(e,n,r,t)})}else qt(n)&&e.callbacks_.push(function(){const a=Yt(e);3===e.type_?a.has(n)&&An(n,r.handledSet_,r):Ht(a,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&An(Ht(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(Mn(e),void 0!==xn(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),Rn(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Yt(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[Dt]:!0,[_t]:1!==e.type_||"length"!==t,[Ut]:r[Ut],[Tt]:n[t]}:r},defineProperty(){Pt(11)},getPrototypeOf:e=>Kt(e.base_),setPrototypeOf(){Pt(12)}},Pn={};for(let e in En){let t=En[e];Pn[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function xn(e,t){const n=e[Et];return(n?Yt(n):e)[t]}function Kn(e,t){if(!(t in e))return;let n=Kt(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=Kt(n)}}function Rn(e){e.modified_||(e.modified_=!0,e.parent_&&Rn(e.parent_))}function Mn(e){e.copy_||(e.assigned_=new Map,e.copy_=en(e.base_,e.scope_.immer_.useStrictShallowCopy_))}Pn.deleteProperty=function(e,t){return Pn.set.call(this,e,t,void 0)},Pn.set=function(e,t,n){return En.set.call(this,e[0],t,n,e[0])};function _n(e,t,n,r){const[a,o]=Qt(t)?ln(an).proxyMap_(t,n):Wt(t)?ln(an).proxySet_(t,n):function(e,t){const n=$t(e),r={type_:n?1:0,scope_:t?t.scope_:hn(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=r,o=En;n&&(a=[r],o=Pn);const{revoke:i,proxy:s}=Proxy.revocable(a,o);return r.draft_=s,r.revoke_=i,[s,r]}(t,n);return(n?.scope_??hn()).drafts_.push(a),o.callbacks_=n?.callbacks_??[],o.key_=r,n&&void 0!==r?function(e,t,n){e.callbacks_.push(function(r){const a=t;if(!a||!kn(a,r))return;r.mapSetPlugin_?.fixSetContents(a);const o=Zt(a);Sn(e,a.draft_??a,o,n),Cn(a,r)})}(n,o,r):o.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(o);const{patchPlugin_:t}=e;o.modified_&&t&&t.generatePatches_(o,[],e)}),a}function Un(e){return Nt(e)||Pt(10),Dn(e)}function Dn(e){if(!qt(e)||rn(e))return e;const t=e[Et];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=en(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=en(e,!0);return Ft(n,(e,t)=>{Vt(n,e,Dn(t))},r),t&&(t.finalized_=!1),n}function Tn(){const e="replace",t="add",n="remove";function r(e){if(!qt(e))return e;if($t(e))return e.map(r);if(Qt(e))return new Map(Array.from(e.entries()).map(([e,t])=>[e,r(t)]));if(Wt(e))return new Set(Array.from(e).map(r));const t=Object.create(Kt(e));for(const n in e)t[n]=r(e[n]);return jt(e,At)&&(t[At]=e[At]),t}function a(e){return Nt(e)?r(e):e}var o,i;i={applyPatches_:function(a,o){return o.forEach(o=>{const{path:i,op:s}=o;let c=a;for(let e=0;e<i.length-1;e++){const t=zt(c);let n=i[e];"string"!=typeof n&&"number"!=typeof n&&(n=""+n),0!==t&&1!==t||"__proto__"!==n&&n!==Rt||Pt(19),Gt(c)&&n===Mt&&Pt(19),c=Ht(c,n),null!==c&&Xt(c)||Pt(18,i.join("/"))}const l=zt(c),d=r(o.value),u=i[i.length-1];switch(s){case e:switch(l){case 2:return c.set(u,d);case 3:Pt(16);default:return c[u]=d}case t:switch(l){case 1:return"-"===u?c.push(d):c.splice(u,0,d);case 2:return c.set(u,d);case 3:return c.add(d);default:return c[u]=d}case n:switch(l){case 1:return c.splice(u,1);case 2:return c.delete(u);case 3:return c.delete(o.value);default:return delete c[u]}default:Pt(17)}}),a},generatePatches_:function(r,o,i){if(r.scope_.processedForPatches_.has(r))return;r.scope_.processedForPatches_.add(r);const{patches_:s,inversePatches_:c}=i;switch(r.type_){case 0:case 2:return function(r,o,i,s){const{base_:c,copy_:l,type_:d}=r;Ft(r.assigned_,(r,u)=>{const h=Ht(c,r,d),f=Ht(l,r,d),p=u?jt(c,r)?e:t:n;if(h===f&&p===e)return;const m=o.concat(r);i.push(p===n?{op:p,path:m}:{op:p,path:m,value:a(f)}),s.push(p===t?{op:n,path:m}:p===n?{op:t,path:m,value:a(h)}:{op:e,path:m,value:a(h)})})}(r,o,s,c);case 1:return function(r,o,i,s){let{base_:c,assigned_:l}=r,d=r.copy_;d.length<c.length&&([c,d]=[d,c],[i,s]=[s,i]);const u=!0===r.allIndicesReassigned_;for(let t=0;t<c.length;t++){const n=d[t],r=c[t];if((u||l?.get(t.toString()))&&n!==r){const c=n?.[Et];if(c&&c.modified_)continue;const l=o.concat([t]);i.push({op:e,path:l,value:a(n)}),s.push({op:e,path:l,value:a(r)})}}for(let e=c.length;e<d.length;e++){const n=o.concat([e]);i.push({op:t,path:n,value:a(d[e])})}for(let e=d.length-1;c.length<=e;--e){const t=o.concat([e]);s.push({op:n,path:t})}}(r,o,s,c);case 3:return function(e,r,a,o){let{base_:i,copy_:s}=e,c=0;i.forEach(e=>{if(!s.has(e)){const i=r.concat([c]);a.push({op:n,path:i,value:e}),o.unshift({op:t,path:i,value:e})}c++}),c=0,s.forEach(e=>{if(!i.has(e)){const i=r.concat([c]);a.push({op:t,path:i,value:e}),o.unshift({op:n,path:i,value:e})}c++})}(r,o,s,c)}},generateReplacementPatches_:function(t,n,r){const{patches_:a,inversePatches_:o}=r;a.push({op:e,path:[],value:n===Ct?void 0:n}),o.push({op:e,path:[],value:t})},getPath:function e(t,n=[]){if(void 0!==t.key_){const e=t.parent_.copy_??t.parent_.base_,a=(r=Ht(e,t.key_),Xt(r)?r?.[Et]:null),o=Ht(e,t.key_);if(void 0===o)return null;if(o!==t.draft_&&o!==t.base_&&o!==t.copy_)return null;if(null!=a&&a.base_!==t.base_)return null;const i=3===t.parent_.type_;let s;if(i){const e=t.parent_;s=Array.from(e.drafts_.keys()).indexOf(t.key_)}else s=t.key_;if(!(i&&e.size>s||jt(e,s)))return null;n.push(s)}var r;if(t.parent_)return e(t.parent_,n);n.reverse();try{!function(e,t){let n=e;for(let e=0;e<t.length-1;e++){const r=t[e];if(n=Ht(n,r),!Xt(n)||null===n)throw new Error(`Cannot resolve path at '${t.join("/")}'`)}}(t.copy_,n)}catch(e){return null}return n}},cn[o=on]||(cn[o]=i)}var Nn=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(Gt(e)&&!Gt(t)){const n=t;t=e;const r=this;return function(e=n,...a){return r.produce(e,e=>t.call(this,e,...a))}}let r;if(Gt(t)||Pt(6),void 0===n||Gt(n)||Pt(7),qt(e)){const a=yn(this),o=_n(a,e,void 0);let i=!0;try{r=t(o),i=!1}finally{i?pn(a):mn(a)}return fn(a,n),wn(r,a)}if(!e||!Xt(e)){if(r=t(e),void 0===r&&(r=e),r===Ct&&(r=void 0),this.autoFreeze_&&tn(r,!0),n){const t=[],a=[];ln(on).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:a}),n(t,a)}return r}Pt(1)},this.produceWithPatches=(e,t)=>{if(Gt(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},Jt(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),Jt(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),Jt(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){qt(e)||Pt(8),Nt(e)&&(e=Un(e));const t=yn(this),n=_n(t,e,void 0);return n[Et].isManual_=!0,mn(t),n}finishDraft(e,t){const n=e&&e[Et];n&&n.isManual_||Pt(9);const{scope_:r}=n;return fn(r,t),wn(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const r=t[n];if(0===r.path.length&&"replace"===r.op){e=r.value;break}}n>-1&&(t=t.slice(n+1));const r=ln(on).applyPatches_;return Nt(e)?r(e,t):this.produce(e,e=>r(e,t))}};Nn.produce;var qn=Nn.produceWithPatches.bind(Nn),On=Nn.applyPatches.bind(Nn),Bn=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}};var Ln=e=>Array.isArray(e)?e:[e];function Fn(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(e=>"function"==typeof e)){const n=e.map(e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e).join(", ");throw new TypeError(`${t}[${n}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}var zn="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function jn(){return{s:0,v:void 0,o:null,p:null}}function Hn(e,t={}){let n={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:r}=t;let a,o=0;function i(){let t=n;const{length:i}=arguments;for(let e=0,n=i;e<n;e++){const n=arguments[e];if("function"==typeof n||"object"==typeof n&&null!==n){let e=t.o;null===e&&(t.o=e=new WeakMap);const r=e.get(n);void 0===r?(t=jn(),e.set(n,t)):t=r}else{let e=t.p;null===e&&(t.p=e=new Map);const r=e.get(n);void 0===r?(t=jn(),e.set(n,t)):t=r}}const s=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),o++,r){const e=a?.deref?.()??a;null!=e&&r(e,c)&&(c=e,0!==o&&o--);a="object"==typeof c&&null!==c||"function"==typeof c?new zn(c):c}return s.s=1,s.v=c,c}return i.clearCache=()=>{n={s:0,v:void 0,o:null,p:null},i.resetResultsCount()},i.resultsCount=()=>o,i.resetResultsCount=()=>{o=0},i}function Vn(e,...t){const n="function"==typeof e?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t,r=0,a=0,o={},i=e.pop();"object"==typeof i&&(o=i,i=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(i,`createSelector expects an output function after the inputs, but received: [${typeof i}]`);const s={...n,...o},{memoize:c,memoizeOptions:l=[],argsMemoize:d=Hn,argsMemoizeOptions:u=[]}=s,h=Ln(l),f=Ln(u),p=Fn(e),m=c(function(){return r++,i.apply(null,arguments)},...h),y=d(function(){a++;const e=function(e,t){const n=[],{length:r}=e;for(let a=0;a<r;a++)n.push(e[a].apply(null,t));return n}(p,arguments);return t=m.apply(null,e),t},...f);return Object.assign(y,{resultFunc:i,memoizedResultFunc:m,dependencies:p,dependencyRecomputations:()=>a,resetDependencyRecomputations:()=>{a=0},lastResult:()=>t,recomputations:()=>r,resetRecomputations:()=>{r=0},memoize:c,argsMemoize:d})};return Object.assign(r,{withTypes:()=>r}),r}var $n=Vn(Hn),Qn=Object.assign((e,t=$n)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const n=Object.keys(e),r=n.map(t=>e[t]);return t(r,(...e)=>e.reduce((e,t,r)=>(e[n[r]]=t,e),{}))},{withTypes:()=>Qn}),Wn="uninitialized",Xn="pending",Gn="fulfilled",Jn="rejected";function Yn(e){return{status:e,isUninitialized:e===Wn,isLoading:e===Xn,isSuccess:e===Gn,isError:e===Jn}}var Zn=f;function er(e,t){if(e===t||!(Zn(e)&&Zn(t)||Array.isArray(e)&&Array.isArray(t)))return t;const n=Object.keys(t),r=Object.keys(e);let a=n.length===r.length;const o=Array.isArray(t)?[]:{};for(const r of n)o[r]=er(e[r],t[r]),a&&(a=e[r]===o[r]);return a?e:o}function tr(e,t,n){return e.reduce((e,r,a)=>(t(r,a)&&e.push(n(r,a)),e),[]).flat()}function nr(e){return null!=e}function rr(e){return[...e?.values()??[]].filter(nr)}function ar(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var or=()=>new Map,ir=class{constructor(e,t=void 0){this.value=e,this.meta=t}value;meta},sr="__rtkq/",cr="focused",lr=i(`${sr}${cr}`),dr=i(`${sr}un${cr}`),ur=i(`${sr}online`),hr=i(`${sr}offline`),fr="query",pr="mutation",mr="infinitequery";function yr(e){return e.type===fr}function gr(e){return e.type===mr}function wr(e){return yr(e)||gr(e)}function br(e,t,n,r,a,o){const i="function"==typeof e?e(t,n,r,a):e;return i?tr(i,nr,e=>o(vr(e))):[]}function vr(e){return"string"==typeof e?{type:e}:e}var kr=(e,t)=>e.endpointDefinitions[t],Ir=Symbol("forceQueryFn"),Sr=e=>"function"==typeof e[Ir];var Cr=class extends Bn{constructor(e,t,n,r){super(e),this.value=t,this.schemaName=n,this._bqMeta=r}value;schemaName;_bqMeta},Ar=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function Er(e,t,n,r){const a=await e["~standard"].validate(t);if(a.issues)throw new Cr(a.issues,t,n,r);return a.value}function Pr(e){return e}var xr=(e={})=>({...e,[p]:!0});function Kr(e,{pages:t,pageParams:n},r){const a=t.length-1;return e.getNextPageParam(t[a],t,n[a],n,r)}function Rr(e,{pages:t,pageParams:n},r){return e.getPreviousPageParam?.(t[0],t,n[0],n,r)}function Mr(e,t,n,r){return br(n[e.meta.arg.endpointName][t],d(e)?e.payload:void 0,u(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,r)}function _r(e){return Nt(e)?Un(e):e}function Ur(e,t,n){const r=e[t];r&&n(r)}function Dr(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function Tr(e,t,n){const r=e[Dr(t)];r&&n(r)}var Nr={};function qr({reducerPath:e,queryThunk:t,mutationThunk:a,serializeQueryArgs:o,context:{endpointDefinitions:s,apiUid:f,extractRehydrationInfo:m,hasRehydrationInfo:y},assertTagType:g,config:w}){const v=i(`${e}/resetApiState`);function k(e,t,n,r){e[t.queryCacheKey]??={status:Wn,endpointName:t.endpointName},Ur(e,t.queryCacheKey,e=>{e.status=Xn,e.requestId=n&&e.requestId?e.requestId:r.requestId,void 0!==t.originalArgs&&(e.originalArgs=t.originalArgs),e.startedTimeStamp=r.startedTimeStamp;gr(s[r.arg.endpointName])&&"direction"in t&&(e.direction=t.direction)})}function I(e,t,n,r){Ur(e,t.arg.queryCacheKey,e=>{if(e.requestId!==t.requestId&&!r)return;const{merge:a}=s[t.arg.endpointName];if(e.status=Gn,a)if(void 0!==e.data){const{fulfilledTimeStamp:r,arg:o,baseQueryMeta:i,requestId:s}=t;let c=b(e.data,e=>a(e,n,{arg:o.originalArgs,baseQueryMeta:i,fulfilledTimeStamp:r,requestId:s}));e.data=c}else e.data=n;else e.data=s[t.arg.endpointName].structuralSharing??1?er(Nt(e.data)?(o=e.data,Nt(o)||Pt(15),o[Et].base_):e.data,n):n;var o;delete e.error,e.fulfilledTimeStamp=t.fulfilledTimeStamp})}const S=n({name:`${e}/queries`,initialState:Nr,reducers:{removeQueryResult:{reducer(e,{payload:{queryCacheKey:t}}){delete e[t]},prepare:c()},cacheEntriesUpserted:{reducer(e,t){for(const n of t.payload){const{queryDescription:r,value:a}=n;k(e,r,!0,{arg:r,requestId:t.meta.requestId,startedTimeStamp:t.meta.timestamp}),I(e,{arg:r,requestId:t.meta.requestId,fulfilledTimeStamp:t.meta.timestamp,baseQueryMeta:{}},a,!0)}},prepare:e=>({payload:e.map(e=>{const{endpointName:t,arg:n,value:r}=e,a=s[t];return{queryDescription:{type:fr,endpointName:t,originalArgs:e.arg,queryCacheKey:o({queryArgs:n,endpointDefinition:a,endpointName:t})},value:r}}),meta:{[p]:!0,requestId:r(),timestamp:Date.now()}})},queryResultPatched:{reducer(e,{payload:{queryCacheKey:t,patches:n}}){Ur(e,t,e=>{e.data=On(e.data,n.concat())})},prepare:c()}},extraReducers(e){e.addCase(t.pending,(e,{meta:t,meta:{arg:n}})=>{k(e,n,Sr(n),t)}).addCase(t.fulfilled,(e,{meta:t,payload:n})=>{I(e,t,n,Sr(t.arg))}).addCase(t.rejected,(e,{meta:{condition:t,arg:n,requestId:r},error:a,payload:o})=>{Ur(e,n.queryCacheKey,e=>{if(t);else{if(e.requestId!==r)return;e.status=Jn,e.error=o??a}})}).addMatcher(y,(e,t)=>{const{queries:n}=m(t);for(const[t,r]of Object.entries(n))r?.status!==Gn&&r?.status!==Jn||(e[t]=r)})}}),C=n({name:`${e}/mutations`,initialState:Nr,reducers:{removeMutationResult:{reducer(e,{payload:t}){const n=Dr(t);n in e&&delete e[n]},prepare:c()}},extraReducers(e){e.addCase(a.pending,(e,{meta:t,meta:{requestId:n,arg:r,startedTimeStamp:a}})=>{r.track&&(e[Dr(t)]={requestId:n,status:Xn,endpointName:r.endpointName,startedTimeStamp:a})}).addCase(a.fulfilled,(e,{payload:t,meta:n})=>{n.arg.track&&Tr(e,n,e=>{e.requestId===n.requestId&&(e.status=Gn,e.data=t,e.fulfilledTimeStamp=n.fulfilledTimeStamp)})}).addCase(a.rejected,(e,{payload:t,error:n,meta:r})=>{r.arg.track&&Tr(e,r,e=>{e.requestId===r.requestId&&(e.status=Jn,e.error=t??n)})}).addMatcher(y,(e,t)=>{const{mutations:n}=m(t);for(const[t,r]of Object.entries(n))r?.status!==Gn&&r?.status!==Jn||t===r?.requestId||(e[t]=r)})}}),A=n({name:`${e}/invalidation`,initialState:{tags:{},keys:{}},reducers:{updateProvidedBy:{reducer(e,t){for(const{queryCacheKey:n,providedTags:r}of t.payload){E(e,n);for(const{type:t,id:a}of r){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];r.includes(n)||r.push(n)}e.keys[n]=r}},prepare:c()}},extraReducers(e){e.addCase(S.actions.removeQueryResult,(e,{payload:{queryCacheKey:t}})=>{E(e,t)}).addMatcher(y,(e,t)=>{const{provided:n}=m(t);for(const[t,r]of Object.entries(n.tags??{}))for(const[a,o]of Object.entries(r)){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];for(const t of o){r.includes(t)||r.push(t),e.keys[t]=n.keys[t]}}}).addMatcher(l(d(t),u(t)),(e,t)=>{P(e,[t])}).addMatcher(S.actions.cacheEntriesUpserted.match,(e,t)=>{P(e,t.payload.map(({queryDescription:e,value:t})=>({type:"UNKNOWN",payload:t,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:e}})))})}});function E(e,t){const n=_r(e.keys[t]??[]);for(const r of n){const n=r.type,a=r.id??"__internal_without_id",o=e.tags[n]?.[a];o&&(e.tags[n][a]=_r(o).filter(e=>e!==t))}delete e.keys[t]}function P(e,t){const n=t.map(e=>{const t=Mr(e,"providesTags",s,g),{queryCacheKey:n}=e.meta.arg;return{queryCacheKey:n,providedTags:t}});A.caseReducers.updateProvidedBy(e,A.actions.updateProvidedBy(n))}const x=n({name:`${e}/subscriptions`,initialState:Nr,reducers:{updateSubscriptionOptions(e,t){},unsubscribeQueryResult(e,t){},internal_getRTKQSubscriptions(){}}}),K=n({name:`${e}/internalSubscriptions`,initialState:Nr,reducers:{subscriptionsUpdated:{reducer:(e,t)=>On(e,t.payload),prepare:c()}}}),R=n({name:`${e}/config`,initialState:{online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine,focused:"undefined"==typeof document||"hidden"!==document.visibilityState,middlewareRegistered:!1,...w},reducers:{middlewareRegistered(e,{payload:t}){e.middlewareRegistered="conflict"!==e.middlewareRegistered&&f===t||"conflict"}},extraReducers:e=>{e.addCase(ur,e=>{e.online=!0}).addCase(hr,e=>{e.online=!1}).addCase(lr,e=>{e.focused=!0}).addCase(dr,e=>{e.focused=!1}).addMatcher(y,e=>({...e}))}}),M=h({queries:S.reducer,mutations:C.reducer,provided:A.reducer,subscriptions:K.reducer,config:R.reducer});return{reducer:(e,t)=>M(v.match(t)?void 0:e,t),actions:{...R.actions,...S.actions,...x.actions,...K.actions,...C.actions,...A.actions,resetApiState:v}}}var Or=Symbol.for("RTKQ/skipToken"),Br={status:Wn},Lr=b(Br,()=>{}),Fr=b(Br,()=>{});var zr=WeakMap?new WeakMap:void 0,jr=({endpointName:e,queryArgs:t})=>{let n="";const r=zr?.get(t);if("string"==typeof r)n=r;else{const e=JSON.stringify(t,(e,t)=>(t="bigint"==typeof t?{$bigint:t.toString()}:t,t=f(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t));f(t)&&zr?.set(t,e),n=e}return`${e}(${n})`};function Hr(...e){return function(t){const n=Hn(e=>t.extractRehydrationInfo?.(e,{reducerPath:t.reducerPath??"api"})),o={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...t,extractRehydrationInfo:n,serializeQueryArgs(e){let n=jr;if("serializeQueryArgs"in e.endpointDefinition){const t=e.endpointDefinition.serializeQueryArgs;n=e=>{const n=t(e);return"string"==typeof n?n:jr({...e,queryArgs:n})}}else t.serializeQueryArgs&&(n=t.serializeQueryArgs);return n(e)},tagTypes:[...t.tagTypes||[]]},i={endpointDefinitions:{},batch(e){e()},apiUid:r(),extractRehydrationInfo:n,hasRehydrationInfo:Hn(e=>null!=n(e))},s={injectEndpoints:function(e){const t=e.endpoints({query:e=>({...e,type:fr}),mutation:e=>({...e,type:pr}),infiniteQuery:e=>({...e,type:mr})});for(const[n,r]of Object.entries(t))if(!0!==e.overrideExisting&&n in i.endpointDefinitions){if("throw"===e.overrideExisting)throw new Error(a(39))}else{i.endpointDefinitions[n]=r;for(const e of c)e.injectEndpoint(n,r)}return s},enhanceEndpoints({addTagTypes:e,endpoints:t}){if(e)for(const t of e)o.tagTypes.includes(t)||o.tagTypes.push(t);if(t)for(const[e,n]of Object.entries(t))"function"==typeof n?n(kr(i,e)):Object.assign(kr(i,e)||{},n);return s}},c=e.map(e=>e.init(s,o,i));return s.injectEndpoints({endpoints:t.endpoints})}}function Vr(e,...t){return Object.assign(e,...t)}var $r=({api:e,queryThunk:t,internalState:n,mwApi:r})=>{const a=`${e.reducerPath}/subscriptions`;let o=null,i=null;const{updateSubscriptionOptions:s,unsubscribeQueryResult:c}=e.internalActions,l=()=>n.currentSubscriptions,d={getSubscriptions:l,getSubscriptionCount:e=>{const t=l().get(e);return t?.size??0},isRequestSubscribed:(e,t)=>{const n=l();return!!n?.get(e)?.get(t)}};function u(e){return JSON.parse(JSON.stringify(Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)]))))}return(r,l)=>{if(o||(o=u(n.currentSubscriptions)),e.util.resetApiState.match(r))return o={},n.currentSubscriptions.clear(),i=null,[!0,!1];if(e.internalActions.internal_getRTKQSubscriptions.match(r))return[!1,d];const h=((n,r)=>{if(s.match(r)){const{queryCacheKey:e,requestId:t,options:a}=r.payload,o=n.get(e);return o?.has(t)&&o.set(t,a),!0}if(c.match(r)){const{queryCacheKey:e,requestId:t}=r.payload,a=n.get(e);return a&&a.delete(t),!0}if(e.internalActions.removeQueryResult.match(r))return n.delete(r.payload.queryCacheKey),!0;if(t.pending.match(r)){const{meta:{arg:e,requestId:t}}=r,a=ar(n,e.queryCacheKey,or);return e.subscribe&&a.set(t,e.subscriptionOptions??a.get(t)??{}),!0}let a=!1;if(t.rejected.match(r)){const{meta:{condition:e,arg:t,requestId:o}}=r;if(e&&t.subscribe){const e=ar(n,t.queryCacheKey,or);e.set(o,t.subscriptionOptions??e.get(o)??{}),a=!0}}return a})(n.currentSubscriptions,r);let f=!0;if(h){i||(i=setTimeout(()=>{const t=u(n.currentSubscriptions),[,r]=qn(o,()=>t);l.next(e.internalActions.subscriptionsUpdated(r)),o=t,i=null},500));const s="string"==typeof r.type&&!!r.type.startsWith(a),c=t.rejected.match(r)&&r.meta.condition&&!!r.meta.arg.subscribe;f=!s&&!c}return[f,!1]}},Qr=({reducerPath:e,api:t,queryThunk:n,context:r,internalState:a,selectors:{selectQueryEntry:o,selectConfig:i},getRunningQueryThunk:s,mwApi:c})=>{const{removeQueryResult:d,unsubscribeQueryResult:u,cacheEntriesUpserted:h}=t.internalActions,f=l(u.match,n.fulfilled,n.rejected,h.match);function p(e){const t=a.currentSubscriptions.get(e);if(!t)return!1;return t.size>0}const m={};function y(e){for(const t of e.values())t?.abort?.()}function g(e,t,n){const r=t.getState();for(const a of e){const e=o(r,a);e?.endpointName&&w(a,e.endpointName,t,n)}}function w(e,t,n,a){const i=kr(r,t),c=i?.keepUnusedDataFor??a.keepUnusedDataFor;if(c===1/0)return;const l=Math.max(0,Math.min(c,2147482.647));if(!p(e)){const t=m[e];t&&clearTimeout(t),m[e]=setTimeout(()=>{if(!p(e)){const t=o(n.getState(),e);if(t?.endpointName){const e=n.dispatch(s(t.endpointName,t.originalArgs));e?.abort()}n.dispatch(d({queryCacheKey:e}))}delete m[e]},1e3*l)}}return(e,n)=>{const o=n.getState(),s=i(o);if(f(e)){let t;if(h.match(e))t=e.payload.map(e=>e.queryDescription.queryCacheKey);else{const{queryCacheKey:n}=u.match(e)?e.payload:e.meta.arg;t=[n]}g(t,n,s)}if(t.util.resetApiState.match(e)){for(const[e,t]of Object.entries(m))t&&clearTimeout(t),delete m[e];y(a.runningQueries),y(a.runningMutations)}if(r.hasRehydrationInfo(e)){const{queries:t}=r.extractRehydrationInfo(e);g(Object.keys(t),n,s)}}},Wr=new Error("Promise never resolved before cacheEntryRemoved."),Xr=({api:e,reducerPath:t,context:n,queryThunk:r,mutationThunk:a,internalState:o,selectors:{selectQueryEntry:i,selectApiState:s}})=>{const c=v(r),l=v(a),u=d(r,a),h={},{removeQueryResult:f,removeMutationResult:p,cacheEntriesUpserted:m}=e.internalActions;function y(e,t,n){const r=h[e];r?.valueResolved&&(r.valueResolved({data:t,meta:n}),delete r.valueResolved)}function g(e){const t=h[e];t&&(delete h[e],t.cacheEntryRemoved())}function w(e){const{arg:t,requestId:n}=e.meta,{endpointName:r,originalArgs:a}=t;return[r,a,n]}function b(t,r,a,o,i){const s=kr(n,t),c=s?.onCacheEntryAdded;if(!c)return;const l={},d=new Promise(e=>{l.cacheEntryRemoved=e}),u=Promise.race([new Promise(e=>{l.valueResolved=e}),d.then(()=>{throw Wr})]);u.catch(()=>{}),h[a]=l;const f=e.endpoints[t].select(wr(s)?r:a),p=o.dispatch((e,t,n)=>n),m={...o,getCacheEntry:()=>f(o.getState()),requestId:i,extra:p,updateCachedData:wr(s)?n=>o.dispatch(e.util.updateQueryData(t,r,n)):void 0,cacheDataLoaded:u,cacheEntryRemoved:d},y=c(r,m);Promise.resolve(y).catch(e=>{if(e!==Wr)throw e})}return(n,o,s)=>{const d=function(e){if(c(e))return e.meta.arg.queryCacheKey;if(l(e))return e.meta.arg.fixedCacheKey??e.meta.requestId;return f.match(e)?e.payload.queryCacheKey:p.match(e)?Dr(e.payload):""}(n);function v(e,t,n,r){const a=i(s,t),c=i(o.getState(),t);!a&&c&&b(e,r,t,o,n)}if(r.pending.match(n)){const[e,t,r]=w(n);v(e,d,r,t)}else if(m.match(n))for(const{queryDescription:e,value:t}of n.payload){const{endpointName:r,originalArgs:a,queryCacheKey:o}=e;v(r,o,n.meta.requestId,a),y(o,t,{})}else if(a.pending.match(n)){if(o.getState()[t].mutations[d]){const[e,t,r]=w(n);b(e,t,d,o,r)}}else if(u(n))y(d,n.payload,n.meta.baseQueryMeta);else if(f.match(n)||p.match(n))g(d);else if(e.util.resetApiState.match(n))for(const e of Object.keys(h))g(e)}},Gr=({api:e,context:{apiUid:t},reducerPath:n})=>(n,r)=>{e.util.resetApiState.match(n)&&r.dispatch(e.internalActions.middlewareRegistered(t))},Jr=({reducerPath:e,context:t,context:{endpointDefinitions:n},mutationThunk:r,queryThunk:a,api:o,assertTagType:i,refetchQuery:s,internalState:c})=>{const{removeQueryResult:h}=o.internalActions,f=l(d(r),u(r)),p=l(d(a,r),y(a,r));let m=[],g=0;function w(n,r){const a=r.getState(),i=a[e];if(m.push(...n),"delayed"===i.config.invalidationBehavior&&g>0)return;const l=m;if(m=[],0===l.length)return;const d=o.util.selectInvalidatedBy(a,l);t.batch(()=>{const e=Array.from(d.values());for(const{queryCacheKey:t}of e){const e=i.queries[t],n=ar(c.currentSubscriptions,t,or);e&&(0===n.size?r.dispatch(h({queryCacheKey:t})):e.status!==Wn&&r.dispatch(s(e)))}})}return(e,t)=>{(a.pending.match(e)||r.pending.match(e))&&g++,p(e)&&(g=Math.max(0,g-1)),f(e)?w(Mr(e,"invalidatesTags",n,i),t):p(e)?w([],t):o.util.invalidateTags.match(e)&&w(br(e.payload,void 0,void 0,void 0,void 0,i),t)}},Yr=({reducerPath:e,queryThunk:t,api:n,refetchQuery:r,internalState:a})=>{const{currentPolls:o,currentSubscriptions:i}=a,s=new Set;let c=null;function l(e,t){s.add(e),c||(c=setTimeout(()=>{for(const e of s)u({queryCacheKey:e},t);s.clear(),c=null},0))}function d({queryCacheKey:t},n){const a=n.getState()[e],s=a.queries[t],c=i.get(t);if(!s||s.status===Wn)return;const{lowestPollingInterval:l,skipPollingIfUnfocused:u}=f(c);if(!Number.isFinite(l))return;const h=o.get(t);h?.timeout&&(clearTimeout(h.timeout),h.timeout=void 0);const p=Date.now()+l;o.set(t,{nextPollTimestamp:p,pollingInterval:l,timeout:setTimeout(()=>{!a.config.focused&&u||n.dispatch(r(s)),d({queryCacheKey:t},n)},l)})}function u({queryCacheKey:t},n){const r=n.getState()[e].queries[t],a=i.get(t);if(!r||r.status===Wn)return;const{lowestPollingInterval:s}=f(a);if(!Number.isFinite(s))return void h(t);const c=o.get(t),l=Date.now()+s;(!c||l<c.nextPollTimestamp)&&d({queryCacheKey:t},n)}function h(e){const t=o.get(e);t?.timeout&&clearTimeout(t.timeout),o.delete(e)}function f(e=new Map){let t=!1,n=Number.POSITIVE_INFINITY;for(const r of e.values())r.pollingInterval&&(n=Math.min(r.pollingInterval,n),t=r.skipPollingIfUnfocused||t);return{lowestPollingInterval:n,skipPollingIfUnfocused:t}}return(e,r)=>{(n.internalActions.updateSubscriptionOptions.match(e)||n.internalActions.unsubscribeQueryResult.match(e))&&l(e.payload.queryCacheKey,r),(t.pending.match(e)||t.rejected.match(e)&&e.meta.condition)&&l(e.meta.arg.queryCacheKey,r),(t.fulfilled.match(e)||t.rejected.match(e)&&!e.meta.condition)&&d(e.meta.arg,r),n.util.resetApiState.match(e)&&(!function(){for(const e of o.keys())h(e)}(),c&&(clearTimeout(c),c=null),s.clear())}},Zr=({api:e,context:t,queryThunk:n,mutationThunk:r})=>{const a=g(n,r),o=y(n,r),i=d(n,r),s={};return(n,r)=>{if(a(n)){const{requestId:a,arg:{endpointName:o,originalArgs:i}}=n.meta,c=kr(t,o),l=c?.onQueryStarted;if(l){const t={},n=new Promise((e,n)=>{t.resolve=e,t.reject=n});n.catch(()=>{}),s[a]=t;const d=e.endpoints[o].select(wr(c)?i:a),u=r.dispatch((e,t,n)=>n),h={...r,getCacheEntry:()=>d(r.getState()),requestId:a,extra:u,updateCachedData:wr(c)?t=>r.dispatch(e.util.updateQueryData(o,i,t)):void 0,queryFulfilled:n};l(i,h)}}else if(i(n)){const{requestId:e,baseQueryMeta:t}=n.meta;s[e]?.resolve({data:n.payload,meta:t}),delete s[e]}else if(o(n)){const{requestId:e,rejectedWithValue:t,baseQueryMeta:r}=n.meta;s[e]?.reject({error:n.payload??n.error,isUnhandledError:!t,meta:r}),delete s[e]}}};function ea(e){const{reducerPath:t,queryThunk:n,api:r,context:a,getInternalState:o}=e,{apiUid:s}=a,c={invalidateTags:i(`${t}/invalidateTags`)},l=e=>e.type.startsWith(`${t}/`),d=[Gr,Qr,Jr,Yr,Xr,Zr];return{middleware:n=>{let i=!1;const c=o(n.dispatch),h={...e,internalState:c,refetchQuery:u,isThisApiSliceAction:l,mwApi:n},f=d.map(e=>e(h)),p=$r(h),m=(({reducerPath:e,context:t,api:n,refetchQuery:r,internalState:a})=>{const{removeQueryResult:o}=n.internalActions;function i(n,i){const s=n.getState()[e],c=s.queries,l=a.currentSubscriptions;t.batch(()=>{for(const e of l.keys()){const t=c[e],a=l.get(e);if(!a||!t)continue;const d=[...a.values()];(d.some(e=>!0===e[i])||d.every(e=>void 0===e[i])&&s.config[i])&&(0===a.size?n.dispatch(o({queryCacheKey:e})):t.status!==Wn&&n.dispatch(r(t)))}})}return(e,t)=>{lr.match(e)&&i(t,"refetchOnFocus"),ur.match(e)&&i(t,"refetchOnReconnect")}})(h);return e=>o=>{if(!w(o))return e(o);i||(i=!0,n.dispatch(r.internalActions.middlewareRegistered(s)));const c={...n,next:e},d=n.getState(),[u,h]=p(o,c,d);let y;if(y=u?e(o):h,n.getState()[t]&&(m(o,c,d),l(o)||a.hasRehydrationInfo(o)))for(const e of f)e(o,c,d);return y}},actions:c};function u(t){return e.api.endpoints[t.endpointName].initiate(t.originalArgs,{subscribe:!1,forceRefetch:!0})}}var ta=Symbol(),na=Hr((({createSelector:e=o}={})=>({name:ta,init(t,{baseQuery:n,tagTypes:r,reducerPath:a,serializeQueryArgs:o,keepUnusedDataFor:i,refetchOnMountOrArgChange:c,refetchOnFocus:l,refetchOnReconnect:u,invalidationBehavior:h,onSchemaFailure:f,catchSchemaFailure:p,skipSchemaValidation:w},b){Tn();const v=e=>e;Object.assign(t,{reducerPath:a,endpoints:{},internalActions:{onOnline:ur,onOffline:hr,onFocus:lr,onFocusLost:dr},util:{}});const k=function({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=e=>Lr,a=e=>Fr;return{buildQuerySelector:function(e,t){return l(e,t,o)},buildInfiniteQuerySelector:function(e,t){const{infiniteQueryOptions:n}=t;return l(e,t,function(e){const t={...e,...Yn(e.status)},{isLoading:r,isError:a,direction:o}=t,i="forward"===o,s="backward"===o;return{...t,hasNextPage:d(n,t.data,t.originalArgs),hasPreviousPage:u(n,t.data,t.originalArgs),isFetchingNextPage:r&&i,isFetchingPreviousPage:r&&s,isFetchNextPageError:a&&i,isFetchPreviousPageError:a&&s}})},buildMutationSelector:function(){return e=>{let t;return t="object"==typeof e?Dr(e)??Or:e,n(t===Or?a:e=>i(e)?.mutations?.[t]??Fr,o)}},selectInvalidatedBy:function(e,n){const r=e[t],a=new Set,o=tr(n,nr,vr);for(const e of o){const t=r.provided.tags[e.type];if(!t)continue;let n=(void 0!==e.id?t[e.id]:Object.values(t).flat())??[];for(const e of n)a.add(e)}return Array.from(a.values()).flatMap(e=>{const t=r.queries[e];return t?{queryCacheKey:e,endpointName:t.endpointName,originalArgs:t.originalArgs}:[]})},selectCachedArgsForQuery:function(e,t){return tr(Object.values(s(e)),e=>e?.endpointName===t&&e.status!==Wn,e=>e.originalArgs)},selectApiState:i,selectQueries:s,selectMutations:function(e){return i(e)?.mutations},selectQueryEntry:c,selectConfig:function(e){return i(e)?.config}};function o(e){return{...e,...Yn(e.status)}}function i(e){return e[t]}function s(e){return i(e)?.queries}function c(e,t){return s(e)?.[t]}function l(t,a,o){return i=>{if(i===Or)return n(r,o);const s=e({queryArgs:i,endpointDefinition:a,endpointName:t});return n(e=>c(e,s)??Lr,o)}}function d(e,t,n){return!!t&&null!=Kr(e,t,n)}function u(e,t,n){return!(!t||!e.getPreviousPageParam)&&null!=Rr(e,t,n)}}({serializeQueryArgs:o,reducerPath:a,createSelector:e}),{selectInvalidatedBy:I,selectCachedArgsForQuery:S,buildQuerySelector:C,buildInfiniteQuerySelector:A,buildMutationSelector:E}=k;Vr(t.util,{selectInvalidatedBy:I,selectCachedArgsForQuery:S});const{queryThunk:P,infiniteQueryThunk:x,mutationThunk:K,patchQueryData:R,updateQueryData:M,upsertQueryData:_,prefetch:U,buildMatchThunkActions:D}=function({reducerPath:e,baseQuery:t,context:{endpointDefinitions:n},serializeQueryArgs:r,api:a,assertTagType:o,selectors:i,onSchemaFailure:c,catchSchemaFailure:l,skipSchemaValidation:u}){function h(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}function f(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}const p=(e,t)=>e.query&&e[t]?e[t]:Pr,w=async(e,{signal:r,abort:a,rejectWithValue:o,fulfillWithValue:s,dispatch:d,getState:m,extra:y})=>{const g=n[e.endpointName],{metaSchema:w,skipSchemaValidation:v=u}=g,k=e.type===fr;try{let I=Pr;const S={signal:r,abort:a,dispatch:d,getState:m,extra:y,endpoint:e.endpointName,type:e.type,forced:k?b(e,m()):void 0,queryCacheKey:k?e.queryCacheKey:void 0},C=k?e[Ir]:void 0;let A;const E=async(t,n,r,a)=>{if(null==n&&t.pages.length)return Promise.resolve({data:t});const o={queryArg:e.originalArgs,pageParam:n},i=await P(o),s=a?h:f;return{data:{pages:s(t.pages,i.data,r),pageParams:s(t.pageParams,n,r)},meta:i.meta}};async function P(e){let n;const{extraOptions:r,argSchema:a,rawResponseSchema:o,responseSchema:i}=g;if(a&&!Ar(v,"arg")&&(e=await Er(a,e,"argSchema",{})),C?n=C():g.query?(I=p(g,"transformResponse"),n=await t(g.query(e),S,r)):n=await g.queryFn(e,S,r,e=>t(e,S,r)),n.error)throw new ir(n.error,n.meta);let{data:s}=n;o&&!Ar(v,"rawResponse")&&(s=await Er(o,n.data,"rawResponseSchema",n.meta));let c=await I(s,n.meta,e);return i&&!Ar(v,"response")&&(c=await Er(i,c,"responseSchema",n.meta)),{...n,data:c}}if(k&&"infiniteQueryOptions"in g){const{infiniteQueryOptions:x}=g,{maxPages:K=1/0}=x,R=e.refetchCachedPages??x.refetchCachedPages??!0;let M;const _={pages:[],pageParams:[]},U=i.selectQueryEntry(m(),e.queryCacheKey)?.data,D=b(e,m())&&!e.direction||!U?_:U;if("direction"in e&&e.direction&&D.pages.length){const T="backward"===e.direction,N=(T?Rr:Kr)(x,D,e.originalArgs);M=await E(D,N,K,T)}else{const{initialPageParam:q=x.initialPageParam}=e,O=U?.pageParams??[],B=O[0]??q,L=O.length;if(M=await E(D,B,K),C&&(M={data:M.data.pages[0]}),R)for(let F=1;F<L;F++){const z=Kr(x,M.data,e.originalArgs);M=await E(M.data,z,K)}}A=M}else A=await P(e.originalArgs);return w&&!Ar(v,"meta")&&A.meta&&(A.meta=await Er(w,A.meta,"metaSchema",A.meta)),s(A.data,xr({fulfilledTimeStamp:Date.now(),baseQueryMeta:A.meta}))}catch(j){let H=j;if(H instanceof ir){let V=p(g,"transformErrorResponse");const{rawErrorResponseSchema:$,errorResponseSchema:Q}=g;let{value:W,meta:X}=H;try{$&&!Ar(v,"rawErrorResponse")&&(W=await Er($,W,"rawErrorResponseSchema",X)),w&&!Ar(v,"meta")&&(X=await Er(w,X,"metaSchema",X));let G=await V(W,X,e.originalArgs);return Q&&!Ar(v,"errorResponse")&&(G=await Er(Q,G,"errorResponseSchema",X)),o(G,xr({baseQueryMeta:X}))}catch(J){H=J}}try{if(H instanceof Cr){const Y={endpoint:e.endpointName,arg:e.originalArgs,type:e.type,queryCacheKey:k?e.queryCacheKey:void 0};g.onSchemaFailure?.(H,Y),c?.(H,Y);const{catchSchemaFailure:Z=l}=g;if(Z)return o(Z(H,Y),xr({baseQueryMeta:H._bqMeta}))}}catch(ee){H=ee}throw console.error(H),H}};function b(e,t){const n=i.selectQueryEntry(t,e.queryCacheKey),r=i.selectConfig(t).refetchOnMountOrArgChange,a=n?.fulfilledTimeStamp,o=e.forceRefetch??(e.subscribe&&r);return!!o&&(!0===o||(Number(new Date)-Number(a))/1e3>=o)}const v=()=>s(`${e}/executeQuery`,w,{getPendingMeta({arg:e}){const t=n[e.endpointName];return xr({startedTimeStamp:Date.now(),...gr(t)?{direction:e.direction}:{}})},condition(e,{getState:t}){const r=t(),a=i.selectQueryEntry(r,e.queryCacheKey),o=a?.fulfilledTimeStamp,s=e.originalArgs,c=a?.originalArgs,l=n[e.endpointName],d=e.direction;return!(!Sr(e)&&("pending"===a?.status||!b(e,r)&&(!yr(l)||!l?.forceRefetch?.({currentArg:s,previousArg:c,endpointState:a,state:r}))&&o&&!d))},dispatchConditionRejection:!0}),k=v(),I=v(),S=s(`${e}/executeMutation`,w,{getPendingMeta:()=>xr({startedTimeStamp:Date.now()})});function C(e){return t=>t?.meta?.arg?.endpointName===e}return{queryThunk:k,mutationThunk:S,infiniteQueryThunk:I,prefetch:(e,t,n={})=>(r,o)=>{const i=(e=>"force"in e)(n)&&n.force,s=(e=>"ifOlderThan"in e)(n)&&n.ifOlderThan,c=(n=!0)=>{const r={forceRefetch:n,subscribe:!1};return a.endpoints[e].initiate(t,r)},l=a.endpoints[e].select(t)(o());if(i)r(c());else if(s){const e=l?.fulfilledTimeStamp;if(!e)return void r(c());(Number(new Date)-Number(new Date(e)))/1e3>=s&&r(c())}else r(c(!1))},updateQueryData:(e,t,n,r=!0)=>(o,i)=>{const s=a.endpoints[e].select(t)(i()),c={patches:[],inversePatches:[],undo:()=>o(a.util.patchQueryData(e,t,c.inversePatches,r))};if(s.status===Wn)return c;let l;if("data"in s)if(qt(s.data)){const[e,t,r]=qn(s.data,n);c.patches.push(...t),c.inversePatches.push(...r),l=e}else l=n(s.data),c.patches.push({op:"replace",path:[],value:l}),c.inversePatches.push({op:"replace",path:[],value:s.data});return 0===c.patches.length||o(a.util.patchQueryData(e,t,c.patches,r)),c},upsertQueryData:(e,t,n)=>r=>r(a.endpoints[e].initiate(t,{subscribe:!1,forceRefetch:!0,[Ir]:()=>({data:n})})),patchQueryData:(e,t,i,s)=>(c,l)=>{const d=n[e],u=r({queryArgs:t,endpointDefinition:d,endpointName:e});if(c(a.internalActions.queryResultPatched({queryCacheKey:u,patches:i})),!s)return;const h=a.endpoints[e].select(t)(l()),f=br(d.providesTags,h.data,void 0,t,{},o);c(a.internalActions.updateProvidedBy([{queryCacheKey:u,providedTags:f}]))},buildMatchThunkActions:function(e,t){return{matchPending:m(g(e),C(t)),matchFulfilled:m(d(e),C(t)),matchRejected:m(y(e),C(t))}}}}({baseQuery:n,reducerPath:a,context:b,api:t,serializeQueryArgs:o,assertTagType:v,selectors:k,onSchemaFailure:f,catchSchemaFailure:p,skipSchemaValidation:w}),{reducer:T,actions:N}=qr({context:b,queryThunk:P,mutationThunk:K,serializeQueryArgs:o,reducerPath:a,assertTagType:v,config:{refetchOnFocus:l,refetchOnReconnect:u,refetchOnMountOrArgChange:c,keepUnusedDataFor:i,reducerPath:a,invalidationBehavior:h}});Vr(t.util,{patchQueryData:R,updateQueryData:M,upsertQueryData:_,prefetch:U,resetApiState:N.resetApiState,upsertQueryEntries:N.cacheEntriesUpserted}),Vr(t.internalActions,N);const q=new WeakMap,O=e=>ar(q,e,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:B,buildInitiateInfiniteQuery:L,buildInitiateMutation:F,getRunningMutationThunk:z,getRunningMutationsThunk:j,getRunningQueriesThunk:H,getRunningQueryThunk:V}=function({serializeQueryArgs:e,queryThunk:t,infiniteQueryThunk:n,mutationThunk:r,api:a,context:o,getInternalState:i}){const s=e=>i(e)?.runningQueries,c=e=>i(e)?.runningMutations,{unsubscribeQueryResult:l,removeMutationResult:d,updateSubscriptionOptions:u}=a.internalActions;return{buildInitiateQuery:function(e,t){return h(e,t)},buildInitiateInfiniteQuery:function(e,t){return h(e,t)},buildInitiateMutation:function(e){return(t,{track:n=!0,fixedCacheKey:a}={})=>(o,i)=>{const s=r({type:"mutation",endpointName:e,originalArgs:t,track:n,fixedCacheKey:a}),l=o(s),{requestId:u,abort:h,unwrap:f}=l,p=(m=e=>({error:e}),l.unwrap().then(e=>({data:e})).catch(m));var m;const y=Object.assign(p,{arg:l.arg,requestId:u,abort:h,unwrap:f,reset:()=>{o(d({requestId:u,fixedCacheKey:a}))}}),g=c(o);return g.set(u,y),y.then(()=>{g.delete(u)}),a&&(g.set(a,y),y.then(()=>{g.get(a)===y&&g.delete(a)})),y}},getRunningQueryThunk:function(t,n){return r=>{const a=kr(o,t),i=e({queryArgs:n,endpointDefinition:a,endpointName:t});return s(r)?.get(i)}},getRunningMutationThunk:function(e,t){return e=>c(e)?.get(t)},getRunningQueriesThunk:function(){return e=>rr(s(e))},getRunningMutationsThunk:function(){return e=>rr(c(e))}};function h(r,o){const i=(c,{subscribe:d=!0,forceRefetch:h,subscriptionOptions:f,[Ir]:p,...m}={})=>(y,g)=>{const w=e({queryArgs:c,endpointDefinition:o,endpointName:r});let b;const v={...m,type:fr,subscribe:d,forceRefetch:h,subscriptionOptions:f,endpointName:r,originalArgs:c,queryCacheKey:w,[Ir]:p};if(yr(o))b=t(v);else{const{direction:e,initialPageParam:t,refetchCachedPages:r}=m;b=n({...v,direction:e,initialPageParam:t,refetchCachedPages:r})}const k=a.endpoints[r].select(c),I=y(b),S=k(g()),{requestId:C,abort:A}=I,E=S.requestId!==C,P=s(y)?.get(w),x=()=>k(g()),K=Object.assign(p?I.then(x):E&&!P?Promise.resolve(S):Promise.all([P,I]).then(x),{arg:c,requestId:C,subscriptionOptions:f,queryCacheKey:w,abort:A,async unwrap(){const e=await K;if(e.isError)throw e.error;return e.data},refetch:e=>y(i(c,{subscribe:!1,forceRefetch:!0,...e})),unsubscribe(){d&&y(l({queryCacheKey:w,requestId:C}))},updateSubscriptionOptions(e){K.subscriptionOptions=e,y(u({endpointName:r,requestId:C,queryCacheKey:w,options:e}))}});if(!P&&!E&&!p){const e=s(y);e.set(w,K),K.then(()=>{e.delete(w)})}return K};return i}}({queryThunk:P,mutationThunk:K,infiniteQueryThunk:x,api:t,serializeQueryArgs:o,context:b,getInternalState:O});Vr(t.util,{getRunningMutationThunk:z,getRunningMutationsThunk:j,getRunningQueryThunk:V,getRunningQueriesThunk:H});const{middleware:$,actions:Q}=ea({reducerPath:a,context:b,queryThunk:P,mutationThunk:K,infiniteQueryThunk:x,api:t,assertTagType:v,selectors:k,getRunningQueryThunk:V,getInternalState:O});return Vr(t.util,Q),Vr(t,{reducer:T,middleware:$}),{name:ta,injectEndpoint(e,n){const r=t,a=r.endpoints[e]??={};yr(n)&&Vr(a,{name:e,select:C(e,n),initiate:B(e,n)},D(P,e)),n.type===pr&&Vr(a,{name:e,select:E(),initiate:F(e)},D(K,e)),gr(n)&&Vr(a,{name:e,select:A(e,n),initiate:L(e,n)},D(P,e))}}}}))());const ra="0123456789abcdef",aa=new Array(64),oa=new Array(128),ia=e=>new Promise(t=>{let n=0;const r=e.length;for(let t=0;t<r;t++)n+=e[t].length;const a=new Uint8Array(n);let o=0;for(const t of e)a.set(t,o),o+=t.length;t(a)}),sa=(e,t)=>new Promise(n=>{const r=e.length;if(r!==t.length)return void n(!1);let a=0;for(let n=0;n<r;n++)a|=e[n]^t[n];n(0===a)}),ca=e=>{const t=e.length,n=t===N?oa:32===t?aa:new Array(2*t);let r=0;for(let a=0;a<t;a++){const t=e[a];n[r++]=ra[t>>4],n[r++]=ra[15&t]}return n.join("")},la=e=>{if(0===(e=e.replace(/^0x/,"")).length)throw new Error("No hex characters in string");const t=/[^0-9a-f]/i.exec(e);if(t)throw new Error(`Found non-hex characters ${t[0]}`);e.length%2!=0&&(e="0"+e);const n=e.match(/[\dA-F]{2}/gi);if(!n)throw new Error("No hex characters in string");const r=n.length,a=new Uint8Array(r);for(let e=0;e<r;e++)a[e]=parseInt(n[e],16);return a},da=(e,t,n)=>{t=t??32,n=n??16384;const r=65536,a=Math.ceil((e+1048576)/r);if(a>n)throw new Error(`Memory required is ${String(a*r)} bytes while declared maximum is ${String(n*r)} bytes`);return a<t?t:a};var ua=()=>{const e=(L+F)*Uint8Array.BYTES_PER_ELEMENT,t=da(e);return new WebAssembly.Memory({initial:t,maximum:t})},ha=()=>{const e=(X+G)*Uint8Array.BYTES_PER_ELEMENT,t=da(e);return new WebAssembly.Memory({initial:t,maximum:t})},fa=()=>{const e=(L+F+B)*Uint8Array.BYTES_PER_ELEMENT,t=da(e);return new WebAssembly.Memory({initial:t,maximum:t})},pa=e=>{const t=(e+O+F+N)*Uint8Array.BYTES_PER_ELEMENT,n=da(t);return new WebAssembly.Memory({initial:n,maximum:n})},ma=e=>{const t=(e+O+L)*Uint8Array.BYTES_PER_ELEMENT,n=da(t);return new WebAssembly.Memory({initial:n,maximum:n})},ya=()=>{const e=da(0);return new WebAssembly.Memory({initial:e,maximum:e})},ga=e=>{const t=da((2*e+3)*N);return new WebAssembly.Memory({initial:t,maximum:t})},wa=e=>{const t=da(e*N+e*(N+1)+3*N);return new WebAssembly.Memory({initial:t,maximum:t})},ba=e=>{const t=(78643200+e+B+V)*Uint8Array.BYTES_PER_ELEMENT,n=da(t);return new WebAssembly.Memory({initial:n,maximum:n})};function va(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ka,Ia={exports:{}};var Sa=(ka||(ka=1,function(e){var t,n=(t=globalThis.document?.currentScript?.src,async function(e={}){var n=e,r=!!globalThis.window,a=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process,a&&(t=self.location.href);var o,i,s="";if(r||a){try{s=new URL(".",t).href}catch{}a&&(i=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),o=async e=>{var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)}}console.log.bind(console);var c,l=console.error.bind(console),d=!1;function u(e,t,n){const r=e.BYTES_PER_ELEMENT,a=t*r;if(t<=0&&I(`segmentation fault ${n} ${r} bytes at address ${a}`),v){var o=U(0);a+r>o&&I(`segmentation fault, exceeded the top of the available dynamic heap when ${n} ${r} bytes at address ${a}. DYNAMICTOP=${o}`),o<D()&&I(`brk >= _emscripten_stack_get_base() (brk=${o}, _emscripten_stack_get_base()=${D()})`),o>b.buffer.byteLength&&I(`brk <= wasmMemory.buffer.byteLength (brk=${o}, wasmMemory.buffer.byteLength=${b.buffer.byteLength})`)}return t}var h,f,p,m,y,g,w,b,v=!1;function k(){if(!m?.buffer?.resizable){var e=b.buffer;m=new Int8Array(e),w=new Uint8Array(e),f=new Int32Array(e),g=new Uint32Array(e),y=new Float64Array(e),p=new BigInt64Array(e),new BigUint64Array(e)}}function I(e){throw l(e=`Aborted(${e})`),d=!0,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}function S(){return s+"libcrypto.wasm"}async function C(e){if(!c)try{var t=await o(e);return new Uint8Array(t)}catch{}return function(e){if(e==h&&c)return new Uint8Array(c);if(i)return i(e);throw"both async and sync fetching of the wasm failed"}(e)}async function A(e,t,n){if(!e)try{var r=fetch(t,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(r,n)}catch(e){l(`wasm streaming compile failed: ${e}`),l("falling back to ArrayBuffer instantiation")}return async function(e,t){try{var n=await C(e);return await WebAssembly.instantiate(n,t)}catch(e){l(`failed to asynchronously prepare wasm: ${e}`),I(e)}}(t,n)}var E=globalThis.TextDecoder&&new TextDecoder,P=(e,t,n)=>e?((e,t=0,n)=>{var r=((e,t,n)=>{for(var r=t+n;e[t]&&!(t>=r);)++t;return t})(e,t,n);if(r-t>16&&e.buffer&&E)return E.decode(e.subarray(t,r));for(var a="";t<r;){var o=e[t++];if(128&o){var i=63&e[t++];if(192!=(224&o)){var s=63&e[t++];if((o=224==(240&o)?(15&o)<<12|i<<6|s:(7&o)<<18|i<<12|s<<6|63&e[t++])<65536)a+=String.fromCharCode(o);else{var c=o-65536;a+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else a+=String.fromCharCode((31&o)<<6|i)}else a+=String.fromCharCode(o)}return a})(w,e,t):"",x=[],K=(e,t,n)=>{var r=((e,t)=>{var n;for(x.length=0;n=w[u(w,e++,"loading")];){var r=105!=n;t+=(r&=112!=n)&&t%8?4:0,x.push(112==n?g[u(g,t>>2,"loading")]:106==n?p[u(p,t>>3,"loading")]:105==n?f[u(f,t>>2,"loading")]:y[u(y,t>>3,"loading")]),t+=r?8:4}return x})(t,n);return N[e](...r)},R=e=>{I("OOM")},M=(e,t)=>Math.ceil(e/t)*t,_=e=>{var t=(e-b.buffer.byteLength+65535)/65536|0;try{return b.grow(t),k(),1}catch(e){}};!function(){if(n.wasmMemory)b=n.wasmMemory;else{var e=n.INITIAL_MEMORY||2097152;b=new WebAssembly.Memory({initial:e/65536,maximum:16384})}k()}(),n.wasmBinary&&(c=n.wasmBinary);var U,D,T,N={38164:()=>n.getRandomValue(),38200:()=>{if(void 0===n.getRandomValue)try{var e="object"==typeof window?window:self,t=void 0!==e.crypto?e.crypto:e.msCrypto;t=void 0===t?a:t;var r=function(){var e=new Uint32Array(1);return t.getRandomValues(e),e[0]>>>0};r(),n.getRandomValue=r}catch(e){try{var a=require("crypto"),o=function(){var e=a.randomBytes(4);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0};o(),n.getRandomValue=o}catch(e){throw"No secure random number generator found"}}}},q={e:(e,t,n,r)=>I(`Assertion failed: ${P(e)}, at: `+[t?P(t):"unknown filename",n,r?P(r):"unknown function"]),g:()=>I(""),c:function(){I("alignment fault")},d:(e,t,n)=>K(e,t,n),f:e=>{var t=w.length,n=1073741824;(e>>>=0)>n&&R();for(var r=1;r<=4;r*=2){var a=t*(1+.2/r);a=Math.min(a,e+100663296);var o=Math.min(n,M(Math.max(e,a),65536));if(_(o))return!0}R()},a:b,b:function(){I("segmentation fault")}};return T=await async function(){function e(e){return function(e){n._crypto_init=e.i,n._argon2=e.j,n._keypair_from_seed=e.k,n._keypair_from_secret_key=e.l,n._sign=e.m,n._verify=e.n,n._get_merkle_root=e.o,n._get_merkle_proof=e.p,n._get_merkle_root_from_proof=e.q,n._verify_merkle_proof=e.r,n._cpace_ristretto255_from_hash=e.s,n._cpace_ristretto255_scalarmult=e.t,n._cpace_ristretto255_scalar_random=e.u,n._x25519_keypair=e.v,n._x25519_dh=e.w,n._hkdf_sha512_extract=e.x,n._hkdf_sha512_expand=e.y,n._encrypt_chachapoly_symmetric=e.z,n._decrypt_chachapoly_symmetric=e.A,n._receive_message_with_key=e.B,n._sha512_init=e.C,n._sha512_update=e.D,n._sha512_final=e.E,n._mlkem512_keypair=e.F,n._mlkem512_encaps=e.G,n._mlkem512_decaps=e.H,n._mlkem768_keypair=e.I,n._mlkem768_encaps=e.J,n._mlkem768_decaps=e.K,n._mlkem1024_keypair=e.L,n._mlkem1024_encaps=e.M,n._mlkem1024_decaps=e.N,n._free=e.O,n._malloc=e.P,U=e.Q,D=e.R,e.__indirect_function_table}(T=e.exports),T}var t={a:q};h??=S();var r=function(t){return e(t.instance)}(await A(c,h,t));return r}(),await async function(){d||(v=!0,T.h())}(),n});e.exports=n,e.exports.default=n}(Ia)),Ia.exports),Ca=va(Sa);const Aa=new Uint32Array(1),Ea=()=>{const e=globalThis.crypto;if("function"!=typeof e?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");try{return e.getRandomValues(Aa),Aa[0]>>>0}finally{Aa[0]=0}},Pa=(e,t=e=>{const t=globalThis.crypto;if("function"!=typeof t?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");t.getRandomValues(e)})=>{if(!(e instanceof Uint8Array))throw new TypeError("random: destination must be a Uint8Array");const n=new Uint8Array(e.byteLength);try{t(n),e.set(n)}finally{n.fill(0)}};if("object"!=typeof WebAssembly)throw new Error("no native wasm support detected");const xa="0.14.2";let Ka=new URL(`https://cdn.p2party.com/@${xa}/libcrypto.wasm`),Ra=!1;const Ma={integrity:"sha384-pBMyUqQ3KBztxgeJMgDFZeohfj9QlAFNwt4/gRlqT0vlZ2kbkKxv+q5DwbZOBuUP"},_a=e=>{if(Ra)throw new Error("WASM source cannot change after cryptography has loaded");const t=e instanceof URL?new URL(e.href):new URL(e);if("https:"!==t.protocol&&"http:"!==t.protocol)throw new TypeError("WASM source must use http: or https:");Ka=t},Ua=async e=>{Ra=!0;const t=await(async()=>{const e=await fetch(Ka,Ma);if(!e.ok)throw new Error(`Unable to load p2party ${xa} WASM: HTTP ${String(e.status)}`);return await e.arrayBuffer()})();return await Ca({wasmBinary:t,wasmMemory:e,getRandomValue:Ea})},Da=(e,t)=>{t.fill(0),e._free(t.byteOffset)},Ta=async e=>{const t=e?.wasmMemory??ua(),n=e??await Ua(t),r=n._malloc(L),a=new Uint8Array(t.buffer,r,L),o=n._malloc(F),i=new Uint8Array(t.buffer,o,F),s=n._malloc(B),c=new Uint8Array(t.buffer,s,B);try{Pa(c);if(0!==n._keypair_from_seed(a.byteOffset,i.byteOffset,c.byteOffset))throw new Error("An unexpected error occured.");return{publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(i)}}finally{n._free(r),Da(n,i),Da(n,c)}},Na=async(e,t,n)=>{if(t.length!==F)throw new Error(`Ed25519 secret key must be ${String(F)} bytes`);const r=e.length,a=n?n.wasmMemory:pa(r),o=n??await Ua(a),i=o._malloc(Math.max(r*Uint8Array.BYTES_PER_ELEMENT,1)),s=new Uint8Array(a.buffer,i,r*Uint8Array.BYTES_PER_ELEMENT);s.set(e);const c=o._malloc(O),l=new Uint8Array(a.buffer,c,O),d=o._malloc(F),u=new Uint8Array(a.buffer,d,F);u.set(t);try{if(0!==o._sign(r,s.byteOffset,u.byteOffset,l.byteOffset))throw new Error("Could not sign with Ed25519");return Uint8Array.from(l)}finally{o._free(i),o._free(c),Da(o,u)}},qa=async(e,t,n,r)=>{const a=e.length,o=r?r.wasmMemory:ma(a),i=r??await Ua(o),s=i._malloc(a*Uint8Array.BYTES_PER_ELEMENT),c=new Uint8Array(o.buffer,s,a*Uint8Array.BYTES_PER_ELEMENT);c.set(e);const l=i._malloc(O),d=new Uint8Array(o.buffer,l,O);d.set(t);const u=i._malloc(L),h=new Uint8Array(o.buffer,u,L);h.set(n);const f=i._verify(a,c.byteOffset,h.byteOffset,d.byteOffset);return i._free(s),i._free(l),i._free(u),0===f},Oa=/^[0-9a-f]{64}$/,Ba=e=>"string"==typeof e&&Oa.test(e),La=(e,t="Ed25519 identity")=>{if(!Ba(e))throw new Error(`${t} must be 32-byte lowercase hexadecimal`)},Fa=(e,t)=>{if(La(e,"Self Ed25519 identity"),La(t,"Peer Ed25519 identity"),e===t)throw new Error("Cannot assign a protocol role to the same Ed25519 identity");return e<t},za='const e=(e,t)=>t.some(t=>e instanceof t);let t,a;const n=new WeakMap,r=new WeakMap,o=new WeakMap;let i={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return n.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return d(e[t])},set:(e,t,a)=>(e[t]=a,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function s(e){i=e(i)}function c(e){return(a||(a=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(u(this),t),d(this.request)}:function(...t){return d(e.apply(u(this),t))}}function l(a){return"function"==typeof a?c(a):(a instanceof IDBTransaction&&function(e){if(n.has(e))return;const t=new Promise((t,a)=>{const n=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",o),e.removeEventListener("abort",o)},r=()=>{t(),n()},o=()=>{a(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",r),e.addEventListener("error",o),e.addEventListener("abort",o)});n.set(e,t)}(a),e(a,t||(t=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(a,i):a)}function d(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,a)=>{const n=()=>{e.removeEventListener("success",r),e.removeEventListener("error",o)},r=()=>{t(d(e.result)),n()},o=()=>{a(e.error),n()};e.addEventListener("success",r),e.addEventListener("error",o)});return o.set(t,e),t}(e);if(r.has(e))return r.get(e);const t=l(e);return t!==e&&(r.set(e,t),o.set(t,e)),t}const u=e=>o.get(e);const h=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],w=new Map;function g(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,r=y.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!r&&!h.includes(a))return;const o=async function(e,...t){const o=this.transaction(e,r?"readwrite":"readonly");let i=o.store;return n&&(i=i.index(t.shift())),(await Promise.all([i[a](...t),r&&o.done]))[0]};return w.set(t,o),o}s(e=>({...e,get:(t,a,n)=>g(t,a)||e.get(t,a,n),has:(t,a)=>!!g(t,a)||e.has(t,a)}));const f=["continue","continuePrimaryKey","advance"],m={},p=new WeakMap,b=new WeakMap,k={get(e,t){if(!f.includes(t))return e[t];let a=m[t];return a||(a=m[t]=function(...e){p.set(this,b.get(this)[t](...e))}),a}};async function*S(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const a=new Proxy(t,k);for(b.set(a,t),o.set(a,u(t));t;)yield a,t=await(p.get(a)||t.continue()),p.delete(a)}function I(t,a){return a===Symbol.asyncIterator&&e(t,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===a&&e(t,[IDBIndex,IDBObjectStore])}s(e=>({...e,get:(t,a,n)=>I(t,a)?S:e.get(t,a,n),has:(t,a)=>I(t,a)||e.has(t,a)}));const x=64*Uint8Array.BYTES_PER_ELEMENT,K=65405-(9+x+8+8+256+8+8+8+(4+48*(x+1)));(new TextEncoder).encode("p2party-x25519-idsig-v1");const v=["hybrid-3dh-mlkem512-cpace21-v4","hybrid-3dh-mlkem768-cpace21-v4","hybrid-3dh-mlkem1024-cpace21-v4"],C="p2party-reassembled",R="p2party";async function A(){return function(e,t,{blocked:a,upgrade:n,blocking:r,terminated:o}={}){const i=indexedDB.open(e,t),s=d(i);return n&&i.addEventListener("upgradeneeded",e=>{n(d(i.result),e.oldVersion,e.newVersion,d(i.transaction),e)}),a&&i.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),s.then(e=>{o&&e.addEventListener("close",()=>o()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}(R,19,{upgrade(e,t,a,n){if(e.objectStoreNames.contains("addressBook")){const e=n.objectStore("addressBook");e.indexNames.contains("username")||e.createIndex("username","username",{unique:!1}),e.indexNames.contains("peerId")||e.createIndex("peerId","peerId",{unique:!0}),e.indexNames.contains("peerPublicKey")||e.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}else{const t=e.createObjectStore("addressBook",{keyPath:["peerId"]});t.createIndex("username","username",{unique:!1}),t.createIndex("peerId","peerId",{unique:!0}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}if(e.objectStoreNames.contains("blacklist")){const e=n.objectStore("blacklist");e.indexNames.contains("username")||e.createIndex("username","username",{unique:!1}),e.indexNames.contains("peerId")||e.createIndex("peerId","peerId",{unique:!0}),e.indexNames.contains("peerPublicKey")||e.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}else{const t=e.createObjectStore("blacklist",{keyPath:["peerId"]});t.createIndex("username","username",{unique:!1}),t.createIndex("peerId","peerId",{unique:!0}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}if(e.objectStoreNames.contains("uniqueRoom")){const e=n.objectStore("uniqueRoom");e.indexNames.contains("roomUrl")||e.createIndex("roomUrl","roomUrl",{unique:!0}),e.indexNames.contains("roomId")||e.createIndex("roomId","roomId",{unique:!0})}else{const t=e.createObjectStore("uniqueRoom",{keyPath:["roomId"]});t.createIndex("roomUrl","roomUrl",{unique:!0}),t.createIndex("roomId","roomId",{unique:!0})}if(e.objectStoreNames.contains("messageData")){const e=n.objectStore("messageData");e.indexNames.contains("roomId")||e.createIndex("roomId","roomId",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1}),e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!0}),e.indexNames.contains("fromPeerId")||e.createIndex("fromPeerId","fromPeerId",{unique:!1})}else{const t=e.createObjectStore("messageData",{keyPath:["timestamp","roomId","merkleRoot"]});t.createIndex("roomId","roomId",{unique:!1}),t.createIndex("hash","hash",{unique:!1}),t.createIndex("merkleRoot","merkleRoot",{unique:!0}),t.createIndex("fromPeerId","fromPeerId",{unique:!1})}if(e.objectStoreNames.contains("chunks")){const e=n.objectStore("chunks");e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1})}else{const t=e.createObjectStore("chunks",{keyPath:["merkleRoot","chunkIndex"]});t.createIndex("merkleRoot","merkleRoot",{unique:!1}),t.createIndex("hash","hash",{unique:!1})}if(t<18&&e.objectStoreNames.contains("newChunks")&&e.deleteObjectStore("newChunks"),e.objectStoreNames.contains("newChunks")){const e=n.objectStore("newChunks");e.indexNames.contains("transferId")||e.createIndex("transferId","transferId",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1}),e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!1}),e.indexNames.contains("receiptScope")||e.createIndex("receiptScope",["merkleRoot","receiptToken"],{unique:!1})}else{const t=e.createObjectStore("newChunks",{keyPath:["transferId","chunkIndex"]});t.createIndex("transferId","transferId",{unique:!1}),t.createIndex("hash","hash",{unique:!1}),t.createIndex("merkleRoot","merkleRoot",{unique:!1}),t.createIndex("receiptScope",["merkleRoot","receiptToken"],{unique:!1})}if(e.objectStoreNames.contains("sendQueue")){const e=n.objectStore("sendQueue");e.indexNames.contains("labelPeer")||e.createIndex("labelPeer",["label","toPeerId"],{unique:!1})}else{e.createObjectStore("sendQueue",{keyPath:["position","label","toPeerId"]}).createIndex("labelPeer",["label","toPeerId"],{unique:!1})}if(!e.objectStoreNames.contains("ratchetSessions")){const t=e.createObjectStore("ratchetSessions",{keyPath:["roomId","peerPublicKey"]});t.createIndex("peerId","peerId",{unique:!1}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!1}),t.createIndex("roomId","roomId",{unique:!1})}t>0&&t<19&&(n.objectStore("ratchetSessions").clear(),n.objectStore("sendQueue").clear()),e.objectStoreNames.contains("meta")||e.createObjectStore("meta")}})}const D="ratchetWrapKey",P=12,E=16,L=16,B=Uint8Array.of(80,50,82,87),j=B.byteLength+1+L+P,M=262144,N=(new TextEncoder).encode("p2party-edge-crypto-at-rest-aad-v2");var U;!function(e){e[e.RootKey=1]="RootKey",e[e.SendingChainKey=2]="SendingChainKey",e[e.ReceivingChainKey=3]="ReceivingChainKey",e[e.DhSelfSecret=4]="DhSelfSecret",e[e.SkippedMessageKey=5]="SkippedMessageKey",e[e.EdgeCryptoState=6]="EdgeCryptoState"}(U||(U={}));const q=e=>e.slice(0),$=(e,t,a)=>{if(!(e instanceof ArrayBuffer))throw new Error(`${t} must be an ArrayBuffer`);if(void 0!==a&&e.byteLength!==a)throw new Error(`${t} must be ${String(a)} bytes`);return e},T=(e,t)=>{if("number"!=typeof e||!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a safe unsigned integer`);return e},z=(e,t)=>{if("string"!=typeof e||0===e.length)throw new Error(`${t} must be a non-empty string`);const a=(new TextEncoder).encode(e);if(a.byteLength>1048576)throw new Error(`${t} is too long`);if((new TextDecoder).decode(a)!==e)throw new Error(`${t} is not canonical Unicode`);return e},F=e=>{if(!Number.isInteger(e)||e<0||e>4294967295)throw new Error("ratchet wrap: value exceeds uint32");const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t},H=e=>{T(e,"ratchet wrap counter");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t},O=e=>{const t=e.reduce((e,t)=>e+t.byteLength,0),a=new Uint8Array(t);let n=0;for(const t of e)a.set(t,n),n+=t.byteLength;return a},Q=e=>O([F(e.byteLength),e]),V=e=>Q((new TextEncoder).encode(e)),W=e=>{const t=e.rootSuite;if("string"!=typeof(a=t)||!v.includes(a))throw new Error("Unsupported ratchet root suite");var a;if(z(e.roomId,"ratchet roomId"),z(e.peerPublicKey,"ratchet peerPublicKey"),!/^[0-9a-f]{64}$/.test(e.peerPublicKey))throw new Error("ratchet peerPublicKey must be 32-byte lowercase hex");if(z(e.peerId,"ratchet peerId"),$(e.dhSelfPub,"ratchet dhSelfPub",32),null!==e.dhRemotePub&&$(e.dhRemotePub,"ratchet dhRemotePub",32),T(e.Ns,"ratchet Ns"),T(e.Nr,"ratchet Nr"),T(e.PN,"ratchet PN"),T(e.updatedAt,"ratchet updatedAt"),!Array.isArray(e.skippedMessageKeys)||e.skippedMessageKeys.length>2e3)throw new Error("ratchet skipped-message-key count is invalid");if(e.skippedMessageKeys.forEach((e,t)=>{$(e.dhPub,`ratchet skipped[${String(t)}].dhPub`,32),T(e.n,`ratchet skipped[${String(t)}].n`)}),null!==e.edgeCryptoState){const t=$(e.edgeCryptoState,"ratchet edge crypto state");if(t.byteLength<1||t.byteLength>M+j+E)throw new Error("ratchet edge crypto state length is invalid")}},X=e=>({rootSuite:e.rootSuite,roomId:e.roomId,peerPublicKey:e.peerPublicKey,peerId:e.peerId,rootKey:q($(e.rootKey,"ratchet rootKey")),sendingChainKey:null===e.sendingChainKey?null:q($(e.sendingChainKey,"ratchet sendingChainKey")),receivingChainKey:null===e.receivingChainKey?null:q($(e.receivingChainKey,"ratchet receivingChainKey")),dhSelfPub:q($(e.dhSelfPub,"ratchet dhSelfPub")),dhSelfSec:q($(e.dhSelfSec,"ratchet dhSelfSec")),dhRemotePub:null===e.dhRemotePub?null:q($(e.dhRemotePub,"ratchet dhRemotePub")),Ns:e.Ns,Nr:e.Nr,PN:e.PN,skippedMessageKeys:(()=>{if(!Array.isArray(e.skippedMessageKeys))throw new Error("ratchet skippedMessageKeys must be an array");return e.skippedMessageKeys.map((e,t)=>({dhPub:q($(e.dhPub,`ratchet skipped[${String(t)}].dhPub`)),n:e.n,messageKey:q($(e.messageKey,`ratchet skipped[${String(t)}].messageKey`))}))})(),edgeCryptoState:null===e.edgeCryptoState?null:q($(e.edgeCryptoState,"ratchet edge crypto state")),updatedAt:e.updatedAt}),G=e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)},_=(e,t,a,n=0)=>{if(W(e),a.byteLength!==L)throw new Error("ratchet wrap: invalid record ID");const r=(null===e.sendingChainKey?0:1)|(null===e.receivingChainKey?0:2)|(null===e.dhRemotePub?0:4)|(null===e.edgeCryptoState?0:8),o=[Q(N),Uint8Array.of(2,t),Q(a),F(n),V(e.rootSuite),V(e.roomId),V(e.peerPublicKey),V(e.peerId),Q(new Uint8Array(e.dhSelfPub)),Uint8Array.of(r)];null!==e.dhRemotePub&&o.push(Q(new Uint8Array(e.dhRemotePub))),o.push(H(e.Ns),H(e.Nr),H(e.PN),H(e.updatedAt),F(e.skippedMessageKeys.length));for(const t of e.skippedMessageKeys)o.push(Q(new Uint8Array(t.dhPub)),H(t.n));return O(o)},Y=(e,t=32)=>{const a=new Uint8Array(e),n=j+1+E,r=j+M+E;if(null===t&&(a.byteLength<n||a.byteLength>r)||null!==t&&a.byteLength!==j+t+E)throw new Error("Unsupported or malformed ratchet wrap envelope");for(let e=0;e<B.byteLength;e++)if(a[e]!==B[e])throw new Error("Unsupported or malformed ratchet wrap envelope");if(2!==a[B.byteLength])throw new Error("Unsupported or malformed ratchet wrap envelope");return Uint8Array.from(a.subarray(B.byteLength+1,B.byteLength+1+L))},J=async(e,t,a,n,r=32)=>{if($(t,"ratchet secret",null===r?void 0:r),null===r&&(t.byteLength<1||t.byteLength>M))throw new Error("ratchet variable secret length is invalid");if(n.byteLength!==L)throw new Error("ratchet wrap: invalid record ID");const o=crypto.getRandomValues(new Uint8Array(P)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:a,tagLength:128},e,t),s=new Uint8Array(j+i.byteLength);return s.set(B,0),s[B.byteLength]=2,s.set(n,B.byteLength+1),s.set(o,B.byteLength+1+L),s.set(new Uint8Array(i),j),s.buffer},Z=async(e,t,a,n,r=32)=>{$(t,"ratchet wrapped secret");const o=Y(t,r);if(!te(o,n))throw new Error("Ratchet wrap record ID mismatch");const i=new Uint8Array(t),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:i.subarray(B.byteLength+1+L,j),additionalData:a,tagLength:128},e,i.subarray(j));if(null!==r&&s.byteLength!==r||null===r&&(s.byteLength<1||s.byteLength>M))throw new Uint8Array(s).fill(0),new Error("Ratchet wrapped secret has an invalid plaintext length");return s},ee=async e=>{W(e);const t=Y(e.rootKey),a=[e.sendingChainKey,e.receivingChainKey,e.dhSelfSec,...e.skippedMessageKeys.map(e=>e.messageKey)];for(const e of a)if(null!==e&&!te(Y(e),t))throw new Error("Ratchet wrap record ID mismatch");if(null!==e.edgeCryptoState&&!te(Y(e.edgeCryptoState,null),t))throw new Error("Ratchet wrap record ID mismatch");const n=[_(e,U.RootKey,t),Q(new Uint8Array(e.rootKey)),Q(e.sendingChainKey?new Uint8Array(e.sendingChainKey):new Uint8Array),Q(e.receivingChainKey?new Uint8Array(e.receivingChainKey):new Uint8Array),Q(new Uint8Array(e.dhSelfSec))];for(const t of e.skippedMessageKeys)n.push(Q(new Uint8Array(t.messageKey)));n.push(Q(e.edgeCryptoState?new Uint8Array(e.edgeCryptoState):new Uint8Array));const r=O(n);try{return new Uint8Array(await crypto.subtle.digest("SHA-256",r))}finally{r.fill(0)}},te=(e,t)=>{if(e.byteLength!==t.byteLength)return!1;let a=0;for(let n=0;n<e.byteLength;n++)a|=e[n]^t[n];return 0===a};async function ae(){const e=await A();try{const t=await e.get("meta",D);if(t)return t;const a=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),n=e.transaction("meta","readwrite"),r=n.objectStore("meta"),o=await r.get(D);return o?(await n.done,o):(await r.put(a,D),await n.done,a)}finally{e.close()}}async function ne(e,t){const a=crypto.getRandomValues(new Uint8Array(P)),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:a},e,t),r=new Uint8Array(P+n.byteLength);return r.set(a,0),r.set(new Uint8Array(n),P),r.buffer}async function re(e,t){const a=new Uint8Array(t);if(a.byteLength<28)throw new Error("Malformed wrapped secret");return crypto.subtle.decrypt({name:"AES-GCM",iv:a.subarray(0,P)},e,a.subarray(P))}const oe=()=>globalThis.navigator?.storage,ie=new Map,se=e=>e.createSyncAccessHandle,ce=(e,t,a,n)=>new File([e],t.length>0?t:a,{type:n});async function le(e,t,a,n){if(e.length!==2*x)return null;const r=ie.get(e);if(r)return r;const o=async function(e,t,a,n){try{const r=oe();if(!r||"function"!=typeof r.getDirectory)return console.warn("OPFS unavailable — reassembling file in memory"),null;const o=await r.getDirectory(),i=await o.getDirectoryHandle(C,{create:!0}),s=await i.getFileHandle(e,{create:!0}),c=await s.getFile();if(t>0&&c.size===t)return ce(c,a,e,n);const l=s.createSyncAccessHandle;if("function"!=typeof l)return console.warn("OPFS sync access handle unavailable — reassembling in memory"),null;const d=await l.call(s);let u;try{u=await A(),d.truncate(0);let t=0;const a=u.transaction("chunks","readonly"),n=a.objectStore("chunks").index("merkleRoot");let r=await n.openCursor(e);for(;r;){const e=new Uint8Array(r.value.data??new ArrayBuffer(0));let a=0;for(;a<e.length;){const n=d.write(e.subarray(a),{at:t+a});if(n<=0)throw new Error("OPFS short write");a+=n}t+=e.length,r=await r.continue()}await a.done,d.flush()}catch(t){try{d.close()}catch{}if(u)try{u.close()}catch{}throw await i.removeEntry(e).catch(()=>{}),t}return d.close(),u.close(),ce(await s.getFile(),a,e,n)}catch(e){return console.error(e),null}}(e,t,a,n);ie.set(e,o);try{return await o}finally{ie.delete(e)}}async function de(e){try{const t=oe();if(!t||"function"!=typeof t.getDirectory)return;const a=await t.getDirectory(),n=await a.getDirectoryHandle(C).catch(()=>null);n&&await n.removeEntry(e).catch(()=>{})}catch{}}const ue=new Map,he=new Map,ye=new Map,we=new Map;async function ge(e,t){const a=we.get(e)??Promise.resolve();let n;const r=new Promise(e=>{n=e}),o=a.then(()=>r);we.set(e,o),await a;try{return await t()}finally{n(),we.get(e)===o&&we.delete(e)}}async function fe(e,t){const a=ue.get(e);if(a)return a;const n=he.get(e);if(n)return n;if(ue.size>=8)for(const t of ue.keys())if(t!==e){await be(t);break}const r=async function(e,t){const a=oe();if(!a||"function"!=typeof a.getDirectory)return null;const n=await a.getDirectory(),r=await n.getDirectoryHandle(C,{create:!0}),o=await r.getFileHandle(e,{create:!0}),i=se(o);if("function"!=typeof i)return null;const s=await i.call(o);try{return t>0&&s.getSize()!==t&&s.truncate(t),{access:s,uniformSize:0,uniformKnown:!1,maxRealLen:0,seenCount:0}}catch(e){try{s.close()}catch{}throw e}}(e,t).catch(e=>(console.error(e),null));he.set(e,r);try{const t=await r;return t&&ue.set(e,t),t}finally{he.delete(e)}}function me(e,t,a){const n=new Uint8Array(a);let r=0;for(;r<n.length;){const a=e.write(n.subarray(r),{at:t+r});if(a<=0)throw new Error("OPFS short write");r+=a}}async function pe(e){const{schemaVersion:t,roomId:a,fromPeerId:n,channelLabel:r,timestamp:o,merkleRoot:i,hash:s,filename:c,messageType:l,chunkIndex:d,mimeType:u,leafHash:h,realLen:y,totalSize:w,data:g,storage:f}=e;if(1!==t||!Number.isSafeInteger(l)||l<1||l>64||!Number.isSafeInteger(d)||d<0||!Number.isSafeInteger(y)||y<=0||y>K||!Number.isSafeInteger(w)||w<=0||w>10737418240||y>w||d>=w||g.byteLength!==y||!Number.isSafeInteger(o))throw new Error("invalid receive chunk bounds");const m=e=>{if(e&&(e.roomId!==a||e.fromPeerId!==n||e.hash!==s||e.totalSize!==w||e.messageType!==l||e.filename!==c||e.channelLabel!==r||e.timestamp!==o))throw new Error("receive chunk metadata conflicts with message")},p=e=>{const t=e.map(e=>({chunkIndex:e.chunkIndex,realLen:e.realLen??0})).sort((e,t)=>e.chunkIndex-t.chunkIndex);let a=0;for(let e=0;e<t.length;e++){const n=t[e];if(!Number.isSafeInteger(n.chunkIndex)||n.chunkIndex<0||!Number.isSafeInteger(n.realLen)||n.realLen<=0||n.realLen>K||n.realLen>w||n.chunkIndex>=w||e>0&&t[e-1].chunkIndex===n.chunkIndex)throw new Error("invalid receive chunk layout");if(a+=n.realLen,!Number.isSafeInteger(a)||a>w)throw new Error("receive chunks exceed declared total")}const n=t.find(e=>0===e.chunkIndex);let r;if(n)r=n.realLen;else if(t.length>=2){r=0;for(const e of t)r=Math.max(r,e.realLen)}if(void 0!==r){const e=Math.ceil(w/r),n=e-1,o=w-r*n;for(const a of t){if(a.chunkIndex>=e)throw new Error("receive chunk index exceeds canonical manifest");const t=a.chunkIndex===n?o:r;if(a.realLen!==t)throw new Error("receive chunk length conflicts with manifest")}const i=a===w&&t.length===e&&t.every((e,t)=>e.chunkIndex===t);if(a===w&&!i)throw new Error("receive completion has a chunk-index gap");return{savedSize:a,complete:i}}if(a===w)throw new Error("receive completion is missing chunk zero");return{savedSize:a,complete:!1}},b=await A();let k;try{const e=b.transaction(["chunks","messageData"],"readonly");k=await e.objectStore("chunks").count([i,d]);m(await e.objectStore("messageData").index("merkleRoot").get(i)),await e.done}finally{b.close()}if(k>0){const e=await A();try{const t=e.transaction(["chunks","messageData"],"readonly"),a=t.objectStore("chunks").index("merkleRoot"),n=[];let r=await a.openCursor(i);for(;r;)n.push(r.value),r=await r.continue();m(await t.objectStore("messageData").index("merkleRoot").get(i));const o=p(n);return await t.done,{stored:!1,...o}}finally{e.close()}}const S=await A();try{const e=S.transaction(["chunks","messageData"],"readonly"),t=[];let a=await e.objectStore("chunks").index("merkleRoot").openCursor(i);for(;a;)t.push(a.value),a=await a.continue();m(await e.objectStore("messageData").index("merkleRoot").get(i)),p([...t,{chunkIndex:d,realLen:y}]),await e.done}finally{S.close()}let I=!1;if("opfs"===f)try{I=await async function(e,t,a,n,r){const o=await fe(e,n);if(!o)return!1;if(o.maxRealLen=Math.max(o.maxRealLen,a),o.seenCount+=1,o.uniformKnown||(0===t?(a<n&&(o.uniformSize=a),o.uniformKnown=!0):o.seenCount>=2&&(o.uniformSize=o.maxRealLen,o.uniformKnown=!0)),!o.uniformKnown)return!1;const i=0===t?0:t*o.uniformSize;return me(o.access,i,r),o.access.flush(),!0}(i,d,y,w,g)}catch(e){console.error(e),I=!1}const x="opfs"===f&&I?{merkleRoot:i,hash:s,chunkIndex:d,mimeType:u,realLen:y,leafHash:h}:{merkleRoot:i,hash:s,chunkIndex:d,mimeType:u,realLen:y,leafHash:h,data:g},v=await A();try{const e=v.transaction(["chunks","messageData","uniqueRoom"],"readwrite"),t=e.objectStore("chunks"),u=await t.getKey([i,d]);let h=!1;const g=[];let f=await t.index("merkleRoot").openCursor(i);for(;f;)g.push(f.value),f=await f.continue();void 0===u&&(p([...g,{chunkIndex:d,realLen:y}]),await t.add(x),g.push(x),h=!0);const b=p(g);if(h){const t=e.objectStore("messageData"),d=await t.index("merkleRoot").get(i);m(d),await t.put({roomId:a,timestamp:d?.timestamp??o,merkleRoot:i,hash:s,fromPeerId:n,filename:c,messageType:l,savedSize:b.savedSize,totalSize:w,channelLabel:r});const u=e.objectStore("uniqueRoom"),h=await u.index("roomId").get(a);h&&h.lastMessageMerkleRoot!==i&&await u.put({...h,lastMessageMerkleRoot:i,messageCount:h.messageCount+1,updatedAt:o})}return await e.done,{stored:h,...b}}finally{v.close()}}async function be(e){const t=he.get(e);if(t)try{await t}catch{}const a=ue.get(e);if(a){ue.delete(e);try{a.access.flush(),a.access.close()}catch{}}}async function ke(e,t,a,n){if(e.length!==2*x)return null;await be(e);const r=ye.get(e);if(r)return r;const o=async function(e,t,a,n){try{const r=oe();if(!r||"function"!=typeof r.getDirectory)return null;const o=await r.getDirectory(),i=await o.getDirectoryHandle(C,{create:!0}),s=await i.getFileHandle(e,{create:!0}),c=await A(),l=[];let d=0;try{const t=c.transaction("chunks","readonly"),a=t.objectStore("chunks").index("merkleRoot");let n=await a.openCursor(e);for(;n;){const e=n.value;e.realLen&&e.realLen>d&&(d=e.realLen),e.data&&e.data.byteLength>0&&l.push(e),n=await n.continue()}await t.done}catch(e){return console.error(e),c.close(),null}const u=await s.getFile();if(t>0&&u.size===t&&0===l.length)return c.close(),ce(u,a,e,n);if(l.length>0&&(0===d||l.some(e=>null==e.realLen)))return c.close(),null;const h=se(s);if("function"!=typeof h)return c.close(),null;const y=await h.call(s);try{t>0&&y.getSize()!==t&&y.truncate(t);for(let e=0;e<l.length;e++){const t=l[e];me(y,0===t.chunkIndex?0:t.chunkIndex*d,t.data)}y.flush()}finally{y.close()}if(l.length>0)try{const e=c.transaction("chunks","readwrite"),t=e.objectStore("chunks");for(let e=0;e<l.length;e++){const a=l[e];await t.put({merkleRoot:a.merkleRoot,hash:a.hash,chunkIndex:a.chunkIndex,mimeType:a.mimeType,realLen:a.realLen,leafHash:a.leafHash})}await e.done}catch(e){console.error(e)}c.close();const w=await s.getFile();return t>0&&w.size!==t?null:ce(w,a,e,n)}catch(e){return console.error(e),null}}(e,t,a,n);ye.set(e,o);try{return await o}finally{ye.delete(e)}}const Se=new class{#e=new Map;#t(e,t){const a=(e=>`${String(e.roomId.length)}:${e.roomId}${String(e.peerPublicKey.length)}:${e.peerPublicKey}`)(e),n=this.#e.get(a);if(n&&e.updatedAt<n.updatedAt)throw t.fill(0),new Error("Ratchet persistence rollback detected");if(e.updatedAt===n?.updatedAt&&!te(t,n.fingerprint))throw t.fill(0),new Error("Ratchet persistence equivocation detected");!n||e.updatedAt>n.updatedAt?(n?.fingerprint.fill(0),this.#e.set(a,{updatedAt:e.updatedAt,fingerprint:t})):t.fill(0)}async acceptAuthenticated(e){const t=await ee(e);this.#t(e,t)}async rememberTrustedWrite(e){const t=await ee(e);this.#t(e,t)}forget(e,t){const a=`${String(e.length)}:${e}${String(t.length)}:${t}`;this.#e.get(a)?.fingerprint.fill(0),this.#e.delete(a)}clear(){for(const e of this.#e.values())e.fingerprint.fill(0);this.#e.clear()}},Ie=new Map,xe=new Map,Ke=(e,t)=>`${String(e.length)}:${e}${String(t.length)}:${t}`,ve=async(e,t,a)=>{const n=Ke(e,t),r=xe.get(n)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=r.catch(()=>{}).then(()=>i);xe.set(n,s),await r.catch(()=>{});try{return await a()}finally{o(),xe.get(n)===s&&xe.delete(n)}};async function Ce(e,t){return ve(e,t,async()=>{try{const a=await A();let n;try{n=await a.get("ratchetSessions",[e,t])}finally{a.close()}if(!n)return;const r=await ae(),o=await async function(e,t,a){const n=X(e);W(n);const r=[];try{const e=Y(n.rootKey),o=await Z(t,n.rootKey,_(n,U.RootKey,e),e);r.push(o);const i=n.sendingChainKey?await Z(t,n.sendingChainKey,_(n,U.SendingChainKey,e),e):null;i&&r.push(i);const s=n.receivingChainKey?await Z(t,n.receivingChainKey,_(n,U.ReceivingChainKey,e),e):null;s&&r.push(s);const c=await Z(t,n.dhSelfSec,_(n,U.DhSelfSecret,e),e);r.push(c);const l=[];for(let a=0;a<n.skippedMessageKeys.length;a++){const o=n.skippedMessageKeys[a],i=await Z(t,o.messageKey,_(n,U.SkippedMessageKey,e,a),e);r.push(i),l.push({dhPub:o.dhPub,n:o.n,messageKey:i})}const d=n.edgeCryptoState?await Z(t,n.edgeCryptoState,_(n,U.EdgeCryptoState,e),e,null):null;return d&&r.push(d),a&&await a.acceptAuthenticated(n),{...n,rootKey:o,sendingChainKey:i,receivingChainKey:s,dhSelfSec:c,skippedMessageKeys:l,edgeCryptoState:d}}catch(e){for(const e of r)new Uint8Array(e).fill(0);throw e}finally{G(n)}}(n,r,Se),i=Ke(e,t);return Ie.set(i,Math.max(Ie.get(i)??0,o.updatedAt)),o}catch(e){return void console.error(e)}})}async function Re(e){await ve(e.roomId,e.peerPublicKey,async()=>{const t=Ke(e.roomId,e.peerPublicKey),a=Ie.get(t)??0,n=Math.max(Date.now(),e.updatedAt),r=n>a?n:a+1;if(!Number.isSafeInteger(r))throw new Error("Ratchet persistence timestamp exhausted");const o={...e,updatedAt:r};try{const e=await ae(),a=await async function(e,t){const a=X(e);if(W(a),$(a.rootKey,"ratchet rootKey",32),a.sendingChainKey&&$(a.sendingChainKey,"ratchet sendingChainKey",32),a.receivingChainKey&&$(a.receivingChainKey,"ratchet receivingChainKey",32),$(a.dhSelfSec,"ratchet dhSelfSec",32),a.skippedMessageKeys.forEach((e,t)=>$(e.messageKey,`ratchet skipped[${String(t)}].messageKey`,32)),a.edgeCryptoState&&($(a.edgeCryptoState,"ratchet edge crypto state"),a.edgeCryptoState.byteLength<1||a.edgeCryptoState.byteLength>M))throw new Error("ratchet edge crypto state length is invalid");try{const e=crypto.getRandomValues(new Uint8Array(L)),n=await J(t,a.rootKey,_(a,U.RootKey,e),e),r=a.sendingChainKey?await J(t,a.sendingChainKey,_(a,U.SendingChainKey,e),e):null,o=a.receivingChainKey?await J(t,a.receivingChainKey,_(a,U.ReceivingChainKey,e),e):null,i=await J(t,a.dhSelfSec,_(a,U.DhSelfSecret,e),e),s=[];for(let n=0;n<a.skippedMessageKeys.length;n++){const r=a.skippedMessageKeys[n];s.push({dhPub:r.dhPub,n:r.n,messageKey:await J(t,r.messageKey,_(a,U.SkippedMessageKey,e,n),e)})}const c=a.edgeCryptoState?await J(t,a.edgeCryptoState,_(a,U.EdgeCryptoState,e),e,null):null;return{...a,rootKey:n,sendingChainKey:r,receivingChainKey:o,dhSelfSec:i,skippedMessageKeys:s,edgeCryptoState:c}}finally{G(a)}}(o,e),n=await A();try{await n.put("ratchetSessions",a)}finally{n.close()}await Se.rememberTrustedWrite(a),Ie.set(t,r)}finally{(e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)})(o)}})}const Ae=/^[0-9a-f]{64}$/,De=(e,t)=>{if("string"!=typeof e||0===e.length)throw new Error("PIN attempt room ID must not be empty");if(void 0!==t&&!Ae.test(t))throw new Error("PIN attempt peer identity must be 32-byte lowercase hexadecimal")},Pe=e=>`pinAttempts:v2:${e.length}:${e}:`,Ee=(e,t)=>`${Pe(e)}${t}`;const Le="identityX25519";const Be="identityEd25519";async function je(){try{await async function(){const e=[...he.values()];for(let t=0;t<e.length;t++)try{await e[t]}catch{}const t=[...ue.keys()];for(let e=0;e<t.length;e++)await be(t[e])}();const e=oe();if(e&&"function"==typeof e.getDirectory){const t=await e.getDirectory();await t.removeEntry(C,{recursive:!0}).catch(()=>{})}}catch{}await function(e,{blocked:t}={}){const a=indexedDB.deleteDatabase(e);return t&&a.addEventListener("blocked",e=>t(e.oldVersion,e)),d(a).then(()=>{})}(R,{blocked(){console.error("DB deletion BLOCKED")}}),Se.clear(),Ie.clear()}onmessage=async e=>{const t=e.data,{id:a,method:n}=t;try{let e;switch(n){case"getDBAddressBookEntry":e=await async function(e,t){if(!e&&!t)return;if(e&&e.length<10&&!t)return;if(t&&64!==t.length&&!e)return;const a=await A();try{const n=a.transaction("addressBook","readonly"),r=e?n.objectStore("addressBook").index("peerId"):n.objectStore("addressBook").index("peerPublicKey"),o=e?await r.get(e):await r.get(t??"");return await n.done,a.close(),o?{username:o.username,peerId:o.peerId,peerPublicKey:o.peerPublicKey}:void 0}catch{return void a.close()}}(...t.args);break;case"getAllDBAddressBookEntries":e=await async function(){try{const e=await A(),t=await e.getAll("addressBook");return e.close(),t}catch{return[]}}(...t.args);break;case"setDBAddressBookEntry":await async function(e,t,a){try{const n=await A(),r=n.transaction(["addressBook"],"readwrite"),o=r.objectStore("addressBook"),i=o.index("peerId"),s=o.index("peerPublicKey"),c=await i.get(t),l=await s.get(a);(!c&&!l||c&&!l||!c&&l)&&await o.put({username:e,peerId:t,peerPublicKey:a,dateAdded:Date.now()}),await r.done,n.close()}catch(e){console.error(e)}}(...t.args),e=void 0;break;case"deleteDBAddressBookEntry":e=await async function(e,t,a){const n=!e||0===e.length,r=!t||t.length<10,o=64!==a?.length;if(n&&r&&o)throw new Error("Cannot delete address book with no data");let i=t??"";try{const n=await A(),s=n.transaction("addressBook","readwrite"),c=s.objectStore("addressBook");if(r)if(o){const t=c.index("username"),a=await t.getKey(e??"");if(a){const n=await t.get(e??"");i=n?.peerId??"",await c.delete(a)}}else{const e=c.index("peerPublicKey"),t=await e.getKey(a);if(t){const n=await e.get(a);i=n?.peerId??"",await c.delete(t)}}else{const e=c.index("peerId"),a=await e.getKey(t);a&&await c.delete(a)}await s.done,n.close()}catch{}return i}(...t.args);break;case"getDBPeerIsBlacklisted":e=await async function(e,t){if(!e&&!t)return!1;if(e&&e.length<10&&!t)return!1;if(t&&64!==t.length&&!e)return!1;const a=await A();try{const n=a.transaction("blacklist","readonly"),r=e?n.objectStore("blacklist").index("peerId"):n.objectStore("blacklist").index("peerPublicKey"),o=e?await r.get(e):await r.get(t??"");return await n.done,!!o}finally{a.close()}}(...t.args);break;case"getAllDBBlacklisted":e=await async function(){const e=await A();try{const t=await e.getAll("blacklist");return e.close(),t}catch{return e.close(),[]}}(...t.args);break;case"setDBPeerInBlacklist":await async function(e,t){try{const a=await A(),n=a.transaction(["blacklist"],"readwrite"),r=n.objectStore("blacklist"),o=r.index("peerId"),i=r.index("peerPublicKey"),s=await o.get(e),c=await i.get(t);(!s&&!c||s&&!c||!s&&c)&&await r.put({peerId:e,peerPublicKey:t,dateAdded:Date.now()}),await n.done,a.close()}catch(e){throw console.error(e),e}}(...t.args),e=void 0;break;case"deleteDBPeerFromBlacklist":await async function(e,t){const a=!e||e.length<10;if(a&&64!==t?.length)throw new Error("Cannot delete blacklisted with no data");try{const n=await A(),r=n.transaction("blacklist","readwrite"),o=r.objectStore("blacklist");if(a){const e=o.index("peerPublicKey"),a=await e.getKey(t??"");a&&await o.delete(a)}else{const t=o.index("peerId"),a=await t.getKey(e);a&&await o.delete(a)}await r.done,n.close()}catch(e){console.error(e)}}(...t.args),e=void 0;break;case"getAllDBUniqueRooms":e=await async function(){const e=await A();try{const t=await e.getAll("uniqueRoom");return e.close(),t}catch{return e.close(),[]}}(...t.args);break;case"setDBUniqueRoom":await async function(e,t,a){if(32!==a.byteLength)throw new Error("Room policy must be the canonical 32-byte descriptor");const n=await A();try{const r=n.transaction(["uniqueRoom"],"readwrite"),o=r.objectStore("uniqueRoom"),i=o.index("roomUrl"),s=o.index("roomId"),c=await i.get(e),l=await s.get(t),d=c??l;if(d)await o.put({...d,roomId:t,roomUrl:e,roomPolicy:a,updatedAt:Date.now()});else{const n=Date.now();await o.put({roomId:t,roomUrl:e,roomPolicy:a,messageCount:0,lastMessageMerkleRoot:"",createdAt:n,updatedAt:n})}await r.done}finally{n.close()}}(...t.args),e=void 0;break;case"getDBMessageData":e=await async function(e,t){try{const a=await A(),n=a.transaction(["messageData"],"readonly"),r=n.objectStore("messageData"),o=r.index("merkleRoot"),i=r.index("hash");if(e?.length===2*x){const r=await o.get(e);if(r)return await n.done,a.close(),r;if(t?.length===2*x){const e=await i.get(t);return await n.done,a.close(),e}return await n.done,void a.close()}if(t?.length===2*x){const e=await i.get(t);return await n.done,a.close(),e}return await n.done,void a.close()}catch(e){return void console.error(e)}}(...t.args);break;case"getDBRoomMessageData":e=await async function(e){const t=await A(),a=await t.getAllFromIndex("messageData","roomId",e);t.close();const n=a.length,r=[];for(let t=0;t<n;t++)r.push({transferId:a[t].transferId,roomId:e,merkleRoot:a[t].merkleRoot,hash:a[t].hash,fromPeerId:a[t].fromPeerId,filename:a[t].filename,messageType:a[t].messageType,savedSize:a[t].savedSize,totalSize:a[t].totalSize,channelLabel:a[t].channelLabel,timestamp:a[t].timestamp});return r}(...t.args);break;case"getDBRoomStats":e=await async function(e){const t=await A(),a=await t.getAllFromIndex("messageData","roomId",e);t.close();const n=new Set;let r=0,o=0,i=0,s=0;for(const e of a){const t=void 0!==e.transferId,a=t?e.totalSize:e.savedSize;t?(r+=a,i+=1):(o+=a,s+=1,e.fromPeerId.length>0&&n.add(e.fromPeerId))}return{messageCount:a.length,messagesSent:i,messagesReceived:s,bytesSent:r,bytesReceived:o,bytesTotal:r+o,peerIds:[...n]}}(...t.args);break;case"setDBRoomMessageData":await async function(e,t,a,n,r,o,i,s,c,l,d){try{const u=await A(),h=u.transaction(["messageData","uniqueRoom"],"readwrite"),y=h.objectStore("messageData"),w=await y.index("merkleRoot").get(t),g=w?.savedSize??0;try{await y.put({transferId:d,roomId:e,timestamp:l,merkleRoot:t,hash:a,fromPeerId:n,filename:s,messageType:i,savedSize:g+r<=o?g+r:o,totalSize:o,channelLabel:c})}catch(e){throw await h.done,u.close(),e}const f=h.objectStore("uniqueRoom"),m=await f.index("roomId").get(e);if(m&&m.lastMessageMerkleRoot!==t)try{await f.put({...m,lastMessageMerkleRoot:t,messageCount:m.messageCount+1,updatedAt:l})}catch(e){throw await h.done,u.close(),e}await h.done,u.close()}catch(e){throw console.error(e),e}}(...t.args),e=void 0;break;case"getDBChunk":e=await async function(e,t){const a=await A(),n=await a.get("chunks",[e,t]);return a.close(),n?.data}(...t.args);break;case"existsDBChunk":e=await async function(e,t){const a=await A(),n=await a.count("chunks",[e,t]);return a.close(),n>0}(...t.args);break;case"getDBNewChunk":e=await async function(e,t){const a=await A();try{return await a.get("newChunks",[e,t])}finally{a.close()}}(...t.args);break;case"getDBNewChunkByReceipt":e=await async function(e,t){if(e.length!==2*x||t.length!==2*x)return;const a=await A();try{return await a.getFromIndex("newChunks","receiptScope",[e,t])}finally{a.close()}}(...t.args);break;case"existsDBNewChunk":e=await async function(e,t){const a=await A(),n=await a.count("newChunks",[e,t]);return a.close(),n>0}(...t.args);break;case"getDBSendQueue":e=await async function(e,t,a){const n=await A();if(a){const r=await n.get("sendQueue",[a,e,t]);return n.close(),r?[r]:[]}const r=n.transaction("sendQueue","readonly").objectStore("sendQueue").index("labelPeer"),o=IDBKeyRange.only([e,t]),i=await r.getAll(o);return n.close(),i}(...t.args);break;case"getDBAllChunks":e=await async function(e,t){try{const a=await A(),n=a.transaction("chunks","readonly"),r=n.objectStore("chunks"),o=r.index("hash"),i=r.index("merkleRoot");if(e?.length===2*x){const t=await i.getAll(e);return 0===t.length?(await n.done,a.close(),[]):(await n.done,a.close(),t)}if(t?.length===2*x){const e=await o.getAll(t);return await n.done,a.close(),e.length>0?e.filter(t=>t.merkleRoot===e[0].merkleRoot):e}return await n.done,a.close(),[]}catch(e){return console.error(e),[]}}(...t.args);break;case"getDBAllChunkLeafHashes":e=await async function(e){if(e.length!==2*x)return[];try{const t=await A(),a=t.transaction("chunks","readonly"),n=a.objectStore("chunks").index("merkleRoot"),r=[];let o=await n.openCursor(e);for(;o;)r.push({chunkIndex:o.value.chunkIndex,leafHash:o.value.leafHash}),o=await o.continue();return await a.done,t.close(),r}catch(e){return console.error(e),[]}}(...t.args);break;case"assembleToOPFS":e=await le(...t.args);break;case"getDBAllChunksCount":e=await async function(e,t){try{const a=await A(),n=a.transaction(["chunks"],"readonly"),r=n.objectStore("chunks"),o=r.index("hash"),i=r.index("merkleRoot");if(t?.length===2*x){const r=await o.count(t);if(0===r){if(e?.length===2*x){const t=await i.count(e);return await n.done,a.close(),t}return await n.done,a.close(),0}return await n.done,a.close(),r}if(e?.length===2*x){const t=await i.count(e);return await n.done,a.close(),t}return await n.done,a.close(),0}catch{return 0}}(...t.args);break;case"setDBChunk":await async function(e){const t=await A();try{await t.add("chunks",e)}finally{t.close()}}(...t.args),e=void 0;break;case"storeReceiveChunk":{const a=t.args[0];e=await ge(a.merkleRoot,()=>async function(e){return pe(e)}(a));break}case"getReceiveFile":{const a=t.args;e=await ge(a[0],()=>ke(...a));break}case"closeReceiveFile":await ge(t.args[0],()=>be(...t.args)),e=void 0;break;case"deleteReceiveTransfer":await ge(t.args[0],()=>async function(e){if(e.length!==2*x||!/^[0-9a-f]+$/.test(e))throw new Error("invalid receive transfer Merkle root");await be(e);const t=await A();try{const a=t.transaction(["chunks","messageData","uniqueRoom"],"readwrite"),n=a.objectStore("chunks"),r=a.objectStore("messageData"),o=a.objectStore("uniqueRoom"),i=await n.index("merkleRoot").getAllKeys(e);for(const e of i)await n.delete(e);const s=await r.index("merkleRoot").getAllKeys(e);let c="";for(const e of s){const t=await r.get(e);!c&&t&&(c=t.roomId),await r.delete(e)}if(c){const e=await o.index("roomId").get(c);if(e){const t=r.index("roomId"),a=await t.count(c),n=await t.openCursor(IDBKeyRange.only(c),"prev");await o.put({...e,messageCount:a,updatedAt:n?.value.timestamp??Date.now(),lastMessageMerkleRoot:n?.value.merkleRoot??""})}}await a.done}finally{t.close()}await de(e)}(...t.args)),e=void 0;break;case"getDBAllNewChunks":e=await async function(e){const{transferId:t,merkleRootHex:a,hashHex:n}=e,r=t?"transferId":a?"merkleRoot":n?"hash":void 0,o=t??a??n;if(!r||!o)return[];const i=await A();try{return await i.getAllFromIndex("newChunks",r,o)}finally{i.close()}}(...t.args);break;case"getDBAllNewChunksCount":e=await async function(e){const t=await A();try{return await t.countFromIndex("newChunks","transferId",e)}finally{t.close()}}(...t.args);break;case"setDBNewChunk":await async function(e){const t=await A();try{await t.put("newChunks",e)}finally{t.close()}}(...t.args),e=void 0;break;case"setDBSendQueue":await async function(e){const t=await A();await t.put("sendQueue",e),t.close()}(...t.args),e=void 0;break;case"countDBSendQueue":e=await async function(e,t){const a=await A(),n=a.transaction("sendQueue","readonly").objectStore("sendQueue").index("labelPeer"),r=IDBKeyRange.only([e,t]),o=await n.count(r);return a.close(),o}(...t.args);break;case"deleteDBChunk":await async function(e,t){try{const a=await A(),n=a.transaction("chunks","readwrite"),r=n.objectStore("chunks");if(void 0!==t){const a=IDBKeyRange.only([e,t]);await r.delete(a)}else{const t=r.index("hash"),a=await t.getAllKeys(e),n=a.length;if(0===n){const t=r.index("merkleRoot"),a=await t.getAllKeys(e),n=a.length;for(let e=0;e<n;e++)await r.delete(a[e])}else for(let e=0;e<n;e++)await r.delete(a[e])}await n.done,a.close()}catch{}}(...t.args),e=void 0;break;case"deleteDBNewChunk":await async function(e){const{transferId:t,merkleRootHex:a,hashHex:n,chunkIndex:r}=e,o=await A();try{const e=o.transaction("newChunks","readwrite"),i=e.objectStore("newChunks");if(t&&void 0!==r)await i.delete([t,r]);else if(t){const e=await i.index("transferId").getAllKeys(t);for(const t of e)await i.delete(t)}else if(a){const e=await i.index("merkleRoot").getAllKeys(a);for(const t of e)await i.delete(t)}else if(n){const e=await i.index("hash").getAllKeys(n);for(const t of e)await i.delete(t)}await e.done}catch(e){throw console.error(e),e}finally{o.close()}}(...t.args),e=void 0;break;case"deleteDBMessageData":await async function(e){try{const t=await A(),a=t.transaction(["messageData","uniqueRoom"],"readwrite"),n=a.objectStore("messageData"),r=a.objectStore("uniqueRoom"),o=n.index("merkleRoot"),i=await o.getAllKeys(e),s=i.length;let c="";for(let e=0;e<s;e++){if(0===e||0===c.length){const t=await n.get(i[e]);c=t?.roomId??""}await n.delete(i[e])}if(c.length>0){const e=r.index("roomId"),t=await e.get(c);if(t){const e=n.index("roomId"),a=await e.getAllKeys(c),o=a.length,i=o>0?await n.get(a[o-1]):void 0;await r.put({...t,messageCount:t.messageCount>0?t.messageCount-1:0,updatedAt:i?.timestamp??Date.now(),lastMessageMerkleRoot:i?.merkleRoot??""})}}await a.done,t.close(),await ge(e,async()=>{await be(e),await de(e)})}catch{}}(...t.args),e=void 0;break;case"deleteDBUniqueRoom":await async function(e){try{const t=await A(),a=t.transaction(["uniqueRoom","ratchetSessions"],"readwrite"),n=a.objectStore("uniqueRoom"),r=n.index("roomId"),o=await r.getKey(e);void 0!==o&&await n.delete(o);const i=a.objectStore("ratchetSessions"),s=await i.index("roomId").getAllKeys(e);for(const t of s)await i.delete(t),Array.isArray(t)&&"string"==typeof t[1]&&(Se.forget(e,t[1]),Ie.delete(Ke(e,t[1])));await a.done,t.close()}catch{}}(...t.args),e=void 0;break;case"deleteDBSendQueue":await async function(e,t,a){try{const n=await A();if(void 0!==a)await n.delete("sendQueue",[a,e,t]);else{const a=IDBKeyRange.only([e,t]);await n.delete("sendQueue",a)}n.close()}catch{}}(...t.args),e=void 0;break;case"getRatchetSession":e=await Ce(...t.args);break;case"setRatchetSession":await Re(...t.args),e=void 0;break;case"deleteRatchetSession":await async function(e,t){await ve(e,t,async()=>{try{const a=await A();await a.delete("ratchetSessions",[e,t]),a.close(),Se.forget(e,t),Ie.delete(Ke(e,t))}catch(e){console.error(e)}})}(...t.args),e=void 0;break;case"getPinAttemptState":e=await async function(e,t){De(e,t);const a=await A();try{return await a.get("meta",Ee(e,t))}finally{a.close()}}(...t.args);break;case"incrementPinAttemptState":e=await async function(e,t,a,n,r,o){if(De(e,t),!Number.isSafeInteger(a)||!Number.isSafeInteger(n)||!Number.isSafeInteger(r)||!Number.isSafeInteger(o)||a<0||n<1||r<1||o<r)throw new Error("Invalid PIN backoff parameters");const i=await A();try{const s=i.transaction("meta","readwrite"),c=s.objectStore("meta"),l=Ee(e,t),d=await c.get(l),u=(d?.failures??0)+1,h={failures:u,retryAfter:a+(u<n?0:Math.min(r*2**(u-n),o))};return await c.put(h,l),await s.done,h}finally{i.close()}}(...t.args);break;case"deletePinAttemptState":await async function(e,t){De(e,t);const a=await A();try{if(void 0!==t)return void await a.delete("meta",Ee(e,t));const n=a.transaction("meta","readwrite"),r=n.objectStore("meta"),o=Pe(e),i=await r.getAllKeys();await Promise.all(i.filter(e=>"string"==typeof e&&e.startsWith(o)).map(e=>r.delete(e))),await r.delete(`pinAttempts:${e}`),await n.done}finally{a.close()}}(...t.args),e=void 0;break;case"getIdentityX25519":e=await async function(){const e=await A();let t;try{t=await e.get("meta",Le)}finally{e.close()}if(!t)return;if(32!==t.pub.byteLength||64!==t.crossSig.byteLength)throw new Error("Stored X25519 identity has invalid public fields");const a=await ae(),n=await re(a,t.wrappedSecret);if(32!==n.byteLength)throw new Error("Stored X25519 identity has an invalid secret length");return{pub:t.pub,secret:n,crossSig:t.crossSig}}();break;case"setIdentityX25519":await async function(e){if(32!==e.pub.byteLength||32!==e.secret.byteLength||64!==e.crossSig.byteLength)throw new Error("X25519 identity has invalid field lengths");const t=await ae(),a=await ne(t,e.secret),n={pub:e.pub,wrappedSecret:a,crossSig:e.crossSig},r=await A();try{await r.put("meta",n,Le)}finally{r.close()}}(...t.args),e=void 0;break;case"deleteIdentityX25519":await async function(){const e=await A();try{const t=e.transaction(["meta","ratchetSessions"],"readwrite");await t.objectStore("meta").delete(Le),await t.objectStore("ratchetSessions").clear(),await t.done}finally{e.close()}Se.clear(),Ie.clear()}(),e=void 0;break;case"getIdentityEd25519":e=await async function(){const e=await A();let t;try{t=await e.get("meta",Be)}finally{e.close()}if(!t)return;if(32!==t.pub.byteLength)throw new Error("Stored Ed25519 public key has an invalid length");const a=await ae(),n=await re(a,t.wrappedSecret);if(64!==n.byteLength)throw new Error("Stored Ed25519 secret key has an invalid length");return{pub:t.pub,secret:n}}();break;case"setIdentityEd25519":await async function(e){if(32!==e.pub.byteLength||64!==e.secret.byteLength)throw new Error("Ed25519 identity has invalid key lengths");const t=await ae(),a=await ne(t,e.secret),n={pub:e.pub,wrappedSecret:a},r=await A();try{await r.put("meta",n,Be)}finally{r.close()}}(...t.args),e=void 0;break;case"deleteIdentityEd25519":await async function(){const e=await A();try{const t=e.transaction(["meta","ratchetSessions"],"readwrite");await t.objectStore("meta").delete(Be),await t.objectStore("ratchetSessions").clear(),await t.done}finally{e.close()}Se.clear(),Ie.clear()}(),e=void 0;break;case"deleteDB":await je(),e=void 0;break;default:return void postMessage({id:a,error:"Method not found"})}postMessage({id:a,result:e})}catch(e){postMessage({id:a,error:String(e)})}};\n',ja=new Blob([za],{type:"application/javascript"}),Ha=new Worker(URL.createObjectURL(ja),{type:"module"});let Va=0;const $a=new Map;Ha.onmessage=e=>{const{id:t,result:n,error:r}=e.data,a=$a.get(t);a&&($a.delete(t),r?a.reject(r):a.resolve(n))};const Qa=e=>{const t=[...$a.values()];$a.clear();for(const n of t)n.reject(e)};function Wa(e,...t){return new Promise((n,r)=>{const a=++Va;$a.set(a,{resolve:n,reject:r}),Ha.postMessage({id:a,method:e,args:t})})}Ha.onerror=e=>{Qa(new Error(`p2party: the database worker failed: ${e.message||"unknown error"}`))},Ha.onmessageerror=()=>{Qa(new Error("p2party: a database worker message could not be deserialized"))};const Xa=(e,t)=>Wa("getDBAddressBookEntry",e,t),Ga=async(e,t)=>{try{return await Wa("getDBPeerIsBlacklisted",e,t)}catch(e){return console.error("p2party: blacklist lookup failed; treating this peer as blocked",e),!0}},Ja=()=>Wa("getAllDBUniqueRooms"),Ya=(e,t)=>Wa("getDBMessageData",e,t),Za=e=>Wa("getDBRoomMessageData",e),eo=(e,t)=>Wa("getDBNewChunk",e,t),to=e=>Wa("setDBChunk",e),no=e=>Wa("storeReceiveChunk",e),ro=e=>Wa("deleteReceiveTransfer",e),ao=e=>Wa("setDBNewChunk",e),oo=e=>Wa("deleteDBNewChunk",e),io=(e,t,n)=>Wa("deleteDBSendQueue",e,t,n),so=(e,t)=>Wa("deleteRatchetSession",e,t),co=(e,t)=>Wa("getPinAttemptState",e,t),lo=()=>Wa("getIdentityX25519"),uo=()=>Wa("deleteIdentityX25519"),ho=e=>Wa("setIdentityEd25519",e),fo=()=>Wa("deleteIdentityEd25519"),po=(e,t)=>new Promise((n,r)=>{try{const r=(new TextEncoder).encode(e);if(r.length<=0||r.length>32)throw new Error("Channel label must be between 1 and 32 UTF-8 bytes");if("string"==typeof t&&!/^[0-9a-f]{128}$/.test(t))throw new Error("Merkle root hex should be 128 canonical lowercase characters");if("string"!=typeof t&&t.length!==N)throw new Error("Merkle root should be 64 bytes");let a="";const o=new Uint8Array(32);o.set(r.subarray(0,Math.min(32,r.length))),a+=ca(o),a+="~",a+="string"==typeof t?t:ca(t),n(a)}catch(e){r(e)}}),mo=e=>new Promise((t,n)=>{try{const n=e.split("~"),r=n.length;if(1===r)return void t({channelLabel:e,merkleRootHex:"",merkleRoot:new Uint8Array});if(2!==r||193!==e.length)throw new Error(`Channel message label needs exactly ${String(2)} bounded components.`);if(!/^[0-9a-f]{64}~[0-9a-f]{128}$/.test(e))throw new Error("Channel message label must use canonical lowercase hex");const a=la(n[0]);if(32!==a.length)throw new Error("Channel label is not 32 bytes long.");const o=(new TextDecoder).decode(a).replace(/\0+$/,""),i=la(n[1]);if(i.length!==N)throw new Error("Merkle root has invalid length");t({channelLabel:o,merkleRoot:i,merkleRootHex:n[1]})}catch(e){n(e)}}),yo=new Map,go=(e,t,n)=>`${e}\0${t}\0${n}`,wo=(e,t,n)=>{const r=go(e,t,n);let a=yo.get(r);return a||(a={acked:new Set,complete:!1},yo.set(r,a)),a},bo=(e,t,n)=>new Set(wo(e,t,n).acked),vo=(e,t,n)=>wo(e,t,n).acked.size,ko=(e,t,n)=>{const r=wo(e,t,n);return!r.complete&&(r.complete=!0,!0)},Io=(e,t,n)=>yo.get(go(e,t,n))?.complete??!1,So=(e,t,n)=>{yo.delete(go(e,t,n))},Co=async(e,t,n,r,a)=>{const o=Date.now()+r;for(;Date.now()<o&&!Io(e,t,n)&&!a?.aborted;)await new Promise(e=>setTimeout(e,200));return!a?.aborted&&Io(e,t,n)},Ao=async(e,t,n,r,a)=>{try{const o=ca(e),{merkleRootHex:i}=await mo(t),{rooms:s}=a.getState(),c=s.find(e=>e.id===r);if(!c)return{kind:"ignored",peerId:n};const l=c.messages.findLastIndex(e=>e.merkleRootHex===i);if(l<0)return{kind:"ignored",peerId:n};const d=c.messages[l].sha512Hex,u=c.messages[l].transferId;if(!u)return{kind:"ignored",peerId:n};if(o===d){return ko(c.id,n,u)?{kind:"peer-complete",peerId:n,transferId:u,newlyAccepted:!0}:{kind:"peer-complete",peerId:n,transferId:u,newlyAccepted:!1}}{const e=await((e,t)=>Wa("getDBNewChunkByReceipt",e,t))(i,o),t=e?.chunkIndex??-1;if(e&&e.transferId===u&&t>-1){const e=((e,t,n,r)=>{const a=wo(e,t,n).acked,o=a.size;return a.add(r),a.size!==o})(c.id,n,u,t);return{kind:"chunk-acked",peerId:n,transferId:u,chunkIndex:t,newlyAccepted:e}}}return{kind:"ignored",peerId:n}}catch(e){throw console.error(e),e}},Eo=e=>{const t=new Uint8Array(ee);let n=0;new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.schemaVersion),!1),n+=8,t[n]=e.messageType,n+=1,t.set(e.hash,n),n+=N;new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.totalSize),!1),n+=8;new DataView(t.buffer,n,8).setBigInt64(0,BigInt(e.date.getTime()),!1),n+=8;const r=(new TextEncoder).encode(e.name),a=new Uint8Array(256);a.set(r.subarray(0,Math.min(256,r.length))),t.set(a,n),n+=256;new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkStartIndex),!1),n+=8;new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkEndIndex),!1),n+=8;return new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkIndex),!1),t},Po=e=>{if(e.length!==ee)throw new Error("Invalid metadata buffer totalSize");let t=0;const n=new DataView(e.buffer,e.byteOffset+t,8),r=Number(n.getBigUint64(0,!1));t+=8;const a=e[t];t+=1;const o=e.slice(t,t+N);t+=N;const i=new DataView(e.buffer,e.byteOffset+t,8),s=Number(i.getBigUint64(0,!1));t+=8;const c=new DataView(e.buffer,e.byteOffset+t,8),l=Number(c.getBigUint64(0,!1)),d=new Date(l);t+=8;const u=e.slice(t,t+256);let h=(new TextDecoder).decode(u).replace(/\0+$/,"");h=h.replace(/[/\\]/g,"_").replace(/[<>:"'|?*]/g,"_").replace(/[\u0000-\u001f\u007f]/g,""),t+=256;const f=new DataView(e.buffer,e.byteOffset+t,8),p=Number(f.getBigUint64(0,!1));t+=8;const m=new DataView(e.buffer,e.byteOffset+t,8),y=Number(m.getBigUint64(0,!1));t+=8;const g=new DataView(e.buffer,e.byteOffset+t,8);return{schemaVersion:r,messageType:a,hash:o,totalSize:s,date:d,name:h,chunkStartIndex:p,chunkEndIndex:y,chunkIndex:Number(g.getBigUint64(0,!1))}},xo={Text:1,ImagePNG:2,ImageJPEG:3,ImageJPG:4,ImageGIF:5,ImageBMP:6,ImageTIFF:7,ImageSVG:8,ImageWEBP:9,ImageHEIC:10,DocumentPDF:11,DocumentDOC:12,DocumentDOCX:13,DocumentXLS:14,DocumentXLSX:15,DocumentPPT:16,DocumentPPTX:17,DocumentTXT:18,DocumentRTF:19,DocumentODT:20,AudioMP3:21,AudioWAV:22,AudioAAC:23,AudioFLAC:24,AudioOGG:25,AudioM4A:26,VideoMP4:27,VideoAVI:28,VideoMKV:29,VideoMOV:30,VideoWMV:31,VideoFLV:32,VideoWEBM:33,CompressedZIP:34,CompressedRAR:35,Compressed7Z:36,CompressedTAR:37,CompressedGZ:38,CodeHTML:39,CodeCSS:40,CodeJS:41,CodeJSX:42,CodeTS:43,CodeTSX:44,CodeJSON:45,CodeXML:46,CodePY:47,CodeJAVA:48,CodeC:49,CodeCPP:50,CodeCS:51,CodeRB:52,CodePHP:53,CodeSQL:54,EbookEPUB:55,EbookMOBI:56,EbookAZW:57,FontTTF:58,FontOTF:59,ImageICO:60,ExecutableEXE:61,ExecutableDMG:62,ExecutableAPK:63,Unknown:64},Ko={Text:"Text",Image:"Image",Document:"Document",Audio:"Audio",Video:"Video",Compressed:"Compressed",Code:"Code",Ebook:"Ebook",Font:"Font",Executable:"Executable",Unknown:"Unknown"},Ro=e=>{switch(e){case xo.Text:return"text/plain";case xo.ImagePNG:return"image/png";case xo.ImageJPEG:case xo.ImageJPG:return"image/jpeg";case xo.ImageGIF:return"image/gif";case xo.ImageBMP:return"image/bmp";case xo.ImageTIFF:return"image/tiff";case xo.ImageSVG:return"image/svg+xml";case xo.ImageWEBP:return"image/webp";case xo.ImageHEIC:return"image/heic";case xo.ImageICO:return"image/vnd.microsoft.icon";case xo.DocumentPDF:return"application/pdf";case xo.DocumentDOC:return"application/msword";case xo.DocumentDOCX:return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case xo.DocumentXLS:return"application/vnd.ms-excel";case xo.DocumentXLSX:return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case xo.DocumentPPT:return"application/vnd.ms-powerpoint";case xo.DocumentPPTX:return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case xo.DocumentTXT:return"text/plain";case xo.DocumentRTF:return"application/rtf";case xo.DocumentODT:return"application/vnd.oasis.opendocument.text";case xo.AudioMP3:return"audio/mpeg";case xo.AudioWAV:return"audio/wav";case xo.AudioAAC:return"audio/aac";case xo.AudioFLAC:return"audio/flac";case xo.AudioOGG:return"audio/ogg";case xo.AudioM4A:return"audio/mp4";case xo.VideoMP4:return"video/mp4";case xo.VideoAVI:return"video/x-msvideo";case xo.VideoMKV:return"video/x-matroska";case xo.VideoMOV:return"video/quicktime";case xo.VideoWMV:return"video/x-ms-wmv";case xo.VideoFLV:return"video/x-flv";case xo.VideoWEBM:return"video/webm";case xo.CompressedZIP:return"application/zip";case xo.CompressedRAR:return"application/vnd.rar";case xo.Compressed7Z:return"application/x-7z-compressed";case xo.CompressedTAR:return"application/x-tar";case xo.CompressedGZ:return"application/gzip";case xo.CodeHTML:return"text/html";case xo.CodeCSS:return"text/css";case xo.CodeJS:case xo.CodeJSX:return"application/javascript";case xo.CodeTS:case xo.CodeTSX:return"application/typescript";case xo.CodeJSON:return"application/json";case xo.CodeXML:return"application/xml";case xo.CodePY:return"text/x-python";case xo.CodeJAVA:return"text/x-java-source";case xo.CodeC:return"text/x-c";case xo.CodeCPP:return"text/x-c++";case xo.CodeCS:return"text/plain";case xo.CodeRB:return"text/x-ruby";case xo.CodePHP:return"application/x-httpd-php";case xo.CodeSQL:return"application/sql";case xo.EbookEPUB:return"application/epub+zip";case xo.EbookMOBI:return"application/x-mobipocket-ebook";case xo.EbookAZW:return"application/vnd.amazon.ebook";case xo.FontTTF:return"font/ttf";case xo.FontOTF:return"font/otf";case xo.ExecutableEXE:return"application/vnd.microsoft.portable-executable";case xo.ExecutableDMG:return"application/x-apple-diskimage";case xo.ExecutableAPK:return"application/vnd.android.package-archive";default:return"application/octet-stream"}},Mo=(new TextEncoder).encode("p2party/protocol-v3/chunk-receipt/v1\0"),_o=async(e,t,n)=>{if(e.length!==N)throw new Error("Chunk receipt Merkle root must be 64 bytes");if(n.length!==N)throw new Error("Chunk receipt leaf hash must be 64 bytes");if(!Number.isSafeInteger(t)||t<0)throw new Error("Chunk receipt index must be a safe unsigned integer");const r=new Uint8Array(Mo.length+e.length+8+n.length);let a=0;return r.set(Mo,a),a+=Mo.length,r.set(e,a),a+=e.length,new DataView(r.buffer).setBigUint64(a,BigInt(t),!1),a+=8,r.set(n,a),new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",r))},Uo=e=>{const t=e._malloc(X),n=e._malloc(G);if(0!==e._x25519_keypair(t,n))throw e._free(t),Da(e,new Uint8Array(e.wasmMemory.buffer,n,G)),new Error("x25519_keypair failed");const r=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,t,X)),a=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,n,G));return e._free(t),Da(e,new Uint8Array(e.wasmMemory.buffer,n,G)),{publicKey:r,secretKey:a}},Do=async e=>{const t=e?.wasmMemory??ha(),n=e??await Ua(t);return Uo(n)},To=(e,t,n)=>{const r=n._malloc(X),a=n._malloc(G),o=n._malloc(X);new Uint8Array(n.wasmMemory.buffer,a,G).set(e),new Uint8Array(n.wasmMemory.buffer,o,X).set(t);const i=0===n._x25519_dh(r,a,o)?Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,r,X)):null;if(Da(n,new Uint8Array(n.wasmMemory.buffer,r,X)),Da(n,new Uint8Array(n.wasmMemory.buffer,a,G)),n._free(o),!i)throw new Error("x25519_dh failed (identity point)");return i},No=(e,t,n)=>{const r=Math.max(e.length,1),a=Math.max(t.length,1),o=n._malloc(T),i=n._malloc(r),s=n._malloc(a);try{new Uint8Array(n.wasmMemory.buffer,i,e.length).set(e),new Uint8Array(n.wasmMemory.buffer,s,t.length).set(t);if(0!==n._hkdf_sha512_extract(o,i,e.length,s,t.length))throw new Error("hkdf_sha512_extract failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,o,T))}finally{Da(n,new Uint8Array(n.wasmMemory.buffer,o,T)),Da(n,new Uint8Array(n.wasmMemory.buffer,i,r)),Da(n,new Uint8Array(n.wasmMemory.buffer,s,a))}},qo=(e,t,n,r)=>{const a=r._malloc(n),o=r._malloc(T),i=r._malloc(Math.max(t.length,1));try{new Uint8Array(r.wasmMemory.buffer,o,T).set(e),new Uint8Array(r.wasmMemory.buffer,i,t.length).set(t);if(0!==r._hkdf_sha512_expand(a,n,o,i,t.length))throw new Error("hkdf_sha512_expand failed");return Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,a,n))}finally{Da(r,new Uint8Array(r.wasmMemory.buffer,a,n)),Da(r,new Uint8Array(r.wasmMemory.buffer,o,T)),r._free(i)}},Oo=(new TextEncoder).encode("p2party-rk-v1"),Bo=(new TextEncoder).encode("p2party-ck-v1"),Lo=(new TextEncoder).encode("p2party-mk-v1"),Fo=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),zo=e=>{const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(2*n,2*n+2),16);return t},jo=(e,t,n)=>{const r=No(e,t,n),a=qo(r,Oo,64,n);r.fill(0);const o=a.slice(0,32),i=a.slice(32,64);return a.fill(0),{rootKey:o,chainKey:i}},Ho=(e,t)=>{const n=No(e,Lo,t),r=No(e,Bo,t),a=n.slice(0,32),o=r.slice(0,32);return n.fill(0),r.fill(0),{chainKey:o,messageKey:a}},Vo=(e,t,n,r,a=ye)=>{const o=Uo(r),i={rootSuite:a,rootKey:Uint8Array.from(e),sendingChainKey:null,receivingChainKey:null,dhSelfPub:o.publicKey,dhSelfSec:o.secretKey,dhRemotePub:null,Ns:0,Nr:0,PN:0,skipped:new Map};if(t){if(!n)throw new Error("ratchet: initiator requires remoteDhPub");i.dhRemotePub=Uint8Array.from(n);const e=To(i.dhSelfSec,i.dhRemotePub,r),t=jo(i.rootKey,e,r);e.fill(0),i.rootKey.fill(0),i.rootKey=t.rootKey,i.sendingChainKey=t.chainKey}return i},$o=(e,t)=>{if(!e.sendingChainKey)throw new Error("ratchet: no sending chain");const{chainKey:n,messageKey:r}=Ho(e.sendingChainKey,t),a={dhPub:Uint8Array.from(e.dhSelfPub),N:e.Ns,PN:e.PN};return e.sendingChainKey.fill(0),e.sendingChainKey=n,e.Ns+=1,{messageKey:r,header:a}},Qo=(e,t,n)=>{if(e.Nr+512<t)throw new Error("ratchet: MAX_SKIP exceeded");if(e.receivingChainKey){for(;e.Nr<t;){const{chainKey:t,messageKey:r}=Ho(e.receivingChainKey,n);e.receivingChainKey.fill(0),e.receivingChainKey=t,e.skipped.set(`${Fo(e.dhRemotePub)}:${e.Nr}`,r),e.Nr+=1}if(e.skipped.size>ge)for(const t of e.skipped.keys()){if(e.skipped.size<=ge)break;e.skipped.get(t)?.fill(0),e.skipped.delete(t)}}},Wo=(e,t,n)=>{e.PN=e.Ns,e.Ns=0,e.Nr=0,e.dhRemotePub=Uint8Array.from(t.dhPub);let r=To(e.dhSelfSec,e.dhRemotePub,n),a=jo(e.rootKey,r,n);r.fill(0),e.rootKey.fill(0),e.rootKey=a.rootKey,e.receivingChainKey?.fill(0),e.receivingChainKey=a.chainKey;const o=e.dhSelfSec,i=Uo(n);e.dhSelfPub=i.publicKey,e.dhSelfSec=i.secretKey,o.fill(0),r=To(e.dhSelfSec,e.dhRemotePub,n),a=jo(e.rootKey,r,n),r.fill(0),e.rootKey.fill(0),e.rootKey=a.rootKey,e.sendingChainKey?.fill(0),e.sendingChainKey=a.chainKey},Xo=(e,t,n)=>{if(!Number.isInteger(t.N)||t.N<0||!Number.isInteger(t.PN)||t.PN<0)throw new Error("invalid ratchet header");const r=((e,t)=>{const n=`${Fo(t.dhPub)}:${t.N}`,r=e.skipped.get(n);return r?(e.skipped.delete(n),r):null})(e,t);if(r)return r;if((!e.dhRemotePub||!((e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n})(t.dhPub,e.dhRemotePub))&&(Qo(e,t.PN,n),Wo(e,t,n)),t.N<e.Nr)throw new Error("ratchet: message key already consumed");Qo(e,t.N,n);const{chainKey:a,messageKey:o}=Ho(e.receivingChainKey,n);return e.receivingChainKey.fill(0),e.receivingChainKey=a,e.Nr+=1,o},Go=e=>e.slice().buffer,Jo=e=>e?e.slice().buffer:null,Yo=e=>({rootSuite:e.rootSuite,rootKey:Go(e.rootKey),sendingChainKey:Jo(e.sendingChainKey),receivingChainKey:Jo(e.receivingChainKey),dhSelfPub:Go(e.dhSelfPub),dhSelfSec:Go(e.dhSelfSec),dhRemotePub:Jo(e.dhRemotePub),Ns:e.Ns,Nr:e.Nr,PN:e.PN,skippedMessageKeys:Array.from(e.skipped.entries()).map(([e,t])=>{const n=e.lastIndexOf(":");return{dhPub:zo(e.slice(0,n)).slice().buffer,n:Number(e.slice(n+1)),messageKey:t.slice().buffer}})}),Zo=e=>{const t=new Map;for(const n of e.skippedMessageKeys){const e=new Uint8Array(n.dhPub);t.set(`${Fo(e)}:${n.n}`,new Uint8Array(n.messageKey))}return{rootSuite:e.rootSuite,rootKey:new Uint8Array(e.rootKey),sendingChainKey:e.sendingChainKey?new Uint8Array(e.sendingChainKey):null,receivingChainKey:e.receivingChainKey?new Uint8Array(e.receivingChainKey):null,dhSelfPub:new Uint8Array(e.dhSelfPub),dhSelfSec:new Uint8Array(e.dhSelfSec),dhRemotePub:e.dhRemotePub?new Uint8Array(e.dhRemotePub):null,Ns:e.Ns,Nr:e.Nr,PN:e.PN,skipped:t}},ei=e=>Zo(Yo(e)),ti=e=>{e.rootKey.fill(0),e.sendingChainKey?.fill(0),e.receivingChainKey?.fill(0),e.dhSelfSec.fill(0);for(const t of e.skipped.values())t.fill(0)},ni=(e,t)=>{if(e.rootSuite!==t.rootSuite)throw new Error("ratchet: cannot adopt a different root suite");ti(e),e.rootSuite=t.rootSuite,e.rootKey=t.rootKey,e.sendingChainKey=t.sendingChainKey,e.receivingChainKey=t.receivingChainKey,e.dhSelfPub=t.dhSelfPub,e.dhSelfSec=t.dhSelfSec,e.dhRemotePub=t.dhRemotePub,e.Ns=t.Ns,e.Nr=t.Nr,e.PN=t.PN,e.skipped=t.skipped},ri=(1n<<64n)-1n,ai=(e,t,n)=>{if(!Number.isInteger(n)||n<0||n>Number.MAX_SAFE_INTEGER)throw new Error("chunkFrame: ratchet counter out of safe-integer range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(t,BigInt(n),!1)},oi=(e,t)=>{const n=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(t,!1);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("chunkFrame: ratchet counter exceeds safe-integer range");return Number(n)},ii=(e,t,n=0n)=>{if(e.dhPub.length!==ce)throw new Error("chunkFrame: dhPub must be 32 bytes");if(t.length!==le)throw new Error("chunkFrame: nonce must be 12 bytes");const r=new Uint8Array(69);return r[0]=2,r.set(e.dhPub,1),ai(r,33,e.N),ai(r,41,e.PN),((e,t,n)=>{if("bigint"!=typeof n||n<0n||n>ri)throw new Error("chunkFrame: PQ epoch out of u64 range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(t,n,!1)})(r,49,n),r.set(t,57),r},si=e=>{if(e.length<69)throw new Error("chunkFrame: frame shorter than the header");if(2!==e[0])throw new Error("chunkFrame: leading byte is not FRAME_TYPE_CHUNK");return{header:{dhPub:e.subarray(1,33),N:oi(e,33),PN:oi(e,41)},pqEpoch:(t=e,n=49,new DataView(t.buffer,t.byteOffset,t.byteLength).getBigUint64(n,!1)),nonce:e.subarray(57,69),ciphertext:e.subarray(69)};var t,n},ci=z,li=(1n<<64n)-1n,di=(new TextEncoder).encode("p2party/pq-message-key/v1\0"),ui=(e,t,n)=>{if(!(e instanceof Uint8Array)||e.length!==n)throw new Error(`pqMessageKey: ${t} must be ${String(n)} bytes`)},hi=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new Error(`pqMessageKey: ${t} is outside the safe u64 range`)},fi=(e,t)=>{if("string"!=typeof(n=e.rootSuite)||!me.includes(n))throw new Error("pqMessageKey: unsupported root suite");var n;ui(e.rootKey,"rootKey",32),ui(e.binding,"binding",32),(e=>{if("bigint"!=typeof e||e<0n||e>li)throw new Error("pqMessageKey: epoch is outside the u64 range")})(e.epoch),ui(t.dhPub,"header.dhPub",ce),hi(t.N,"header.N"),hi(t.PN,"header.PN");const r=(new TextEncoder).encode(e.rootSuite);if(r.length>65535)throw new Error("pqMessageKey: root suite identifier is too long");const a=di.length+2+r.length+32+8+1+ce+8+8,o=new Uint8Array(a);let i=0;o.set(di,i),i+=di.length;const s=new DataView(o.buffer);return s.setUint16(i,r.length,!1),i+=2,o.set(r,i),i+=r.length,o.set(e.binding,i),i+=32,s.setBigUint64(i,e.epoch,!1),i+=8,o[i++]=2,o.set(t.dhPub,i),i+=ce,s.setBigUint64(i,BigInt(t.N),!1),i+=8,s.setBigUint64(i,BigInt(t.PN),!1),o},pi=(e,t,n,r)=>{if(!(e instanceof Uint8Array))throw new Error("pqMessageKey: classicalMessageKey must be a Uint8Array");if(t?.rootKey instanceof Uint8Array&&(a=e,o=t.rootKey,a.buffer===o.buffer&&a.byteOffset<o.byteOffset+o.byteLength&&o.byteOffset<a.byteOffset+a.byteLength))throw new Error("pqMessageKey: classicalMessageKey must not alias context.rootKey");var a,o;let i=null,s=null;try{ui(e,"classicalMessageKey",ci);const a=fi(t,n);return i=Uint8Array.from(t.rootKey),s=No(i,e,r),qo(s,a,ci,r)}finally{e.fill(0),i?.fill(0),s?.fill(0)}},mi=z,yi=j,gi=H,wi=N+57,bi=(1n<<64n)-1n,vi=(e,t,n)=>{const r=`${a=e,Array.from(a,e=>e.toString(16).padStart(2,"0")).join("")}:${t}`;var a;if(void 0===n)return r;if("bigint"!=typeof n||n<0n||n>bi)throw new Error("messageChunkCrypto: PQ epoch out of u64 range");return`${r}:${n.toString(10)}`},ki=(e,t,n,r)=>{const a=e._malloc(J),o=e._malloc(ae),i=e._malloc(N),s=e._malloc(mi),c=new Uint8Array(e.wasmMemory.buffer,a,J),l=new Uint8Array(e.wasmMemory.buffer,o,ae);c.fill(0),l.fill(0),c.set(t.subarray(0,J),0),new Uint8Array(e.wasmMemory.buffer,i,N).set(n),new Uint8Array(e.wasmMemory.buffer,s,mi).set(r);const d=e._receive_message_with_key(o,a,i,s),u=0===d?Uint8Array.from(l):null;return e._free(a),e._free(i),Da(e,new Uint8Array(e.wasmMemory.buffer,s,mi)),Da(e,l),{code:d,decrypted:u}},Ii=(e,t,n,r,a,o)=>{if(r.length!==N)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const i=(()=>{const e=new Uint8Array(yi);return crypto.getRandomValues(e),e})(),s=ii(t,i,o?.epoch??0n),c=((e,t)=>{if(t.length<57)throw new Error("messageChunkCrypto: incomplete chunk frame header");const n=new Uint8Array(wi);return n.set(e,0),n.set(t.subarray(0,57),N),n})(r,s);let l=null;try{const r=((e,t,n,r,a)=>{const o=Math.max(r.length,1),i=Math.max(a.length,1),s=r.length+gi,c=e._malloc(mi),l=e._malloc(yi),d=e._malloc(o),u=e._malloc(i),h=e._malloc(s);new Uint8Array(e.wasmMemory.buffer,c,mi).set(t),new Uint8Array(e.wasmMemory.buffer,l,yi).set(n),r.length&&new Uint8Array(e.wasmMemory.buffer,d,r.length).set(r),a.length&&new Uint8Array(e.wasmMemory.buffer,u,a.length).set(a);const f=0===e._encrypt_chachapoly_symmetric(h,d,r.length,c,l,u,a.length)?Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,h,s)):null;if(Da(e,new Uint8Array(e.wasmMemory.buffer,c,mi)),e._free(l),Da(e,new Uint8Array(e.wasmMemory.buffer,d,o)),e._free(u),Da(e,new Uint8Array(e.wasmMemory.buffer,h,s)),!f)throw new Error("messageChunkCrypto: AEAD encrypt failed");return f})(a,o?l=pi(Uint8Array.from(e),o,t,a):e,i,n,c),d=new Uint8Array(s.length+r.length);return d.set(s,0),d.set(r,s.length),d}finally{l?.fill(0)}},Si=(e,t,n,r,a,o)=>{if(r.length!==N)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const{header:i,pqEpoch:s}=si(t);let c=null;if(o){try{c=o(s)}catch{return{decrypted:null,ok:!1,stateAdvanced:!1}}if(!(c&&(l=c,d=s,u=e.rootSuite,l.epoch===d&&l.rootSuite===u&&l.rootKey instanceof Uint8Array&&32===l.rootKey.length&&l.binding instanceof Uint8Array&&32===l.binding.length)))return{decrypted:null,ok:!1,stateAdvanced:!1}}else if(0n!==s)return{decrypted:null,ok:!1,stateAdvanced:!1};var l,d,u;const h=vi(i.dhPub,i.N,o?s:void 0),f=n.get(h);if(f){const{code:e,decrypted:n}=ki(a,t,r,f);return{decrypted:0===e?n:null,ok:0===e,stateAdvanced:!1}}const p=ei(e);let m;try{m=Ci(p,i,a),c&&(m=pi(m,c,i,a))}catch{return ti(p),{decrypted:null,ok:!1,stateAdvanced:!1}}const{code:y,decrypted:g}=ki(a,t,r,m);return-2===y?(m.fill(0),ti(p),{decrypted:null,ok:!1,stateAdvanced:!1}):(ni(e,p),n.set(h,m),{decrypted:0===y?g:null,ok:0===y,stateAdvanced:!0})},Ci=(e,t,n)=>{try{return Xo(e,t,n)}catch(t){throw ti(e),t}},Ai=(e,t)=>`${e.length}:${e}${t.length}:${t}`,Ei=new Map,Pi=new Map,xi=new WeakMap,Ki=async(e,t,n)=>{const r=Ai(e,t),a=Ei.get(r)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=a.catch(()=>{}).then(()=>i);Ei.set(r,s),await a.catch(()=>{});try{return await n()}finally{o(),Ei.get(r)===s&&Ei.delete(r)}},Ri=(e,t)=>{const n=Ai(t,e.withPeerPublicKey),r=xi.get(e);if(r){if(Pi.get(n)!==r)throw new Error("ratchet persistence: stale connection cannot reclaim edge");return}const a=Symbol(n);xi.set(e,a),Pi.set(n,a)},Mi=(e,t)=>{const n=Ai(t,e.withPeerPublicKey),r=xi.get(e);if(!r||Pi.get(n)!==r)throw new Error("ratchet persistence: stale connection owner")},_i=async(e,t,n,r,a=null)=>{const o=Yo(e),i={rootSuite:o.rootSuite,roomId:t,peerPublicKey:n,peerId:r,rootKey:o.rootKey,sendingChainKey:o.sendingChainKey,receivingChainKey:o.receivingChainKey,dhSelfPub:o.dhSelfPub,dhSelfSec:o.dhSelfSec,dhRemotePub:o.dhRemotePub,Ns:o.Ns,Nr:o.Nr,PN:o.PN,skippedMessageKeys:o.skippedMessageKeys,edgeCryptoState:null===a?null:a.slice().buffer,updatedAt:Date.now()};try{await(e=>Wa("setRatchetSession",e))(i)}finally{(e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)})(i)}},Ui=async(e,t,n,r,a=null)=>Ki(t,n,()=>_i(e,t,n,r,a)),Di=async(e,t,n,r,a=_i,o=so)=>Ki(n,e.withPeerPublicKey,async()=>{Mi(e,n);let i=!1;const s=e.serializeEdgeCryptoState?.()??null;try{i=!0,await a(t,n,e.withPeerPublicKey,e.withPeerId,s),Mi(e,n),r()}catch(t){if(i)try{await o(n,e.withPeerPublicKey)}catch(e){throw new AggregateError([t,e],"Ratchet establishment failed and persisted-seed rollback failed",{cause:e})}throw t}finally{s?.fill(0)}}),Ti=new WeakMap,Ni=async(e,t)=>{const n=Ti.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>a);Ti.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),Ti.get(e)===o&&Ti.delete(e)}},qi=async(e,t,n,r)=>Ni(e,async()=>{const a=e.ratchetState;if(!a)throw new Error("ratchet persistence: no live ratchet state");const o=ei(a);let i,s=!1;try{if(i=n(o),i.advanced){const n=i.stageEdgeCryptoState;if(r===Ui)await Ki(t,e.withPeerPublicKey,async()=>{if(Mi(e,t),e.ratchetState!==a)throw new Error("ratchet persistence: live state changed");const r=n?.()??e.serializeEdgeCryptoState?.()??null;try{await _i(o,t,e.withPeerPublicKey,e.withPeerId,r)}finally{r?.fill(0)}Mi(e,t)});else{const a=n?.()??e.serializeEdgeCryptoState?.()??null;try{await r(o,t,e.withPeerPublicKey,e.withPeerId,a)}finally{a?.fill(0)}}if(e.ratchetState!==a)throw new Error("ratchet persistence: live state changed");ni(a,o),s=!0}else ti(o);return i.commit?.(),i.value}catch(e){throw s||ti(o),i?.rollback?.(),e}}),Oi=async(e,t,n,r=Ui)=>qi(e,t,t=>{const r=$o(t,n),a=e.pqHealingState;let o=null;if(a){const e=a.currentMessageContext();o={rootKey:Uint8Array.from(e.rootKey),binding:Uint8Array.from(e.binding),rootSuite:e.rootSuite,epoch:e.epoch}}return{value:{messageKey:r.messageKey,header:r.header,pqContext:o},advanced:!0,commit:()=>e.pqHealingState?.noteApplicationMessage(),rollback:()=>{r.messageKey.fill(0),o?.rootKey.fill(0)}}},r),Bi=async(e,t,n,r,a=Ui)=>qi(e,t,t=>{const a=e.pqHealingState;if(a){if(!n.has(r))return{value:void 0,advanced:!1};const e=new Map(n);return e.delete(r),{value:void 0,advanced:!0,stageEdgeCryptoState:()=>a.serialize(e),commit:()=>{n.get(r)?.fill(0),n.delete(r)}}}const o=t.skipped.get(r);return o&&(t.skipped.delete(r),o.fill(0)),{value:void 0,advanced:void 0!==o,commit:()=>{n.get(r)?.fill(0),n.delete(r)}}},a),Li=new WeakMap,Fi=async(e,t,n,r=Bi)=>{let a=Li.get(e);const o=a?.get(n);if(o)return o;const i=(async()=>{const a=e.messageKeyByMerkleRoot?.get(n),o=e.messageKeyCache;return!(!a||!o)&&(await r(e,t,o,a),e.messageKeyByMerkleRoot?.get(n)===a&&e.messageKeyByMerkleRoot.delete(n),!0)})();a??=new Map,a.set(n,i),Li.set(e,a);try{return await i}finally{a.get(n)===i&&a.delete(n),0===a.size&&Li.delete(e)}},zi=async(e,t,n,r,a=Bi)=>!!(e=>void 0!==e&&Number.isSafeInteger(e.savedSize)&&Number.isSafeInteger(e.totalSize)&&e.savedSize>=0&&e.totalSize>0&&e.savedSize===e.totalSize)(r)&&Fi(e,t,n,a),ji=()=>({date:new Date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!1,totalSize:0,messageType:xo.Text,filename:"",chunkHash:new Uint8Array,messageHash:new Uint8Array}),Hi=async(e,t,n=no)=>{try{return await n({...e,data:t.buffer})}catch(e){return console.error("Could not durably store received chunk",e),null}finally{t.fill(0)}},Vi=async(e,t,n,r,a,o,i,s={})=>{if(i?.aborted)return ji();if(!r.ratchetState)return console.error("v3 receive: no ratchet state for peer"),ji();r.messageKeyCache||(r.messageKeyCache=r.pqHealingState?.activeReceiveKeys??new Map);const c=r.messageKeyCache;let l;try{const{header:t,pqEpoch:n}=si(e);l=vi(t.dhPub,t.N,r.pqHealingState?n:void 0)}catch{return ji()}if(c.size>=256)for(const e of c.keys()){if(c.size<256)break;if(c.get(e)?.fill(0),c.delete(e),r.messageKeyByMerkleRoot)for(const[t,n]of r.messageKeyByMerkleRoot)n===e&&r.messageKeyByMerkleRoot.delete(t)}let d,u;try{const n=await(async(e,t,n,r,a,o,i=Ui)=>qi(e,t,t=>{const i=e.pqHealingState,{header:s,pqEpoch:c}=si(n),l=vi(s.dhPub,s.N,i?c:void 0),d=new Map(r),u=Si(t,n,d,a,o,i?e=>i.resolveMessageContext(e):void 0);if(!u.stateAdvanced)return{value:u,advanced:!1};const h=d.get(l);if(!h||r.has(l))throw u.decrypted?.fill(0),new Error("ratchet persistence: invalid staged receive cache");if(i)return{value:u,advanced:!0,stageEdgeCryptoState:()=>i.serialize(d),commit:()=>{r.set(l,h),i.noteApplicationMessage()},rollback:()=>{h.fill(0),u.decrypted?.fill(0)}};const f=Uint8Array.from(h);for(t.skipped.set(l,f);t.skipped.size>ge;){const e=t.skipped.keys().next().value;if(void 0===e)break;t.skipped.get(e)?.fill(0),t.skipped.delete(e)}return{value:u,advanced:!0,commit:()=>r.set(l,h),rollback:()=>{f.fill(0),h.fill(0),u.decrypted?.fill(0)}}},i))(r,t,e,c,a,o,s.persistRatchetState);d=n.decrypted,u=n.ok}catch(e){return console.error("Could not durably decrypt message",e),ji()}if(!u||!d)return console.error("Could not decrypt or verify message"),ji();const h=ca(a);((e,t,n)=>{e.messageKeyByMerkleRoot??=new Map,e.messageKeyByMerkleRoot.set(t,n)})(r,h,l);try{if(i?.aborted)return ji();const e=d.subarray(0,ee),o=d.slice(ee,ee+N),c=d.subarray(ee+te),l=Po(e);(e=>{if(1!==e.schemaVersion)throw new Error("Unsupported metadata schema version");if(!Number.isSafeInteger(e.messageType)||e.messageType<1||e.messageType>64)throw new Error("Invalid metadata message type");if(e.hash.length!==N)throw new Error("Invalid metadata hash");if(!Number.isSafeInteger(e.totalSize)||e.totalSize<1||e.totalSize>Y)throw new Error("Invalid metadata total size");if(!Number.isSafeInteger(e.date.getTime()))throw new Error("Invalid metadata timestamp");for(const[t,n]of[["chunkStartIndex",e.chunkStartIndex],["chunkEndIndex",e.chunkEndIndex],["chunkIndex",e.chunkIndex]])if(!Number.isSafeInteger(n)||n<0)throw new Error(`Invalid metadata ${t}`);if(e.chunkEndIndex<e.chunkStartIndex)throw new Error("Invalid metadata chunk range")})(l);const u=l.chunkEndIndex-l.chunkStartIndex>l.totalSize||l.chunkEndIndex-l.chunkStartIndex>J?0:l.chunkEndIndex-l.chunkStartIndex,y=()=>({date:l.date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!0,totalSize:l.totalSize,messageType:l.messageType,filename:l.name,chunkHash:o,messageHash:l.hash});if(0===u)return y();if(f=l.chunkStartIndex,p=l.chunkEndIndex,m=c.length,!(Number.isSafeInteger(f)&&Number.isSafeInteger(p)&&f>=0&&p>=f&&p<=m))return y();const g=await _o(a,l.chunkIndex,o);if(i?.aborted)return g.fill(0),ji();const w=Ro(l.messageType),b=c.slice(l.chunkStartIndex,l.chunkEndIndex),v=await Hi({schemaVersion:l.schemaVersion,roomId:t,fromPeerId:r.withPeerId,channelLabel:n,timestamp:l.date.getTime(),merkleRoot:h,hash:ca(l.hash),filename:l.name,messageType:l.messageType,chunkIndex:l.chunkIndex,mimeType:w,leafHash:ca(o),realLen:u,totalSize:l.totalSize,storage:l.messageType===xo.Text?"indexeddb":"opfs"},b,s.storeReceiveChunk);if(!v)return g.fill(0),ji();if(i?.aborted)return g.fill(0),ji();const k=v.complete;return{date:l.date,chunkIndex:l.chunkIndex,chunkSize:u,receivedFullSize:k,chunkAlreadyExists:!v.stored,totalSize:l.totalSize,messageType:l.messageType,filename:l.name,chunkHash:g,messageHash:l.hash}}catch(e){return console.error("Could not parse or store decrypted message",e),ji()}finally{d.fill(0)}var f,p,m},$i=new Map,Qi=(e,t)=>`${e}\0${t}`,Wi=(e,t)=>{const n=Qi(e,t);let r=$i.get(n);if(!r){let e,t;const a=new Promise((n,r)=>{e=n,t=r});a.catch(()=>{}),r={promise:a,resolve:e,reject:t,settled:!1,outcome:"pending",lease:{token:Symbol("ratchet-gate")}},$i.set(n,r)}return r},Xi=(e,t)=>Wi(e,t).promise,Gi=(e,t,n)=>$i.get(Qi(e,t))?.lease===n,Ji=(e,t,n)=>{const r=$i.get(Qi(e,t));return"open"===r?.outcome&&(void 0===n||r.lease===n)},Yi=(e,t,n,r)=>{const a=Wi(e,t);return(!r||a.lease===r)&&(a.settled||(a.settled=!0,a.outcome="rejected",a.reject(n)),!0)},Zi=e=>{if(e.length!==oe)throw new Error("Receipt token must be exactly 64 bytes");const t=new Uint8Array(ie);return t[0]=3,t.set(e,1),t},es=(e,t)=>"open"===e.readyState&&(e.send(Zi(t).buffer),!0),ts=async(e,t)=>{let n=0;for(const r of t){for(;"open"===e.readyState&&e.bufferedAmount>=Z;)await new Promise(e=>setTimeout(e,25));if("open"!==e.readyState)return!1;e.send(Zi(r).buffer),n++,32===n&&(n=0,await new Promise(e=>setTimeout(e,10)))}return"open"===e.readyState},ns=new WeakMap,rs=(e,t,n)=>{const r=e.coverRuntime;if(!r)return!1;if(64!==t.length||64!==n.length)return!1;const a=(e=>{let t=ns.get(e);return t||(t={pending:[],drainJobActive:!1,jobSequence:0},ns.set(e,t)),t})(e);for(a.pending.push({merkleRoot:Uint8Array.from(t),token:Uint8Array.from(n)});a.pending.length>4096;)a.pending.shift();return as(e,r,a),!0},as=(e,t,n)=>{if(n.drainJobActive||0===n.pending.length)return;const r=t.cellsPerLanePerCycle(),a=Math.min(n.pending.length,r);if(a<=0)return;n.drainJobActive=!0,n.jobSequence+=1;const o={id:t.randomLaneLabel(),kind:"control",declaredCellCount:a,nextCell:()=>{const e=n.pending.shift();if(!e)return null;try{return t.sealCoverContent({subtype:"receipt",merkleRoot:e.merkleRoot,token:e.token})}finally{e.merkleRoot.fill(0),e.token.fill(0)}}};try{t.enqueue(o)}catch(e){return n.drainJobActive=!1,void console.error("coverTransfer: could not enqueue receipt drain job",e)}t.onJobSettled(o.id,()=>{n.drainJobActive=!1,as(e,t,n)})},os=e=>{const t=ns.get(e);if(t){for(const e of t.pending)e.merkleRoot.fill(0),e.token.fill(0);t.pending.length=0,t.drainJobActive=!1,ns.delete(e)}},is=e=>{const t=e.runtime.cellsPerLanePerCycle();if(e.totalChunks>t)throw new Error(`coverTransfer: message of ${String(e.totalChunks)} cells exceeds the room F×D capacity of ${String(t)}`);const n=e.realChunkIndices??Array.from({length:e.totalChunks},(e,t)=>t);let r=0;return{id:e.channelMessageLabel,kind:"real",declaredCellCount:e.totalChunks,nextCell:async t=>{const a=(()=>{const t=e.getAckedChunks?.()??ss;for(;r<n.length;){const e=n[r];if(r+=1,!t.has(e))return e}return null})();if(null===a)return null;const o=await e.sealSlotCell(a);if(null===o)return null;if(o.length!==de)throw new Error("coverTransfer: sealed transfer cell is not the uniform length");return o}}},ss=new Set,cs=e=>{if(e.byteLength<32)return`${String(e.byteLength)}:${ca(e)}`;const t=new DataView(e.buffer,e.byteOffset,16),n=new DataView(e.buffer,e.byteOffset+e.byteLength-16,16);return t.getBigUint64(0,!1).toString(16).padStart(16,"0")+t.getBigUint64(8,!1).toString(16).padStart(16,"0")+n.getBigUint64(0,!1).toString(16).padStart(16,"0")+n.getBigUint64(8,!1).toString(16).padStart(16,"0")},ls=new Map,ds=new Map,us=new WeakMap,hs=new Map,fs=(e,t)=>`${String(e.length)}:${e}${t}`,ps=(e,t)=>{if(t.value||e.length>0)return;const n=t.idleWaiters;if(t.idleWaiters=void 0,n)for(const e of n)e()},ms=(e,t)=>t.value||0!==e.length?new Promise(e=>{t.idleWaiters??=new Set,t.idleWaiters.add(e)}):Promise.resolve(),ys=(e,t,n,r)=>{const a=Math.max(0,(us.get(e)??0)+r);0===a?us.delete(e):us.set(e,a);const o=fs(t,n),i=Math.max(0,(ds.get(o)??0)+r);0===i?ds.delete(o):ds.set(o,i)},gs=async(e,t)=>{const n=ls.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.then(()=>a);ls.set(e,o),await n;try{return await t()}finally{r(),ls.get(e)===o&&ls.delete(e)}},ws=(e,t)=>{const n=fs(e.roomId,e.peerId),r=Math.max(0,(hs.get(n)??0)+t);0===r?hs.delete(n):hs.set(n,r)},bs=async(e,t)=>{if(e.draining||e.released)return;e.draining=!0;const n=fs(e.roomId,e.peerId);try{for(;!e.released;){const r=e.pending.shift();if(!r)break;ws(e,-1);try{await gs(n,()=>t(r))}finally{e.seen.delete(cs(r))}}}catch(e){console.error(e)}finally{e.draining=!1,!e.released&&e.pending.length>0&&bs(e,t)}},vs=async(e,t,n,r,a,o,i,s,c,l,d)=>{if(d?.aborted)return{receivedFullSize:!1};if(c)try{const u=c.ratchetGateLease;if(!Gi(n,r,u))return{receivedFullSize:!1};if(await Xi(n,r),d?.aborted)return{receivedFullSize:!1};if(!Gi(n,r,u))return{receivedFullSize:!1};const h=await Vi(e,n,a,c,i,l,d),{date:f,chunkSize:p,chunkIndex:m,receivedFullSize:y,chunkAlreadyExists:g,totalSize:w,messageType:b,filename:v,messageHash:k}=h;if(d?.aborted)return{receivedFullSize:!1};c?.coverRuntime||((e,t)=>{if(e.totalSize>0&&e.chunkHash.length===N&&e.chunkIndex>-1&&e.chunkSize>0)return!!t&&es(t,e.chunkHash);if("open"!==t?.readyState)return!1;const n=new Uint8Array(N);crypto.getRandomValues(n),es(t,n)})(h,s);const I=ca(k);return y&&c?.coverRuntime&&rs(c,i,i),y?(await(e=>Wa("closeReceiveFile",e))(o),t.dispatch(lt({roomId:n,merkleRootHex:o,sha512Hex:I,fromPeerId:r,totalSize:w,messageType:b,filename:v,channelLabel:a,timestamp:f.getTime(),alsoSendFinishedMessage:!0})),(e=>void 0===e?.coverRuntime)(c)&&s&&es(s,k)):p>0&&m>-1&&!g&&t.dispatch(ct({roomId:n,merkleRootHex:o,sha512Hex:I,fromPeerId:r,chunkSize:p,totalSize:w,messageType:b,filename:v,channelLabel:a,timestamp:f.getTime()})),t.dispatch(dt({roomId:n,merkleRootHex:o,real:p>0&&m>-1&&!g})),{receivedFullSize:y}}catch(e){return console.error(e),{receivedFullSize:!1}}return{receivedFullSize:!1}},ks=async(e,t,n,r,a,o,i,s,c,l,d,u,h)=>{if(n.value||n.released||h?.aborted)return;n.value=!0;const f=fs(a,o);try{for(;!n.released&&!h?.aborted;){const t=e.pop();if(!t)break;ys(e,a,o,-t.byteLength),await gs(f,async()=>vs(t,r,a,o,i,s,c,l,d,u,h))}}finally{n.value=!1,e.length>0&&!n.released&&!h?.aborted?ks(e,t,n,r,a,o,i,s,c,l,d,u,h):ps(e,n)}},Is=e=>Object.freeze({...e,wasmExports:Object.freeze({...e.wasmExports})}),Ss=Is({parameterSet:512,standardName:"ML-KEM-512",publicKeyBytes:800,secretKeyBytes:1632,ciphertextBytes:768,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem512_keypair",encaps:"_mlkem512_encaps",decaps:"_mlkem512_decaps"}}),Cs=Is({parameterSet:768,standardName:"ML-KEM-768",publicKeyBytes:1184,secretKeyBytes:2400,ciphertextBytes:1088,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem768_keypair",encaps:"_mlkem768_encaps",decaps:"_mlkem768_decaps"}}),As=Is({parameterSet:1024,standardName:"ML-KEM-1024",publicKeyBytes:1568,secretKeyBytes:3168,ciphertextBytes:1568,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem1024_keypair",encaps:"_mlkem1024_encaps",decaps:"_mlkem1024_decaps"}}),Es=Object.freeze({512:Ss,768:Cs,1024:As}),Ps=e=>{const t=Es[e];if(void 0===t)throw new RangeError(`unsupported ML-KEM parameter set: ${String(e)}`);return t},xs=(e,t,n)=>{if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(e.length!==n)throw new RangeError(`${t} must be exactly ${String(n)} bytes`)},Ks=(e,t,n,r)=>{const a=e._malloc(n);if(0===a)throw new Error(`${t.standardName}: failed to allocate ${r}`);return a},Rs=(e,t,n)=>new Uint8Array(e.wasmMemory.buffer,t,n),Ms=(e,t)=>{void 0!==t&&e._free(t)},_s=(e,t,n)=>{void 0!==t&&Da(e,Rs(e,t,n))};class Us{#e;#t;suite;constructor(e,t){this.#e=e,this.suite=t,this.#t=((e,t)=>{const n=e,r=t.wasmExports,a=[r.keypair,r.encaps,r.decaps].filter(e=>"function"!=typeof n[e]);if(0!==a.length)throw new Error(`${t.standardName} WASM exports are unavailable; rebuild libcrypto.wasm (missing ${a.join(", ")})`);return{keypair:n[r.keypair].bind(e),encaps:n[r.encaps].bind(e),decaps:n[r.decaps].bind(e)}})(e,t)}async generateKeyPair(){await Promise.resolve();const e=this.#e,t=this.suite;let n,r,a;try{n=Ks(e,t,t.publicKeyBytes,"public key"),r=Ks(e,t,t.secretKeyBytes,"secret key"),a=Ks(e,t,t.keyPairRandomBytes,"key-generation randomness");const o=Rs(e,a,t.keyPairRandomBytes);Pa(o);const i=this.#t.keypair(n,r,a);if(0!==i)throw new Error(`${t.standardName} key generation failed (${String(i)})`);return((e,t)=>{let n=!1;return{publicKey:e,secretKey:t,get destroyed(){return n},destroy(){n||(t.fill(0),n=!0)}}})(Uint8Array.from(Rs(e,n,t.publicKeyBytes)),Uint8Array.from(Rs(e,r,t.secretKeyBytes)))}finally{Ms(e,n),_s(e,r,t.secretKeyBytes),_s(e,a,t.keyPairRandomBytes)}}async encapsulate(e){await Promise.resolve();const t=this.#e,n=this.suite;let r,a,o,i;xs(e,`${n.standardName} public key`,n.publicKeyBytes);try{r=Ks(t,n,n.ciphertextBytes,"ciphertext"),a=Ks(t,n,n.sharedSecretBytes,"shared secret"),o=Ks(t,n,n.publicKeyBytes,"public key"),i=Ks(t,n,n.encapsRandomBytes,"encapsulation randomness"),Rs(t,o,n.publicKeyBytes).set(e);const s=Rs(t,i,n.encapsRandomBytes);Pa(s);const c=this.#t.encaps(r,a,o,i);if(0!==c)throw new Error(`${n.standardName} encapsulation failed (${String(c)})`);return((e,t)=>{let n=!1;return{ciphertext:e,sharedSecret:t,get destroyed(){return n},destroy(){n||(t.fill(0),n=!0)}}})(Uint8Array.from(Rs(t,r,n.ciphertextBytes)),Uint8Array.from(Rs(t,a,n.sharedSecretBytes)))}finally{Ms(t,r),_s(t,a,n.sharedSecretBytes),Ms(t,o),_s(t,i,n.encapsRandomBytes)}}async decapsulate(e,t){await Promise.resolve();const n=this.#e,r=this.suite;let a,o,i;xs(e,`${r.standardName} ciphertext`,r.ciphertextBytes),xs(t,`${r.standardName} secret key`,r.secretKeyBytes);try{a=Ks(n,r,r.sharedSecretBytes,"shared secret"),o=Ks(n,r,r.ciphertextBytes,"ciphertext"),i=Ks(n,r,r.secretKeyBytes,"secret key"),Rs(n,o,r.ciphertextBytes).set(e),Rs(n,i,r.secretKeyBytes).set(t);const s=this.#t.decaps(a,o,i);if(0!==s)throw new Error(`${r.standardName} decapsulation failed (${String(s)})`);return(e=>{let t=!1;return{sharedSecret:e,get destroyed(){return t},destroy(){t||(e.fill(0),t=!0)}}})(Uint8Array.from(Rs(n,a,r.sharedSecretBytes)))}finally{_s(n,a,r.sharedSecretBytes),Ms(n,o),_s(n,i,r.secretKeyBytes)}}}const Ds=(e,t)=>{const n=Ps(t.parameterSet);if(t!==n)throw new TypeError("ML-KEM suite descriptor must be one of the exported canonical suites");return new Us(e,n)},Ts=32,Ns=32,qs=64,Os=new Uint8Array([80,50,81,72]),Bs=(new TextEncoder).encode("p2party/pq-healing/root/v1\0"),Ls=(1n<<64n)-1n;class Fs extends Error{code;constructor(e,t){super(`pqHealing: ${t}`),this.name="PqHealingError",this.code=e}}const zs=(e,t)=>{throw new Fs(e,t)},js=(e,t,n)=>e instanceof Uint8Array?e.length!==n?zs("invalid-record",`${t} must be exactly ${String(n)} bytes`):e:zs("invalid-record",`${t} must be a Uint8Array`),Hs=(e,t)=>{("bigint"!=typeof e||e<0n||e>Ls)&&zs("overflow",`${t} is outside the unsigned 64-bit range`)},Vs=(e,t)=>{Hs(e,t),e===Ls&&zs("overflow",`${t} cannot advance beyond uint64`)},$s=e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return zs("invalid-record","advance acknowledgement must be a plain record");const t=e,n=Reflect.ownKeys(t);2===n.length&&n.includes("epoch")&&n.includes("advanceCounter")||zs("invalid-record","advance acknowledgement must contain only epoch and advanceCounter");const r=Object.getOwnPropertyDescriptor(t,"epoch"),a=Object.getOwnPropertyDescriptor(t,"advanceCounter");if(!(void 0!==r&&void 0!==a&&"value"in r&&"value"in a&&r.enumerable&&a.enumerable))return zs("invalid-record","advance acknowledgement fields must be enumerable data properties");const o=r.value,i=a.value;return"bigint"!=typeof o||"bigint"!=typeof i?zs("invalid-record","advance acknowledgement fields must be bigint values"):(Hs(o,"advance acknowledgement epoch"),Hs(i,"advance acknowledgement counter"),{epoch:o,advanceCounter:i})},Qs=(e,t,n)=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return zs("invalid-record",`${t} must be a plain record`);const r=e,a=Reflect.ownKeys(r);if(a.length!==n.length||n.some(e=>!a.includes(e)))return zs("invalid-record",`${t} does not contain exactly its canonical fields`);for(const e of n){const n=Object.getOwnPropertyDescriptor(r,e);void 0!==n&&"value"in n&&n.enumerable||zs("invalid-record",`${t}.${e} must be an enumerable data property`)}return r},Ws=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},Xs=e=>768===e?1:512===e?2:1024===e?3:zs("suite-mismatch","unsupported ML-KEM parameter set"),Gs=e=>1===e?768:2===e?512:3===e?1024:zs("invalid-record","record has an unknown ML-KEM suite tag"),Js=(e,t)=>Reflect.get(e,t),Ys=e=>{const t=Ps(e.parameterSet);e.standardName===t.standardName&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes&&Js(e,"sharedSecretBytes")===t.sharedSecretBytes&&Js(e,"keyPairRandomBytes")===t.keyPairRandomBytes&&Js(e,"encapsRandomBytes")===t.encapsRandomBytes||zs("suite-mismatch","selected suite does not match its canonical FIPS 203 descriptor")},Zs=(e,t)=>{Ys(e),Ys(t),e.parameterSet===t.parameterSet&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes||zs("suite-mismatch","room-selected suite does not exactly match the ML-KEM backend")},ec=e=>qs+e.publicKeyBytes,tc=e=>qs+ec(e)+e.ciphertextBytes,nc=(e,t,n)=>{Ys(t),js(n,"binding",Ts),js(e,"ACK",64),Ws(e.subarray(0,4),Os)||zs("invalid-record","ACK magic is invalid"),1!==e[4]&&zs("invalid-record","ACK version is unsupported"),3!==e[5]&&zs("invalid-record","ACK type is unexpected"),0!==e[7]&&zs("invalid-record","ACK reserved flags must be zero");Gs(e[6])!==t.parameterSet&&zs("suite-mismatch","ACK suite differs from the authenticated room suite"),Ws(e.subarray(8,40),n)||zs("binding-mismatch","ACK belongs to a different authenticated edge");const r=new DataView(e.buffer,e.byteOffset,e.byteLength);return 0n!==r.getBigUint64(56,!1)&&zs("invalid-record","ACK reserved bytes must be zero"),{advanceCounter:r.getBigUint64(40,!1),epoch:r.getBigUint64(48,!1)}},rc=(e,t,n,r,a,o,i)=>{js(n,"binding",Ts),Hs(r,"sender counter"),Hs(a,"from epoch"),Hs(o,"to epoch"),a!==Ls&&o===a+1n||zs("invalid-record","record must advance exactly one PQ epoch");const s=new Uint8Array(i);s.set(Os,0),s[4]=1,s[5]=e,s[6]=Xs(t.parameterSet),s[7]=0,s.set(n,8);const c=new DataView(s.buffer,s.byteOffset,s.byteLength);return c.setBigUint64(40,r,!1),c.setBigUint64(48,a,!1),c.setBigUint64(56,o,!1),s},ac=(e,t,n,r)=>{e instanceof Uint8Array||zs("invalid-record","record must be a Uint8Array"),e.length<qs&&zs("invalid-record","record is shorter than its canonical header"),Ws(e.subarray(0,4),Os)||zs("invalid-record","record magic is invalid"),1!==e[4]&&zs("invalid-record","record version is unsupported"),e[5]!==t&&zs("invalid-record","record type is unexpected"),0!==e[7]&&zs("invalid-record","record reserved flags must be zero");Gs(e[6])!==n.parameterSet&&zs("suite-mismatch","record suite differs from the authenticated room suite");const a=e.subarray(8,40);void 0===r||Ws(a,r)||zs("binding-mismatch","record belongs to a different authenticated edge");const o=new DataView(e.buffer,e.byteOffset,e.byteLength),i=o.getBigUint64(40,!1),s=o.getBigUint64(48,!1),c=o.getBigUint64(56,!1);return s!==Ls&&c===s+1n||zs("invalid-record","record must advance exactly one PQ epoch"),{senderCounter:i,fromEpoch:s,toEpoch:c}},oc=(e,t,n)=>{const r=ac(e,1,t,n);return e.length!==ec(t)&&zs("invalid-record","OFFER length is not canonical for its suite"),{...r,bytes:Uint8Array.from(e),publicKey:e.slice(qs)}},ic=(e,t,n)=>{const r=ac(e,2,t,n);e.length!==tc(t)&&zs("invalid-record","ADVANCE length is not canonical for its suite");const a=ec(t),o=e.slice(qs,qs+a),i=oc(o,t,n);return i.fromEpoch===r.fromEpoch&&i.toEpoch===r.toEpoch||zs("fork","ADVANCE epoch does not exactly match its embedded OFFER"),{...r,bytes:Uint8Array.from(e),offer:i,ciphertext:e.slice(qs+a)}},sc=(e,t)=>{if(Ys(t),!(e instanceof Uint8Array))return zs("invalid-record","record must be a Uint8Array");if(e.length<qs)return zs("invalid-record","record is shorter than its canonical header");if(1===e[5]){const n=oc(e,t);return{type:"offer",parameterSet:t.parameterSet,binding:n.bytes.slice(8,40),senderCounter:n.senderCounter,fromEpoch:n.fromEpoch,toEpoch:n.toEpoch,publicKey:Uint8Array.from(n.publicKey)}}if(2===e[5]){const n=ic(e,t),r={type:"offer",parameterSet:t.parameterSet,binding:n.offer.bytes.slice(8,40),senderCounter:n.offer.senderCounter,fromEpoch:n.offer.fromEpoch,toEpoch:n.offer.toEpoch,publicKey:Uint8Array.from(n.offer.publicKey)};return{type:"advance",parameterSet:t.parameterSet,binding:n.bytes.slice(8,40),senderCounter:n.senderCounter,fromEpoch:n.fromEpoch,toEpoch:n.toEpoch,offerBytes:Uint8Array.from(n.offer.bytes),offer:r,ciphertext:Uint8Array.from(n.ciphertext)}}return zs("invalid-record","record type is unknown")},cc=(e,t,n,r)=>{js(e,"PQ root",Ns);const a=No(e,t,r),o=((...e)=>{const t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n})(Bs,n);try{return qo(a,o,Ns,r)}finally{a.fill(0)}},lc=(e,t)=>{const n=Uint8Array.from(e),r=Uint8Array.from(t);let a=!1;return{publicKey:n,secretKey:r,get destroyed(){return a},destroy(){a||(r.fill(0),a=!0)}}},dc=e=>{switch(e.kind){case"idle":return{kind:"idle"};case"outbound-offer":return{kind:e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared",offer:Uint8Array.from(e.offer.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey)};case"inbound-offer":return{kind:"inbound-offer",offer:Uint8Array.from(e.offer.bytes)};case"outbound-advance-prepared":return{kind:"outbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),nextRoot:Uint8Array.from(e.nextRoot)};case"outbound-advance-awaiting-ack":return{kind:"outbound-advance-awaiting-ack",advance:Uint8Array.from(e.advance.bytes)};case"inbound-advance-prepared":return{kind:"inbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey),nextRoot:Uint8Array.from(e.nextRoot)};case"inbound-advance-awaiting-ack-dispatch":return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Uint8Array.from(e.advance.bytes)}}},uc=(e,t)=>"bigint"!=typeof e?zs("invalid-record",`${t} must be a bigint`):(Hs(e,t),e),hc=(e,t,n)=>{const r=(e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return zs("invalid-record","snapshot.phase must be a plain record");const t=Object.getOwnPropertyDescriptor(e,"kind");return void 0!==t&&"value"in t&&t.enumerable&&"string"==typeof t.value?t.value:zs("invalid-record","snapshot.phase.kind must be an enumerable string data property")})(e);switch(r){case"idle":return Qs(e,"snapshot.phase",["kind"]),{kind:"idle"};case"outbound-offer-prepared":case"outbound-offer-dispatched":{const a=Qs(e,"snapshot.phase",["kind","offer","secretKey"]),o=oc(js(a.offer,"snapshot.phase.offer",ec(t)),t,n),i=js(a.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes);return{kind:"outbound-offer",dispatched:"outbound-offer-dispatched"===r,offer:o,keyPair:lc(o.publicKey,i)}}case"inbound-offer":{const r=Qs(e,"snapshot.phase",["kind","offer"]);return{kind:"inbound-offer",offer:oc(js(r.offer,"snapshot.phase.offer",ec(t)),t,n)}}case"outbound-advance-prepared":{const r=Qs(e,"snapshot.phase",["kind","advance","nextRoot"]),a=ic(js(r.advance,"snapshot.phase.advance",tc(t)),t,n);return{kind:"outbound-advance-prepared",offer:a.offer,advance:a,nextRoot:Uint8Array.from(js(r.nextRoot,"snapshot.phase.nextRoot",Ns))}}case"outbound-advance-awaiting-ack":{const r=Qs(e,"snapshot.phase",["kind","advance"]),a=ic(js(r.advance,"snapshot.phase.advance",tc(t)),t,n);return{kind:"outbound-advance-awaiting-ack",offer:a.offer,advance:a}}case"inbound-advance-prepared":{const r=Qs(e,"snapshot.phase",["kind","advance","secretKey","nextRoot"]),a=ic(js(r.advance,"snapshot.phase.advance",tc(t)),t,n),o=js(r.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes),i=Uint8Array.from(js(r.nextRoot,"snapshot.phase.nextRoot",Ns));return{kind:"inbound-advance-prepared",offer:a.offer,advance:a,keyPair:lc(a.offer.publicKey,o),nextRoot:i}}case"inbound-advance-awaiting-ack-dispatch":{const r=Qs(e,"snapshot.phase",["kind","advance"]);return{kind:"inbound-advance-awaiting-ack-dispatch",advance:ic(js(r.advance,"snapshot.phase.advance",tc(t)),t,n)}}default:return zs("invalid-record","snapshot phase is unknown")}},fc=(e,t)=>{e||zs("invalid-record",`snapshot ${t}`)},pc=(e,t)=>{Zs(t.suite,t.backend.suite),js(t.binding,"binding",Ts);const n=Qs(e,"snapshot",["formatVersion","parameterSet","binding","rootKey","epoch","localCounter","remoteCounter","nextOfferer","phase","lastInboundOffer","lastInboundAdvance"]);1!==n.formatVersion&&zs("invalid-record","snapshot format version is unsupported"),n.parameterSet!==t.suite.parameterSet&&zs("suite-mismatch","snapshot suite differs from the authenticated room suite");const r=js(n.binding,"snapshot.binding",Ts);Ws(r,t.binding)||zs("binding-mismatch","snapshot belongs to a different authenticated edge");const a=js(n.rootKey,"snapshot.rootKey",Ns),o=uc(n.epoch,"snapshot.epoch"),i=uc(n.localCounter,"snapshot.localCounter"),s=uc(n.remoteCounter,"snapshot.remoteCounter");if("local"!==n.nextOfferer&&"remote"!==n.nextOfferer)return zs("invalid-record","snapshot.nextOfferer must be local or remote");const c=Uint8Array.from(a);let l;try{l=hc(n.phase,t.suite,t.binding);const e=null===n.lastInboundOffer?null:oc(js(n.lastInboundOffer,"snapshot.lastInboundOffer",ec(t.suite)),t.suite,t.binding),r=null===n.lastInboundAdvance?null:ic(js(n.lastInboundAdvance,"snapshot.lastInboundAdvance",tc(t.suite)),t.suite,t.binding),a={rootKey:c,epoch:o,localCounter:i,remoteCounter:s,nextOfferer:n.nextOfferer,phase:l,lastInboundOffer:e,lastInboundAdvance:r};return(e=>{const{epoch:t,localCounter:n,remoteCounter:r,nextOfferer:a,phase:o,lastInboundOffer:i,lastInboundAdvance:s}=e;switch(null!==i&&(fc(i.toEpoch<=t,"last inbound OFFER is from a future epoch"),fc(i.senderCounter<r,"last inbound OFFER counter was not consumed")),null!==s&&(fc(s.toEpoch<=t,"last inbound ADVANCE is from a future epoch"),fc(s.senderCounter<r,"last inbound ADVANCE counter was not consumed")),o.kind){case"idle":return;case"outbound-offer":return void fc("local"===a&&o.offer.senderCounter===n&&o.offer.fromEpoch===t,"outbound OFFER does not match the current turn/counter/epoch");case"inbound-offer":return void fc("remote"===a&&o.offer.senderCounter===r&&o.offer.fromEpoch===t,"inbound OFFER does not match the current turn/counter/epoch");case"outbound-advance-prepared":return void fc("remote"===a&&o.advance.senderCounter===n&&o.offer.senderCounter===r&&o.advance.fromEpoch===t,"prepared outbound ADVANCE does not match current state");case"outbound-advance-awaiting-ack":return fc("local"===a&&o.advance.senderCounter+1n===n&&o.offer.senderCounter+1n===r&&o.advance.toEpoch===t,"outbound ADVANCE awaiting ACK does not match committed state"),void fc(null!==i&&Ws(i.bytes,o.offer.bytes),"outbound ADVANCE is missing its exact inbound OFFER replay record");case"inbound-advance-prepared":return void fc("local"===a&&o.advance.senderCounter===r&&o.offer.senderCounter===n&&o.advance.fromEpoch===t,"prepared inbound ADVANCE does not match current state");case"inbound-advance-awaiting-ack-dispatch":fc("remote"===a&&o.advance.senderCounter+1n===r&&o.advance.offer.senderCounter+1n===n&&o.advance.toEpoch===t,"inbound ADVANCE awaiting ACK dispatch does not match committed state"),fc(null!==s&&Ws(s.bytes,o.advance.bytes),"pending ACK is missing its exact inbound ADVANCE replay record")}})(a),a}catch(e){throw c.fill(0),void 0!==l&&("outbound-offer"===l.kind&&l.keyPair.destroy(),"outbound-advance-prepared"===l.kind&&l.nextRoot.fill(0),"inbound-advance-prepared"===l.kind&&(l.keyPair.destroy(),l.nextRoot.fill(0))),e}};class mc{#e;#n;#r;#a;#o;#i;#s;#c;#l;#d={kind:"idle"};#u=null;#h=null;#f=!1;#p=!1;constructor(e){Zs(e.suite,e.backend.suite),js(e.binding,"binding",Ts),js(e.rootKey,"PQ root",Ns);const t=e.nextOfferer;"local"!==t&&"remote"!==t&&zs("invalid-state","nextOfferer must be local or remote");const n=e.epoch??0n,r=e.localCounter??0n,a=e.remoteCounter??0n;Hs(n,"epoch"),Hs(r,"local counter"),Hs(a,"remote counter"),this.#e=e.module,this.#n=e.backend,this.#r=e.suite,this.#a=Uint8Array.from(e.binding),this.#o=Uint8Array.from(e.rootKey),this.#i=n,this.#s=r,this.#c=a,this.#l=e.nextOfferer}static restore(e,t){const n=pc(e,t);try{const e=new mc({...t,rootKey:n.rootKey,epoch:n.epoch,localCounter:n.localCounter,remoteCounter:n.remoteCounter,nextOfferer:n.nextOfferer});return e.#d=n.phase,e.#u=n.lastInboundOffer,e.#h=n.lastInboundAdvance,n.rootKey.fill(0),e}catch(e){throw n.rootKey.fill(0),"outbound-offer"===n.phase.kind&&n.phase.keyPair.destroy(),"outbound-advance-prepared"===n.phase.kind&&n.phase.nextRoot.fill(0),"inbound-advance-prepared"===n.phase.kind&&(n.phase.keyPair.destroy(),n.phase.nextRoot.fill(0)),e}}get suite(){return this.#r}get phase(){return this.#p?"destroyed":(e=>{switch(e.kind){case"idle":return"idle";case"outbound-offer":return e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared";case"inbound-offer":return"inbound-offer";case"outbound-advance-prepared":return"outbound-advance-prepared";case"outbound-advance-awaiting-ack":return"outbound-advance-awaiting-ack";case"inbound-advance-prepared":return"inbound-advance-prepared";case"inbound-advance-awaiting-ack-dispatch":return"inbound-advance-awaiting-ack-dispatch"}})(this.#d)}get epoch(){return this.#m(),this.#i}get localCounter(){return this.#m(),this.#s}get remoteCounter(){return this.#m(),this.#c}get nextOfferer(){return this.#m(),this.#l}get trafficBlocked(){return this.#p||"idle"!==this.#d.kind}copyRootKey(){return this.#m(),Uint8Array.from(this.#o)}snapshot(){return this.#y(),{formatVersion:1,parameterSet:this.#r.parameterSet,binding:Uint8Array.from(this.#a),rootKey:Uint8Array.from(this.#o),epoch:this.#i,localCounter:this.#s,remoteCounter:this.#c,nextOfferer:this.#l,phase:dc(this.#d),lastInboundOffer:null===this.#u?null:Uint8Array.from(this.#u.bytes),lastInboundAdvance:null===this.#h?null:Uint8Array.from(this.#h.bytes)}}clone(){const e=this.snapshot();try{return mc.restore(e,{module:this.#e,backend:this.#n,suite:this.#r,binding:this.#a})}finally{yc(e)}}adopt(e){this.#y(),e.#y(),e===this&&zs("invalid-state","cannot adopt a machine into itself"),this.#r.parameterSet===e.#r.parameterSet&&Ws(this.#a,e.#a)||zs("invalid-state","cannot adopt a machine from another suite or authenticated edge"),this.#g(this.#d),this.#o.fill(0),this.#o=e.#o,this.#i=e.#i,this.#s=e.#s,this.#c=e.#c,this.#l=e.#l,this.#d=e.#d,this.#u=e.#u,this.#h=e.#h,e.#o=new Uint8Array(Ns),e.#a.fill(0),e.#d={kind:"idle"},e.#u=null,e.#h=null,e.#p=!0}copyPendingOutboundRecord(){this.#y();const e=this.#d;return"outbound-offer"===e.kind?Uint8Array.from(e.offer.bytes):"outbound-advance-prepared"===e.kind||"outbound-advance-awaiting-ack"===e.kind?Uint8Array.from(e.advance.bytes):zs("invalid-state","there is no pending outbound record")}async prepareOffer(){let e;this.#w();try{"idle"!==this.#d.kind&&zs("invalid-state","cannot prepare an OFFER while another transition is pending"),"local"!==this.#l&&zs("wrong-turn","the remote peer owns the next OFFER turn"),this.#b(),e=await this.#n.generateKeyPair(),this.#m(),js(e.publicKey,"ML-KEM public key",this.#r.publicKeyBytes),js(e.secretKey,"ML-KEM secret key",this.#r.secretKeyBytes);const t=((e,t,n,r,a)=>{js(a,"ML-KEM public key",e.publicKeyBytes);const o=rc(1,e,t,n,r,r+1n,ec(e));return o.set(a,qs),o})(this.#r,this.#a,this.#s,this.#i,e.publicKey),n=oc(t,this.#r,this.#a);return this.#d={kind:"outbound-offer",dispatched:!1,offer:n,keyPair:e},e=void 0,Uint8Array.from(t)}finally{e?.destroy(),this.#v()}}markOfferDispatched(){this.#y();const e=this.#d;if("outbound-offer"!==e.kind)return zs("invalid-state","there is no outbound OFFER to dispatch");e.dispatched&&zs("invalid-state","outbound OFFER was already marked dispatched"),this.#d={...e,dispatched:!0}}abortUnsentOffer(){this.#y();const e=this.#d;if("outbound-offer"!==e.kind||e.dispatched)return zs("invalid-state","only an undispatched OFFER can be aborted");e.keyPair.destroy(),this.#d={kind:"idle"}}acceptAuthenticatedOffer(e){this.#y();const t=oc(e,this.#r,this.#a);this.#k(t),"idle"!==this.#d.kind&&zs("invalid-state","another PQ healing transition is pending"),"remote"!==this.#l&&zs("wrong-turn","the local peer owns the next OFFER turn"),this.#I(t.senderCounter),this.#S(t.fromEpoch),this.#b(),this.#d={kind:"inbound-offer",offer:t}}async prepareAdvance(){let e;this.#w();try{const t=this.#d;if("inbound-offer"!==t.kind)return zs("invalid-state","an authenticated inbound OFFER is required");Vs(this.#s,"local counter"),e=await this.#n.encapsulate(t.offer.publicKey),this.#m(),js(e.ciphertext,"ML-KEM ciphertext",this.#r.ciphertextBytes),js(e.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const n=((e,t,n,r,a)=>{js(a,"ML-KEM ciphertext",e.ciphertextBytes);const o=rc(2,e,t,n,r.fromEpoch,r.toEpoch,tc(e));return o.set(r.bytes,qs),o.set(a,qs+r.bytes.length),o})(this.#r,this.#a,this.#s,t.offer,e.ciphertext),r=ic(n,this.#r,this.#a),a=cc(this.#o,e.sharedSecret,n,this.#e);return this.#d={kind:"outbound-advance-prepared",offer:t.offer,advance:r,nextRoot:a},Uint8Array.from(n)}finally{e?.destroy(),this.#v()}}commitPreparedAdvance(){this.#y();const e=this.#d;return"outbound-advance-prepared"!==e.kind?zs("invalid-state","there is no prepared outbound ADVANCE"):(this.#C(e.nextRoot),this.#i=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="local",this.#u=e.offer,this.#d={kind:"outbound-advance-awaiting-ack",offer:e.offer,advance:e.advance},Uint8Array.from(e.advance.bytes))}acceptAuthenticatedAdvanceAcknowledgement(e){this.#y();const t=$s(e),n=this.#d;if("outbound-advance-awaiting-ack"!==n.kind)return zs("invalid-state","no outbound ADVANCE is awaiting acknowledgement");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||zs("invalid-record","advance acknowledgement does not bind the pending transition"),this.#d={kind:"idle"}}async acceptAuthenticatedAdvance(e){let t;this.#w();try{const n=ic(e,this.#r,this.#a);this.#A(n);const r=this.#d;if("outbound-offer"!==r.kind||!r.dispatched)return zs("invalid-state","a dispatched outbound OFFER is required before ADVANCE");this.#I(n.senderCounter),this.#S(n.fromEpoch),Ws(n.offer.bytes,r.offer.bytes)||zs("fork","ADVANCE answers a different OFFER"),t=await this.#n.decapsulate(n.ciphertext,r.keyPair.secretKey),this.#m(),js(t.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const a=cc(this.#o,t.sharedSecret,n.bytes,this.#e);this.#d={kind:"inbound-advance-prepared",offer:r.offer,advance:n,keyPair:r.keyPair,nextRoot:a}}finally{t?.destroy(),this.#v()}}commitAcceptedAdvance(){this.#y();const e=this.#d;return"inbound-advance-prepared"!==e.kind?zs("invalid-state","there is no accepted ADVANCE to commit"):(e.keyPair.destroy(),this.#C(e.nextRoot),this.#i=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="remote",this.#h=e.advance,this.#d={kind:"inbound-advance-awaiting-ack-dispatch",advance:e.advance},{epoch:this.#i,advanceCounter:e.advance.senderCounter})}markAdvanceAcknowledgementDispatched(e){this.#y();const t=$s(e),n=this.#d;if("inbound-advance-awaiting-ack-dispatch"!==n.kind)return zs("invalid-state","no advance acknowledgement is pending dispatch");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||zs("invalid-record","advance acknowledgement does not bind the committed transition"),this.#d={kind:"idle"}}destroy(){this.#p||(this.#g(this.#d),this.#o.fill(0),this.#a.fill(0),this.#u=null,this.#h=null,this.#d={kind:"idle"},this.#p=!0)}#m(){this.#p&&zs("destroyed","state machine is destroyed")}#y(){this.#m(),this.#f&&zs("invalid-state","another asynchronous transition is in flight")}#w(){this.#y(),this.#f=!0}#v(){this.#f=!1}#b(){Vs(this.#i,"epoch"),Vs(this.#s,"local counter"),Vs(this.#c,"remote counter")}#I(e){e<this.#c&&zs("replay","record sender counter was already consumed"),e>this.#c&&zs("counter-gap","record sender counter skips an expected transition")}#S(e){e<this.#i&&zs("replay","record PQ epoch was already consumed"),e>this.#i&&zs("epoch-gap","record skips the current PQ epoch")}#k(e){let t=this.#u;const n=this.#d;var r,a;("inbound-offer"!==n.kind&&"outbound-advance-prepared"!==n.kind&&"outbound-advance-awaiting-ack"!==n.kind||(t=n.offer),null!==t&&(a=t,(r=e).senderCounter===a.senderCounter&&r.fromEpoch===a.fromEpoch&&r.toEpoch===a.toEpoch))&&(Ws(e.bytes,t.bytes)&&zs("replay","OFFER is an exact replay"),zs("fork","different OFFER bytes reuse an authenticated slot"))}#A(e){let t=this.#h;const n=this.#d;var r,a;("inbound-advance-prepared"!==n.kind&&"inbound-advance-awaiting-ack-dispatch"!==n.kind||(t=n.advance),null!==t&&(a=t,(r=e).senderCounter===a.senderCounter&&r.fromEpoch===a.fromEpoch&&r.toEpoch===a.toEpoch))&&(Ws(e.bytes,t.bytes)&&zs("replay","ADVANCE is an exact replay"),zs("fork","different ADVANCE bytes reuse an authenticated slot"))}#C(e){js(e,"candidate PQ root",Ns),this.#o.fill(0),this.#o=e}#g(e){"outbound-offer"===e.kind&&e.keyPair.destroy(),"outbound-advance-prepared"===e.kind&&e.nextRoot.fill(0),"inbound-advance-prepared"===e.kind&&(e.keyPair.destroy(),e.nextRoot.fill(0))}}const yc=e=>{e.binding.fill(0),e.rootKey.fill(0),e.lastInboundOffer?.fill(0),e.lastInboundAdvance?.fill(0);const t=e.phase;switch(t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return t.offer.fill(0),void t.secretKey.fill(0);case"inbound-offer":return void t.offer.fill(0);case"outbound-advance-prepared":return t.advance.fill(0),void t.nextRoot.fill(0);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void t.advance.fill(0);case"inbound-advance-prepared":return t.advance.fill(0),t.secretKey.fill(0),void t.nextRoot.fill(0)}},gc=de-69-H,wc=(1n<<64n)-1n,bc=(new TextEncoder).encode("p2party/pq-control-frame/key/v1\0");class vc extends Error{code;constructor(e,t){super(`pqHealingFrame: ${t}`),this.name="PqControlFrameError",this.code=e}}const kc=(e,t)=>{throw new vc(e,t)},Ic=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},Sc=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&kc("invalid-frame",`${t} must be exactly ${String(n)} bytes`),e):kc("invalid-frame",`${t} must be a Uint8Array`),Cc=(e,t)=>"bigint"!=typeof e||e<0n||e>wc?kc("invalid-frame",`${t} must be an unsigned 64-bit bigint`):e,Ac=(e,t,n,r,a,o)=>{Sc(n,"PQ root",Ns),Sc(r,"binding",Ts);const i=(e=>{const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t})(Cc(o,"keyEpoch")),s=new Uint8Array(bc.length+1+1+r.length+i.length);s.set(bc,0),s[bc.length]=(e=>{const t=Ps(e.parameterSet);return e.standardName!==t.standardName||e.publicKeyBytes!==t.publicKeyBytes||e.secretKeyBytes!==t.secretKeyBytes||e.ciphertextBytes!==t.ciphertextBytes||e.sharedSecretBytes!==t.sharedSecretBytes||e.keyPairRandomBytes!==t.keyPairRandomBytes||e.encapsRandomBytes!==t.encapsRandomBytes?kc("invalid-frame","ML-KEM suite descriptor is not canonical"):768===e.parameterSet?1:512===e.parameterSet?2:1024===e.parameterSet?3:kc("invalid-frame","ML-KEM suite is unsupported")})(t),s[bc.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:kc("invalid-direction","control direction is unknown"))(a),s.set(r,bc.length+2),s.set(i,bc.length+2+r.length);const c=No(n,r,e);try{return qo(c,s,z,e)}finally{c.fill(0),i.fill(0)}},Ec=(e,t,n)=>{if(Sc(e,"control record"),64===e.length){const r=nc(e,t,n);return{counter:r.advanceCounter,keyEpoch:r.epoch}}const r=sc(e,t);return Ic(r.binding,n)?{counter:r.senderCounter,keyEpoch:r.fromEpoch}:kc("binding-mismatch","control record belongs to another authenticated edge")},Pc=e=>{const t=Sc(e.binding,"binding",Ts),n=Cc(e.keyEpoch,"keyEpoch"),r=Ec(e.record,e.suite,t);r.keyEpoch!==n&&kc("epoch-mismatch","control record is not authenticated under its required epoch"),e.record.length>gc-4&&kc("invalid-frame","control record does not fit the uniform cell");const a=(()=>{const e=new Uint8Array(j);return crypto.getRandomValues(e),e})(),o=new Uint8Array(69);o[0]=5,o.set(t,1);const i=new DataView(o.buffer,o.byteOffset,o.byteLength);i.setBigUint64(33,r.counter,!1),i.setBigUint64(49,n,!1),o.set(a,57);const s=new Uint8Array(gc);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e.record.length,!1),s.set(e.record,4);const c=Ac(e.module,e.suite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+H,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{return new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a),0!==e._encrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?kc("invalid-frame","control-frame AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{Da(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),Da(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),Da(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,c,a,s,o),n=new Uint8Array(de);return n.set(o,0),n.set(t,69),n}finally{c.fill(0),s.fill(0)}},xc=e=>{const t=Sc(e.frame,"control frame",de),n=Sc(e.binding,"binding",Ts),r=Cc(e.keyEpoch,"keyEpoch");5!==t[0]&&kc("invalid-frame","frame type is not PQ control"),Ic(t.subarray(1,33),n)||kc("binding-mismatch","control frame belongs to another edge");const a=t.subarray(0,69),o=new DataView(t.buffer,t.byteOffset,t.byteLength),i=o.getBigUint64(33,!1);0n!==o.getBigUint64(41,!1)&&kc("invalid-frame","control-frame reserved header must be zero"),o.getBigUint64(49,!1)!==r&&kc("epoch-mismatch","control-frame epoch is not the expected epoch");const s=t.subarray(57,69),c=t.subarray(69),l=Ac(e.module,e.suite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-H,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a);const u=new Uint8Array(e.wasmMemory.buffer,d,o);return u.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?kc("authentication-failed","control-frame authentication failed"):Uint8Array.from(u)}finally{Da(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),Da(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,l,s,c,a);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,!1);(0===t||t>gc-4)&&kc("invalid-padding","encrypted control-record length is invalid");const o=4+t;let u=0;for(let e=o;e<d.length;e+=1)u|=d[e];0!==u&&kc("invalid-padding","encrypted control padding must be all zero");const h=d.slice(4,o),f=Ec(h,e.suite,n);return f.keyEpoch!==r&&kc("epoch-mismatch","decrypted control record does not match its frame epoch"),f.counter!==i&&kc("record-mismatch","decrypted control counter does not match its public header"),h}finally{l.fill(0),d?.fill(0)}},Kc=new Uint8Array([80,50,69,68,71,69,52,0]),Rc=(1n<<64n)-1n,Mc=262144,_c=Math.min(ge,256),Uc=/^[0-9a-f]{64}:[0-9]+:[0-9]+$/,Dc=new TextEncoder,Tc=new TextDecoder("utf-8",{fatal:!0}),Nc=e=>{throw new Error(`pqHealingRuntime: ${e}`)},qc=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},Oc=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&Nc(`${t} must be exactly ${String(n)} bytes`),e):Nc(`${t} must be a Uint8Array`),Bc=(e,t)=>"number"!=typeof e||!Number.isSafeInteger(e)||e<0?Nc(`${t} must be a non-negative safe integer`):e,Lc=e=>1===e?"local":2===e?"remote":Nc("checkpoint has an invalid next-offerer turn");class Fc{#E=[];#P=0;bytes(e){const t=Uint8Array.from(e);this.#E.push(t),this.#P+=t.length,this.#P>Mc&&Nc("checkpoint exceeds the encrypted edge-state budget")}u8(e){(!Number.isInteger(e)||e<0||e>255)&&Nc("u8 value is out of range"),this.bytes(Uint8Array.of(e))}u16(e){(!Number.isInteger(e)||e<0||e>65535)&&Nc("u16 value is out of range");const t=new Uint8Array(2);new DataView(t.buffer).setUint16(0,e,!1),this.bytes(t),t.fill(0)}u32(e){(!Number.isInteger(e)||e<0||e>4294967295)&&Nc("u32 value is out of range");const t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e,!1),this.bytes(t),t.fill(0)}u64(e){((e,t)=>{("bigint"!=typeof e||e<0n||e>Rc)&&Nc(`${t} must be an unsigned 64-bit bigint`)})(e,"checkpoint counter");const t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e,!1),this.bytes(t),t.fill(0)}sized(e){null!==e?(0===e.length&&Nc("present checkpoint byte strings must not be empty"),this.u32(e.length),this.bytes(e)):this.u32(0)}finish(){const e=new Uint8Array(this.#P);let t=0;try{for(const n of this.#E)e.set(n,t),t+=n.length;return e}finally{for(const e of this.#E)e.fill(0);this.#E.length=0,this.#P=0}}}class zc{#x;#K=0;constructor(e){(0===e.length||e.length>Mc)&&Nc("checkpoint length is invalid"),this.#x=Uint8Array.from(e)}take(e){if(!Number.isSafeInteger(e)||e<0||this.#K+e>this.#x.length)return Nc("checkpoint is truncated");const t=this.#x.slice(this.#K,this.#K+e);return this.#K+=e,t}u8(){const e=this.take(1),t=e[0];return e.fill(0),t}u16(){const e=this.take(2),t=new DataView(e.buffer).getUint16(0,!1);return e.fill(0),t}u32(){const e=this.take(4),t=new DataView(e.buffer).getUint32(0,!1);return e.fill(0),t}u64(){const e=this.take(8),t=new DataView(e.buffer).getBigUint64(0,!1);return e.fill(0),t}sized(e){const t=this.u32();return 0===t?null:t>e?Nc("checkpoint field exceeds its budget"):this.take(t)}finish(){this.#K!==this.#x.length&&Nc("checkpoint contains trailing bytes")}destroy(){this.#x.fill(0),this.#K=this.#x.length}}const jc=(e,t,n)=>e.sized(t)??Nc(`${n} is missing`),Hc=(e,t)=>{const n=64+t.publicKeyBytes,r=64+n+t.ciphertextBytes;switch(e.u8()){case 0:return{kind:"idle"};case 1:return{kind:"outbound-offer-prepared",offer:jc(e,n,"prepared OFFER"),secretKey:jc(e,t.secretKeyBytes,"prepared OFFER secret key")};case 2:return{kind:"outbound-offer-dispatched",offer:jc(e,n,"dispatched OFFER"),secretKey:jc(e,t.secretKeyBytes,"dispatched OFFER secret key")};case 3:return{kind:"inbound-offer",offer:jc(e,n,"inbound OFFER")};case 4:return{kind:"outbound-advance-prepared",advance:jc(e,r,"prepared ADVANCE"),nextRoot:jc(e,32,"candidate PQ root")};case 5:return{kind:"outbound-advance-awaiting-ack",advance:jc(e,r,"outbound ADVANCE")};case 6:return{kind:"inbound-advance-prepared",advance:jc(e,r,"inbound ADVANCE"),secretKey:jc(e,t.secretKeyBytes,"inbound ADVANCE secret key"),nextRoot:jc(e,32,"candidate PQ root")};case 7:return{kind:"inbound-advance-awaiting-ack-dispatch",advance:jc(e,r,"acknowledged ADVANCE")};default:return Nc("checkpoint has an unknown PQ phase")}},Vc=e=>{for(const t of e.values())t.fill(0);e.clear()};class $c{#e;#R;#M;#r;#n;#a;#_;#U;#D;#T;#N=null;#q=null;#O=null;#B=null;#L=new Map;#F=0;#z;#p=!1;constructor(e){const t=ve(e.pqMode);ke(e.pqMode)!==e.rootSuite&&Nc("authenticated root suite and room PQ mode disagree"),Oc(e.binding,"edge binding",32),Oc(e.rootKey,"PQ root",32),this.#e=e.module,this.#R=e.pqMode,this.#M=e.rootSuite,this.#r=Ps(t),this.#n=Ds(e.module,this.#r),this.#a=Uint8Array.from(e.binding),this.#D=new mc({module:e.module,backend:this.#n,suite:this.#r,binding:this.#a,rootKey:e.rootKey,nextOfferer:e.nextOfferer}),this.#T=this.#D.copyRootKey(),this.#z=Bc(e.now??Date.now(),"initial healing time"),this.#_=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#U=e.amInitiator?"responder-to-initiator":"initiator-to-responder"}get pqMode(){return this.#R}get rootSuite(){return this.#M}get epoch(){return this.#j(),this.#D.epoch}get phase(){return this.#D.phase}get trafficBlocked(){return this.#p||this.#D.trafficBlocked}get nextOfferer(){return this.#D.nextOfferer}get activeReceiveKeys(){return this.#j(),this.#L}get messagesSinceHealing(){return this.#j(),this.#F}get lastHealedAt(){return this.#j(),this.#z}currentMessageContext(){return this.#j(),{rootKey:this.#T,binding:this.#a,rootSuite:this.#M,epoch:this.#D.epoch}}resolveMessageContext(e){return this.#j(),e===this.#D.epoch?this.currentMessageContext():null}noteApplicationMessage(){this.#j(),this.#F>=Number.MAX_SAFE_INTEGER&&Nc("application-message counter overflow"),this.#F+=1}healingDue(e=Date.now()){return this.#j(),Bc(e,"healing clock"),!this.#D.trafficBlocked&&"local"===this.#D.nextOfferer&&(this.#F>=64||e-this.#z>=864e5)}copyPendingFrame(){return this.#j(),this.#N?Uint8Array.from(this.#N.frame):null}get pendingRetryAt(){return this.#j(),this.#N?.nextRetryAt??null}get pendingAttempts(){return this.#j(),this.#N?.attempts??0}markPendingDispatched(e=Date.now()){this.#j();const t=this.#N;if(!t)return Nc("there is no PQ control outbox");Bc(e,"dispatch clock"),t.attempts>=8&&Nc("PQ control retry budget is exhausted"),this.#N={kind:t.kind,frame:t.frame,attempts:t.attempts+1,nextRetryAt:e+5e3}}async prepareHealingOffer(e=Date.now()){this.#j(),this.healingDue(e)||Nc("a local sparse-PQ healing exchange is not due");const t=await this.#D.prepareOffer(),n=this.#D.copyRootKey();try{const r=Pc({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#_,keyEpoch:this.#D.epoch,record:t});return this.#D.markOfferDispatched(),this.#N?.frame.fill(0),this.#N={kind:"offer",frame:Uint8Array.from(r),attempts:0,nextRetryAt:e},this.#H(),r}finally{n.fill(0),t.fill(0)}}async acceptControlFrame(e,t=Date.now()){if(this.#j(),Oc(e,"PQ control frame",de),Bc(t,"control clock"),this.#q&&"advance"===this.#N?.kind&&qc(e,this.#q))return{dispatch:Uint8Array.from(this.#N.frame),changed:!1};if(this.#O&&this.#B&&qc(e,this.#O))return{dispatch:Uint8Array.from(this.#B),changed:!1};const n=this.#D.copyRootKey();let r=null;try{if(r=xc({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#U,keyEpoch:this.#D.epoch,frame:e}),64===r.length){const e=this.#N;if("advance"!==e?.kind)return Nc("unexpected PQ ADVANCE acknowledgement");const n=nc(r,this.#r,this.#a);return this.#D.acceptAuthenticatedAdvanceAcknowledgement(n),e.frame.fill(0),this.#N=null,this.#H(),this.#F=0,this.#z=t,this.#V(),{dispatch:null,changed:!0}}if("offer"===sc(r,this.#r).type){this.#D.acceptAuthenticatedOffer(r);const a=await this.#D.prepareAdvance();let o;try{o=Pc({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#_,keyEpoch:this.#D.epoch,record:a}),this.#D.commitPreparedAdvance()}finally{a.fill(0)}return this.#N?.frame.fill(0),this.#N={kind:"advance",frame:Uint8Array.from(o),attempts:0,nextRetryAt:t},this.#q?.fill(0),this.#q=Uint8Array.from(e),this.#O?.fill(0),this.#O=null,this.#B?.fill(0),this.#B=null,this.#V(),{dispatch:o,changed:!0}}const a=this.#N;if("offer"!==a?.kind)return Nc("unexpected PQ ADVANCE without a persisted OFFER");await this.#D.acceptAuthenticatedAdvance(r);const o=this.#D.commitAcceptedAdvance(),i=((e,t,n)=>{Ys(t),js(n,"binding",Ts);const r=$s(e),a=new Uint8Array(64);a.set(Os,0),a[4]=1,a[5]=3,a[6]=Xs(t.parameterSet),a[7]=0,a.set(n,8);const o=new DataView(a.buffer,a.byteOffset,a.byteLength);return o.setBigUint64(40,r.advanceCounter,!1),o.setBigUint64(48,r.epoch,!1),a})(o,this.#r,this.#a),s=this.#D.copyRootKey();try{const n=Pc({module:this.#e,suite:this.#r,rootKey:s,binding:this.#a,direction:this.#_,keyEpoch:o.epoch,record:i});return this.#D.markAdvanceAcknowledgementDispatched(o),a.frame.fill(0),this.#N=null,this.#O?.fill(0),this.#O=Uint8Array.from(e),this.#B?.fill(0),this.#B=Uint8Array.from(n),this.#q?.fill(0),this.#q=null,this.#F=0,this.#z=t,this.#V(),{dispatch:n,changed:!0}}finally{s.fill(0),i.fill(0)}}finally{n.fill(0),r?.fill(0)}}clone(){this.#j();const e=this.#D.copyRootKey();let t=null;try{return t=new $c({module:this.#e,pqMode:this.#R,rootSuite:this.#M,binding:this.#a,rootKey:e,nextOfferer:this.#D.nextOfferer,amInitiator:"initiator-to-responder"===this.#_,now:this.#z}),t.#D.destroy(),t.#D=this.#D.clone(),t.#T.fill(0),t.#T=Uint8Array.from(this.#T),t.#N=null===(n=this.#N)?null:{kind:n.kind,frame:Uint8Array.from(n.frame),attempts:n.attempts,nextRetryAt:n.nextRetryAt},t.#q=null===this.#q?null:Uint8Array.from(this.#q),t.#O=null===this.#O?null:Uint8Array.from(this.#O),t.#B=null===this.#B?null:Uint8Array.from(this.#B),t.#L=(e=>{const t=new Map;for(const[n,r]of e)t.set(n,Uint8Array.from(r));return t})(this.#L),t.#F=this.#F,t.#z=this.#z,t}catch(e){throw t?.destroy(),e}finally{e.fill(0)}var n}adopt(e){this.#j(),e.#j(),e===this&&Nc("cannot adopt a PQ runtime into itself"),e.#e===this.#e&&e.#R===this.#R&&e.#M===this.#M&&e.#_===this.#_&&qc(e.#a,this.#a)||Nc("cannot adopt a PQ runtime from another authenticated edge"),this.#D.destroy(),this.#T.fill(0),this.#N?.frame.fill(0),this.#q?.fill(0),this.#O?.fill(0),this.#B?.fill(0),Vc(this.#L),this.#D=e.#D,this.#T=e.#T,this.#N=e.#N,this.#q=e.#q,this.#O=e.#O,this.#B=e.#B,this.#L=e.#L,this.#F=e.#F,this.#z=e.#z,e.#T=new Uint8Array(32),e.#N=null,e.#q=null,e.#O=null,e.#B=null,e.#L=new Map,e.#a.fill(0),e.#p=!0}serialize(e=this.#L){this.#j();const t=this.#D.snapshot(),n=new Fc;try{return n.bytes(Kc),n.u8(1),n.u8(512===(a=this.#r.parameterSet)?1:768===a?2:1024===a?3:Nc("unsupported ML-KEM suite")),n.u8("initiator-to-responder"===this.#_?1:2),n.u8(0),n.u64(BigInt(this.#z)),n.u64(BigInt(this.#F)),n.bytes(t.binding),n.bytes(t.rootKey),n.u64(t.epoch),n.u64(t.localCounter),n.u64(t.remoteCounter),n.u8("local"===(r=t.nextOfferer)?1:"remote"===r?2:Nc("invalid next-offerer turn")),((e,t)=>{switch(e.u8((e=>{switch(e.kind){case"idle":return 0;case"outbound-offer-prepared":return 1;case"outbound-offer-dispatched":return 2;case"inbound-offer":return 3;case"outbound-advance-prepared":return 4;case"outbound-advance-awaiting-ack":return 5;case"inbound-advance-prepared":return 6;case"inbound-advance-awaiting-ack-dispatch":return 7}})(t)),t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return e.sized(t.offer),void e.sized(t.secretKey);case"inbound-offer":return void e.sized(t.offer);case"outbound-advance-prepared":return e.sized(t.advance),void e.sized(t.nextRoot);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void e.sized(t.advance);case"inbound-advance-prepared":e.sized(t.advance),e.sized(t.secretKey),e.sized(t.nextRoot)}})(n,t.phase),n.sized(t.lastInboundOffer),n.sized(t.lastInboundAdvance),((e,t)=>{null!==t?(e.u8("offer"===t.kind?1:2),e.u8(t.attempts),e.u64(BigInt(t.nextRetryAt)),e.sized(t.frame)):e.u8(0)})(n,this.#N),n.sized(this.#q),n.sized(this.#O),n.sized(this.#B),((e,t)=>{t.size>_c&&Nc("too many active receive message keys");const n=[...t.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0);e.u16(n.length);for(const[t,r]of n){Uc.test(t)||Nc("active receive cache key is non-canonical");const n=Dc.encode(t);(0===n.length||n.length>160)&&Nc("active receive cache key length is invalid"),Oc(r,"active receive message key",32),e.u16(n.length),e.bytes(n),e.bytes(r)}})(n,e),n.finish()}finally{yc(t)}var r,a}static readCheckpointBinding(e){Oc(e,"checkpoint");const t=Kc.length+1+1+1+1+8+8;return e.length<t+32?Nc("checkpoint is too short to contain a binding"):e.slice(t,t+32)}static restore(e,t){Oc(e,"encrypted edge checkpoint plaintext"),Oc(t.binding,"expected edge binding",32);const n=new zc(e);let r=null,a=null,o=null,i=null,s=null,c=null,l=null,d=null;try{const e=n.take(Kc.length),h=qc(e,Kc);e.fill(0),h||Nc("checkpoint magic is invalid"),1!==n.u8()&&Nc("checkpoint version is unsupported");const f=1===(u=n.u8())?512:2===u?768:3===u?1024:Nc("checkpoint has an unknown ML-KEM suite");f!==ve(t.pqMode)&&Nc("checkpoint suite disagrees with the authenticated room policy"),ke(t.pqMode)!==t.rootSuite&&Nc("authenticated root suite and room PQ mode disagree");const p=n.u8();p!==(t.amInitiator?1:2)&&Nc("checkpoint belongs to the opposite edge direction"),0!==n.u8()&&Nc("checkpoint reserved byte is non-zero");const m=n.u64(),y=n.u64();(m>BigInt(Number.MAX_SAFE_INTEGER)||y>BigInt(Number.MAX_SAFE_INTEGER))&&Nc("checkpoint counters exceed the safe-integer range");const g=n.take(32);qc(g,t.binding)||Nc("checkpoint belongs to another authenticated edge");const w=n.take(32),b=Ps(f);r={formatVersion:1,parameterSet:f,binding:g,rootKey:w,epoch:n.u64(),localCounter:n.u64(),remoteCounter:n.u64(),nextOfferer:Lc(n.u8()),phase:Hc(n,b),lastInboundOffer:n.sized(8192),lastInboundAdvance:n.sized(8192)},s=(e=>{const t=e.u8();if(0===t)return null;if(1!==t&&2!==t)return Nc("checkpoint outbox kind is invalid");const n=e.u8();n>8&&Nc("checkpoint outbox attempts exceed the retry budget");const r=e.u64();r>BigInt(Number.MAX_SAFE_INTEGER)&&Nc("checkpoint retry deadline exceeds the safe-integer range");const a=jc(e,de,"outbox frame");return Oc(a,"outbox frame",de),{kind:1===t?"offer":"advance",attempts:n,nextRetryAt:Number(r),frame:a}})(n),c=n.sized(de),l=n.sized(de),d=n.sized(de);for(const e of[c,l,d])e&&Oc(e,"cached control frame",de);i=(e=>{const t=e.u16();t>_c&&Nc("checkpoint has too many active receive message keys");const n=new Map;try{for(let r=0;r<t;r+=1){const t=e.u16();(0===t||t>160)&&Nc("checkpoint active receive cache key length is invalid");const r=e.take(t);let a;try{a=Tc.decode(r)}finally{r.fill(0)}0!==a.length&&Uc.test(a)&&!n.has(a)||Nc("checkpoint active receive cache key is non-canonical"),n.set(a,e.take(32))}return n}catch(e){for(const e of n.values())e.fill(0);throw n.clear(),e}})(n),n.finish();const v=Ds(t.module,b);a=mc.restore(r,{module:t.module,backend:v,suite:b,binding:t.binding});const k=a.copyRootKey();try{o=new $c({module:t.module,pqMode:t.pqMode,rootSuite:t.rootSuite,binding:t.binding,rootKey:k,nextOfferer:a.nextOfferer,amInitiator:t.amInitiator,now:Number(m)})}finally{k.fill(0)}return o.#D.destroy(),o.#D=a,a=null,o.#T.fill(0),o.#T=o.#D.copyRootKey(),o.#N=s,s=null,o.#q=c,c=null,o.#O=l,l=null,o.#B=d,d=null,o.#L=i,i=null,o.#F=Number(y),o.#$(),o}catch(e){throw o?.destroy(),e}finally{n.destroy(),r&&yc(r),a?.destroy(),s?.frame.fill(0),c?.fill(0),l?.fill(0),d?.fill(0),i&&Vc(i)}var u}destroy(){this.#p||(this.#D.destroy(),this.#a.fill(0),this.#T.fill(0),this.#N?.frame.fill(0),this.#q?.fill(0),this.#O?.fill(0),this.#B?.fill(0),Vc(this.#L),this.#N=null,this.#q=null,this.#O=null,this.#B=null,this.#p=!0)}#V(){const e=this.#D.copyRootKey();this.#T.fill(0),this.#T=e}#H(){this.#q?.fill(0),this.#O?.fill(0),this.#B?.fill(0),this.#q=null,this.#O=null,this.#B=null}#$(){const e=this.#D.phase;("outbound-offer-dispatched"===e&&"offer"!==this.#N?.kind||"outbound-advance-awaiting-ack"===e&&"advance"!==this.#N?.kind||"offer"===this.#N?.kind&&"outbound-offer-dispatched"!==e||"advance"===this.#N?.kind&&"outbound-advance-awaiting-ack"!==e)&&Nc("checkpoint PQ phase and sealed outbox disagree"),null!==this.#q&&"advance"!==this.#N?.kind&&Nc("checkpoint cached OFFER has no matching ADVANCE outbox"),null===this.#O!=(null===this.#B)&&Nc("checkpoint ADVANCE replay and ACK cache must be paired"),null!==this.#q&&null!==this.#O&&Nc("checkpoint contains mutually exclusive replay caches")}#j(){this.#p&&Nc("state is destroyed")}}const Qc=new TextEncoder,Wc=Qc.encode("CPaceRistretto255"),Xc=Qc.encode("CPaceRistretto255_ISK"),Gc=new Uint8Array(0),Jc=(e,t,n)=>{if(t.length!==n)throw new Error(`cpace: ${e} must be ${n} bytes`)},Yc=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("cpace: invalid transcript field length");const t=[];let n=e;do{let e=n%128;n=Math.floor(n/128),0!==n&&(e|=128),t.push(e)}while(0!==n);return Uint8Array.from(t)},Zc=(e,t,n,r=!1)=>{if(0===n.length)return;const a=e._malloc(n.length),o=new Uint8Array(e.wasmMemory.buffer,a,n.length);try{if(o.set(n),0!==e._sha512_update(t,a,n.length))throw new Error("sha512_update failed")}finally{r?Da(e,o):e._free(a)}},el=(e,t,n)=>{Zc(e,t,Yc(n.data.length)),Zc(e,t,n.data,n.secret)},tl=(e,t,n,r)=>{const a=Math.max(0,127-(Yc(Wc.length).length+Wc.length)-(Yc(e.length).length+e.length)),o=((e,t)=>{const n=e._malloc(q),r=e._malloc(N),a=new Uint8Array(e.wasmMemory.buffer,n,q),o=new Uint8Array(e.wasmMemory.buffer,r,N);try{if(a.fill(0),o.fill(0),0!==e._sha512_init(n))throw new Error("sha512_init failed");for(const r of t)el(e,n,r);if(0!==e._sha512_final(n,r))throw new Error("sha512_final failed");return Uint8Array.from(o)}finally{Da(e,a),Da(e,o)}})(r,[{data:Wc},{data:e,secret:!0},{data:new Uint8Array(a)},{data:n},{data:t}]),i=r._malloc(Q),s=r._malloc($),c=new Uint8Array(r.wasmMemory.buffer,i,Q),l=new Uint8Array(r.wasmMemory.buffer,s,$);try{return c.set(o),l.fill(0),r._cpace_ristretto255_from_hash(s,i),Uint8Array.from(l)}finally{o.fill(0),Da(r,c),r._free(s)}},nl=(new TextEncoder).encode("p2party-interactive-3dh-v2"),rl=new Uint8Array(64),al=e=>{const t=new Uint8Array(ue.length+e.length);return t.set(ue,0),t.set(e,ue.length),t},ol=async(e,t,n)=>Na(al(e),t,n),il=async(e,t,n,r)=>qa(al(e),t,n,r),sl=e=>{const t=(e=>{if("hybrid-mlkem768"===e)return se;if("hybrid-mlkem512"===e)return new Uint8Array([2]);if("hybrid-mlkem1024"===e)return new Uint8Array([3]);throw new Error("handshake: unsupported room PQ mode")})(e.pqMode??"hybrid-mlkem768"),n=[e.channelId,e.ikInitiator,e.ikResponder,e.fpInitiator,e.fpResponder,t];let r=0;for(const e of n)r+=e.length;const a=new Uint8Array(r);let o=0;for(const e of n)a.set(e,o),o+=e.length;return a},cl=(new TextEncoder).encode("p2party-v4-hs-kc-transcript-v4"),ll=(new TextEncoder).encode("p2party-v4-hs-kc-responder-v4"),dl=(new TextEncoder).encode("p2party-v4-hs-kc-initiator-ratchet-dh-v4"),ul=(new TextEncoder).encode("p2party-v4-hs-kc-responder-finish-v4"),hl=new Uint8Array(64),fl=(new TextEncoder).encode("p2party-v4-pq-healing-extract-v1"),pl=(new TextEncoder).encode("p2party-v4-pq-healing-root-v1"),ml=(new TextEncoder).encode("p2party-v4-pq-healing-binding-v1\0"),yl=64,gl=129,wl=e=>{const t=Ps(ve(e)),n=193+t.publicKeyBytes;return{suite:t,publicKeyOffset:193,ciphertextOffset:n,length:n+t.ciphertextBytes}},bl=(e,t,n)=>{const r=n._malloc(e.length),a=n._malloc(t.length),o=n._malloc(yl);try{new Uint8Array(n.wasmMemory.buffer,r,e.length).set(e),new Uint8Array(n.wasmMemory.buffer,a,t.length).set(t);if(0!==n._hkdf_sha512_extract(o,r,e.length,a,t.length))throw new Error("handshake hmac_sha512 failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,o,yl))}finally{Da(n,new Uint8Array(n.wasmMemory.buffer,r,e.length)),n._free(a),n._free(o)}},vl=e=>{let t=0;for(const n of e)t|=n;return 0===t},kl=(e,t)=>{const n=new Uint8Array(97);return n[0]=2,n.set(e,1),n.set(t,33),n},Il=async(e,t,n)=>{const{mode:r,pqMode:a="hybrid-mlkem768",pin:o,channelInput:i,amInitiator:s,idSelfSec:c,selfIdentityX25519Pub:l,selfIdentityCrossSignature:d,peerIdentityEd25519Pub:u}=t,h=wl(a),f=Ds(n,h.suite),p=ke(a),m=crypto.getRandomValues(new Uint8Array(32)),y=Uo(n);let g=new Uint8Array(32),w=null;const b=new Uint8Array(h.suite.publicKeyBytes),v=new Uint8Array(h.suite.ciphertextBytes);let k,I,S,C,A,E,P,x,K=null,R=null,M=null;const _=e=>{if("pin"!==r)return null;if(!o)throw new Error("PIN mode requires a PIN");const t=tl(o,e,i,n),a=((e,t)=>{Jc("generator",e,$);const n=t._malloc(W),r=t._malloc($),a=t._malloc($),o=new Uint8Array(t.wasmMemory.buffer,n,W),i=new Uint8Array(t.wasmMemory.buffer,r,$),s=new Uint8Array(t.wasmMemory.buffer,a,$);try{if(o.fill(0),s.fill(0),i.set(e),t._cpace_ristretto255_scalar_random(n),0!==t._cpace_ristretto255_scalarmult(a,n,r))throw new Error("cpace: public share is the identity");return{y:Uint8Array.from(o),Y:Uint8Array.from(s)}}finally{Da(t,o),t._free(r),t._free(a)}})(t,n);return t.fill(0),a},U=()=>((e,t,n,r,a,o,i,s)=>{const c=new Uint8Array(e.length);return c[0]=1,c.set(t,1),c.set(n,33),c.set(r,65),c.set(a,97),c.set(o,gl),c.set(i,e.publicKeyOffset),c.set(s,e.ciphertextOffset),c})(h,m,y.publicKey,g,l,d,b,v);try{let t;if(s){K=await f.generateKeyPair(),b.set(K.publicKey);const n=_(m);n&&(w=n.y,g=n.Y),await e.send(U()),t=await e.recv()}else t=await e.recv();if(t.length!==h.length||1!==t[0])throw new Error("Malformed handshake HELLO");const a=t.subarray(1,33),o=t.subarray(33,65),D=t.subarray(65,97),T=t.subarray(97,129),O=t.subarray(gl,193),B=t.subarray(h.publicKeyOffset,h.publicKeyOffset+h.suite.publicKeyBytes),L=t.subarray(h.ciphertextOffset,h.ciphertextOffset+h.suite.ciphertextBytes);if(s){if(!vl(B))throw new Error("Malformed handshake HELLO: responder ML-KEM public-key field must be zero");if(vl(L))throw new Error("Malformed handshake HELLO: responder ML-KEM ciphertext is required")}else{if(vl(B))throw new Error("Malformed handshake HELLO: initiator ML-KEM public key is required");if(!vl(L))throw new Error("Malformed handshake HELLO: initiator ML-KEM ciphertext field must be zero")}if(!await il(T,O,u,n))throw new Error("Handshake peer X25519 identity cross-signature invalid");if(s){if(!K)throw new Error("Handshake ML-KEM initiator keypair is unavailable");R=await f.decapsulate(L,K.secretKey),K.destroy()}else{const t=await f.encapsulate(B);R=t,v.set(t.ciphertext);const n=_(a);n&&(w=n.y,g=n.Y),await e.send(U())}k=((e,t,n,r,a,o)=>{let i,s;const c=To(n,r,o);a?(i=To(e,r,o),s=To(n,t,o)):(i=To(n,t,o),s=To(e,r,o));const l=new Uint8Array(96);l.set(i,0),l.set(s,32),l.set(c,64);const d=No(rl,l,o),u=qo(d,nl,32,o);return l.fill(0),i.fill(0),s.fill(0),c.fill(0),d.fill(0),u})(c,T,y.secretKey,o,s,n);const F=s?m:a,z=s?a:m,j=s?y.publicKey:o,H=s?o:y.publicKey,V=s?g:D,Q=s?D:g,X=s?l:T,G=s?d:O,J=s?T:l,Y=s?O:d,Z=s?b:B,ee=s?v:L,te=s?B:b,ne=s?L:v;if("pin"===r){if(!w)throw new Error("Handshake CPace scalar is unavailable");I=((e,t)=>{const{y:n,peerShare:r,sid:a,initiatorShare:o,responderShare:i,initiatorAssociatedData:s=Gc,responderAssociatedData:c=Gc}=e;Jc("private scalar",n,W),Jc("peer share",r,$),Jc("initiator share",o,$),Jc("responder share",i,$);const l=t._malloc(W),d=t._malloc($),u=t._malloc($),h=t._malloc(q),f=t._malloc(N),p=new Uint8Array(t.wasmMemory.buffer,l,W),m=new Uint8Array(t.wasmMemory.buffer,d,$),y=new Uint8Array(t.wasmMemory.buffer,u,$),g=new Uint8Array(t.wasmMemory.buffer,h,q),w=new Uint8Array(t.wasmMemory.buffer,f,N);try{if(p.set(n),m.set(r),y.fill(0),g.fill(0),w.fill(0),0!==t._cpace_ristretto255_scalarmult(u,l,d))throw new Error("cpace: peer share is invalid or the identity");if(0!==t._sha512_init(h))throw new Error("sha512_init failed");if(el(t,h,{data:Xc}),el(t,h,{data:a}),Zc(t,h,Yc($)),0!==t._sha512_update(h,u,$))throw new Error("sha512_update failed");if(el(t,h,{data:o}),el(t,h,{data:s}),el(t,h,{data:i}),el(t,h,{data:c}),0!==t._sha512_final(h,f))throw new Error("sha512_final failed");return Uint8Array.from(w)}finally{Da(t,p),t._free(d),Da(t,y),Da(t,g),Da(t,w)}})({y:w,peerShare:D,sid:F,initiatorShare:V,responderShare:Q},n)}const re=((e,t)=>(new TextEncoder).encode("pin"===e?`p2party-v4-hybrid-root-cpace21-3dh-ml-kem-${String(t)}-v4`:`p2party-v4-hybrid-root-3dh-ml-kem-${String(t)}-v4`))(r,h.suite.parameterSet);S=await ia("pin"===r?[I,k,R.sharedSecret]:[k,R.sharedSecret]),C=No(hl,S,n);const ae=await ia([re,i,X,G,J,Y,Z,ne]);A=qo(C,ae,32,n);const oe=await ia([ml,i,F,z,j,H,X,G,J,Y,Z,ne]);try{x=new Uint8Array(await crypto.subtle.digest("SHA-256",oe.slice().buffer))}finally{oe.fill(0)}E=No(fl,A,n);const ie=await ia([pl,x]);try{P=qo(E,ie,32,n)}finally{ie.fill(0),E.fill(0),E=void 0}k.fill(0),I?.fill(0),S.fill(0),C.fill(0),R.destroy();const se=(e,t,n,r=[])=>ia([cl,e,F,z,j,H,V,Q,X,G,J,Y,Z,ee,te,ne,t,...n?[n]:[],...r,i]);if(s){const t=await e.recv();if(97!==t.length||2!==t[0])throw new Error("Malformed handshake CONFIRM");const r=Uint8Array.from(t.subarray(1,33)),a=t.subarray(33,97);M=Vo(A,!0,r,n,p);const o=M.dhSelfPub,i=await se(dl,r,o,[a]),s=bl(A,i,n);try{await e.send(kl(o,s));const t=await se(ll,r),i=bl(A,t,n),c=await sa(a,i);if(i.fill(0),!c)throw new Error("Handshake key-confirmation failed");const l=await e.recv();if(65!==l.length||3!==l[0])throw new Error("Malformed handshake FINISH");const d=l.subarray(1,65),u=await se(ul,r,o,[a,s]),h=bl(A,u,n),f=await sa(d,h);if(h.fill(0),!f)throw new Error("Handshake final confirmation failed")}finally{s.fill(0)}}else{M=Vo(A,!1,null,n,p);const t=M.dhSelfPub,r=await se(ll,t),a=bl(A,r,n);try{await e.send(kl(t,a));const r=await e.recv();if(97!==r.length||2!==r[0])throw new Error("Malformed handshake CONFIRM");const o=Uint8Array.from(r.subarray(1,33)),i=r.subarray(33,97),s=await se(dl,t,o,[a]),c=bl(A,s,n),l=await sa(i,c);if(c.fill(0),!l)throw new Error("Handshake key-confirmation failed");((e,t,n)=>{if(t.length!==ce)throw new Error("ratchet: invalid initiator DH public key");if(e.sendingChainKey||e.receivingChainKey||e.dhRemotePub||0!==e.Ns||0!==e.Nr||0!==e.PN||0!==e.skipped.size)throw new Error("ratchet: responder bootstrap requires pristine state");Wo(e,{dhPub:t},n)})(M,o,n);const d=await se(ul,t,o,[a,i]),u=bl(A,d,n);try{await e.send((e=>{const t=new Uint8Array(65);return t[0]=3,t.set(e,1),t})(u))}finally{u.fill(0)}}finally{a.fill(0)}}if(!M)throw new Error("Handshake ratchet initialization failed");if(!P||!x)throw new Error("Handshake PQ-healing bootstrap failed");const le=M;M=null;const de={rootKey:P,binding:x,nextOfferer:s?"local":"remote"};return P=void 0,x=void 0,{state:le,secret:A,pqHealing:de}}catch(e){throw A?.fill(0),P?.fill(0),x?.fill(0),e}finally{y.secretKey.fill(0),w?.fill(0),k?.fill(0),I?.fill(0),S?.fill(0),C?.fill(0),E?.fill(0),P?.fill(0),x?.fill(0),R?.destroy(),K?.destroy(),M&&ti(M)}},Sl=/a=fingerprint:sha-256\s+([0-9A-Fa-f:]+)/,Cl=e=>{const t=Sl.exec(e);if(!t)throw new Error("No sha-256 DTLS fingerprint found in SDP");const n=t[1].split(":").map(e=>parseInt(e,16));if(32!==n.length||n.some(e=>Number.isNaN(e)))throw new Error("Malformed sha-256 DTLS fingerprint in SDP");return Uint8Array.from(n)},Al=e=>e.replace(/:/g,"").toLowerCase(),El=new Map,Pl=(e,t)=>`${e}\0${t}`,xl=(e,t,n=new Error("Handshake channel closed"),r)=>{const a=Pl(e,t),o=El.get(a);if(!o||r&&o.lease!==r)return!1;El.delete(a);for(const e of o.waiters)e.reject(n);return!0},Kl=(e,t,n,r)=>{const a=El.get(Pl(e,t));if(!a||a.lease!==r)return!1;if(null===a.nextStep||!((e,t,n="hybrid-mlkem768")=>1===t?e.length===wl(n).length&&1===e[0]:2===t?97===e.length&&2===e[0]:65===e.length&&3===e[0])(n,a.nextStep,a.pqMode))return xl(e,t,new Error("Malformed, surplus, or out-of-order handshake frame"),r),!1;a.nextStep=1===a.nextStep?2:2===a.nextStep&&a.expectFinish?3:null;const o=a.waiters.shift();return o?o.resolve(n):a.queue.push(n),!0},Rl=async(e,t,n,r,a,o,i,s,c)=>{let l=null,d=null,u=null,h=null;try{await(async e=>{const t=e.localDescription?.sdp??"",n=e.remoteDescription?.sdp??"",r=Al(ca(Cl(t))),a=Al(ca(Cl(n))),o=await e.getStats();let i,s,c=!1;if(o.forEach(e=>{"transport"===e.type&&(i=e.localCertificateId??i,s=e.remoteCertificateId??s),"certificate"===e.type&&(c=!0)}),!c&&void 0===i)return void console.warn("p2party: this browser does not report WebRTC certificate statistics, so the post-connect DTLS certificate check cannot run. The SDP fingerprints remain bound into the authenticated handshake transcript.");const l=e=>{if(!e)return null;let t=null;return o.forEach((n,r)=>{"certificate"!==n.type||r!==e&&n.id!==e||!n.fingerprint||(t=Al(n.fingerprint))}),t},d=l(i),u=l(s);if(null===d||d!==r)throw new Error("DTLS fingerprint mismatch: local certificate not found or does not match local SDP fingerprint");if(null===u||u!==a)throw new Error("DTLS fingerprint mismatch: remote certificate not found or does not match remote SDP fingerprint (possible MITM)")})(e);const{publicKey:f}=Xu.getState().keyPair,p=Fa(f,e.withPeerPublicKey),m=await lo();if(!m)throw new Error("X25519 identity not provisioned");l=new Uint8Array(m.secret);const y=new Uint8Array(m.pub),g=new Uint8Array(m.crossSig),w=la(e.withPeerPublicKey),b=((e,t,n)=>{const r=Pl(e,t),a=El.get(r);if(!a||a.lease!==n)throw new Error(`No owned handshake channel registered for ${t}`);const o=()=>{if(El.get(r)!==a||a.lease!==n)throw new Error("Handshake channel lease is stale")};return{send:e=>{o();const t=new Uint8Array(1+e.length);t[0]=1,t.set(e,1),a.channel.send(t.buffer)},recv:()=>{try{o()}catch(e){return Promise.reject(e)}return a.queue.length>0?Promise.resolve(a.queue.shift()):new Promise((e,t)=>{const n={resolve:t=>{clearTimeout(r),e(t)},reject:e=>{clearTimeout(r),t(e)}},r=setTimeout(()=>{const e=a.waiters.indexOf(n);e>-1&&a.waiters.splice(e,1),t(new Error("Handshake step timed out"))},3e4);a.waiters.push(n)})}}})(t,e.withPeerId,s),v=await Il(b,{mode:n,pqMode:r,pin:a,channelInput:o,amInitiator:p,idSelfSec:l,selfIdentityX25519Pub:y,selfIdentityCrossSignature:g,peerIdentityEd25519Pub:w},i);if(u=v.state,d=v.secret,h=((e,t,n,r,a)=>{try{return new $c({module:e,pqMode:t,rootSuite:n,binding:a.binding,rootKey:a.rootKey,nextOfferer:a.nextOfferer,amInitiator:r})}finally{a.rootKey.fill(0),a.binding.fill(0)}})(i,r,u.rootSuite,p,v.pqHealing),!Gi(t,e.withPeerId,c))throw new Error("Handshake transport lease is stale");Ri(e,t),await(async(e,t,n,r,a,o)=>{const i=()=>n.pqRuntime.serialize();e.serializeEdgeCryptoState=i;try{await Di(e,n.state,t,()=>{r(),e.ratchetState&&ti(e.ratchetState),e.ratchetState=n.state,e.pqHealingState?.destroy(),e.pqHealingState=n.pqRuntime,e.messageKeyCache=n.pqRuntime.activeReceiveKeys},a,o)}catch(t){throw e.serializeEdgeCryptoState===i&&(e.serializeEdgeCryptoState=void 0),t}})(e,t,{state:u,pqRuntime:h},()=>{if(!Gi(t,e.withPeerId,c))throw new Error("Handshake transport lease was replaced during persistence");if(!((e,t,n)=>{const r=Wi(e,t);return r.lease===n&&!r.settled&&(r.settled=!0,r.outcome="open",r.resolve(),!0)})(t,e.withPeerId,c))throw new Error("Handshake transport gate is already settled")}),u=null,h=null}catch(n){throw Yi(t,e.withPeerId,n,c),n}finally{d?.fill(0),l?.fill(0),u&&ti(u),h?.destroy(),xl(t,e.withPeerId,new Error("Handshake attempt finished"),s)}},Ml=new WeakMap,_l=(e,t,n,r)=>(async(e,t,n,r)=>Ki(n,e.withPeerPublicKey,async()=>{Mi(e,n);const a=r?.()??e.serializeEdgeCryptoState?.()??null;try{await _i(t,n,e.withPeerPublicKey,e.withPeerId,a)}finally{a?.fill(0)}Mi(e,n)}))(e,t,n,r),Ul=e=>{throw new Error(`pqHealingOrchestrator: ${e}`)};class Dl extends Error{constructor(e){super("pqHealingOrchestrator: edge checkpoint persistence failed",{cause:e}),this.name="PqPersistenceError"}}const Tl=e=>{const t=Ml.get(e);return!(!t||!t.inboundBlocked&&!t.failed)||(e.pqHealingState?.trafficBlocked??!1)},Nl=(e,t)=>0===(e.messageChannels?.size??0)&&!((e,t)=>{const n=fs(e,t);return(ds.get(n)??0)>0||ls.has(n)})(t,e.withPeerId),ql=async(e,t,n)=>Ni(e,async()=>{const r=e.pqHealingState,a=e.ratchetState;if(!r||!a)return Ul("edge has no live PQ runtime or ratchet");const o=r.clone();let i;try{if(i=await n(o),i.persist){try{await t.persistEdge(e,a,t.roomId,()=>o.serialize())}catch(e){throw new Dl(e)}if(e.pqHealingState!==r)throw new Dl(new Error("live PQ runtime changed during persistence"));r.adopt(o),e.messageKeyCache=r.activeReceiveKeys}else o.destroy()}catch(e){throw o.destroy(),e}i.dispatch&&(i.dispatch=Uint8Array.from(i.dispatch),t.hooks.sendControlFrame(i.dispatch)||i.dispatch.fill(0))}),Ol=e=>{const t=Ml.get(e);t&&(t.destroyed=!0,null!==t.interval&&clearInterval(t.interval),t.interval=null,Ml.delete(e))},Bl=(e,t)=>{e.failed||(e.failed=!0,e.hooks.failEdge(t))},Ll=async e=>{const t=Ml.get(e),n=e.pqHealingState;if(t&&!t.destroyed&&!t.failed&&!t.busy&&n){t.busy=!0;try{const r=t.now(),a=n.pendingRetryAt;if(null!==a&&r>=a)return n.pendingAttempts>=8?void Bl(t,new Error("pqHealingOrchestrator: control retry budget exhausted; failing the authenticated edge")):void await ql(e,t,e=>{e.markPendingDispatched(r);const t=e.copyPendingFrame();return t?Promise.resolve({dispatch:t,persist:!0}):Ul("retry tick found no persisted outbox")});n.healingDue(r)&&!n.trafficBlocked&&!t.inboundBlocked&&Nl(e,t.roomId)&&await ql(e,t,async e=>{const t=await e.prepareHealingOffer(r);return e.markPendingDispatched(r),{dispatch:t,persist:!0}})}catch(e){console.error("pqHealingOrchestrator: tick transition failed",e)}finally{t.busy=!1}}},Fl=async(e,t,n)=>{const r=Ml.get(e),a=e.pqHealingState;if(r&&!r.destroyed&&!r.failed&&a)if(n.length===de){r.inboundBlocked=!0;try{await(async(e,t)=>{const n=fs(e,t);for(;;){const e=ls.get(n);if(!e&&0===(ds.get(n)??0))return;e?await e.catch(()=>{}):await new Promise(e=>setTimeout(e,10))}})(t,e.withPeerId);const a=r.now();await ql(e,r,async e=>{const t=await e.acceptControlFrame(Uint8Array.from(n),a);return t.changed?(null!==t.dispatch&&null!==e.pendingRetryAt&&e.markPendingDispatched(a),{dispatch:t.dispatch,persist:!0}):{dispatch:t.dispatch,persist:!1}})}catch(e){if(e instanceof Dl)return void console.error("pqHealingOrchestrator: inbound transition not durable",e);Bl(r,new Error("pqHealingOrchestrator: unauthenticated or forked control cell; failing the authenticated edge",{cause:e}))}finally{r.inboundBlocked=!1}}else Bl(r,new Error("pqHealingOrchestrator: malformed control cell length"))},zl=(e,t)=>{if(!Number.isSafeInteger(t))throw new Error(`coverScheduler: ${e} must be a safe integer`)},jl=(e,t)=>{if(!(t instanceof Uint8Array))throw new Error(`coverScheduler: ${e} must return a Uint8Array`);return t},Hl=e=>e.cancelRequested?0:"control"===e.job.kind?1:2,Vl=(e,t)=>{const n=Hl(e)-Hl(t);if(0!==n)return n;return(t.job.priority??0)-(e.job.priority??0)||e.sequence-t.sequence},$l=e=>({id:e.job.id,kind:e.job.kind,declaredCellCount:e.job.declaredCellCount});class Ql{schedule;clock;laneFactory;makeDummy;maxTimerDriftMs;onStatusChange;onJobResult;onJobInterrupted;cycleDurationMs;slotsPerEpoch;slotsPerLane;status="stopped";running=!1;sequence=0;generation=0;timer;hasTimer=!1;cycle;queued=[];jobs=new Map;constructor(e){if(Xl(e.schedule),this.schedule=Object.freeze({...e.schedule}),this.clock=e.clock,this.laneFactory=e.laneFactory,this.makeDummy=e.makeDummy,this.onStatusChange=e.onStatusChange,this.onJobResult=e.onJobResult,this.onJobInterrupted=e.onJobInterrupted,this.maxTimerDriftMs=e.maxTimerDriftMs??0,!Number.isFinite(this.maxTimerDriftMs)||this.maxTimerDriftMs<0||this.maxTimerDriftMs>=Wl(this.schedule))throw new Error("coverScheduler: max timer drift must be non-negative and less than one slot");this.cycleDurationMs=this.schedule.coverCadenceMs*this.schedule.coverDurationEpochs,this.slotsPerEpoch=this.schedule.coverLanes*this.schedule.coverFramesPerCell,this.slotsPerLane=this.schedule.coverFramesPerCell*this.schedule.coverDurationEpochs,this.assertClockNow()}getStatus(){return this.status}getQueuedJobIds(){return[...this.queued].sort(Vl).map(({job:e})=>e.id)}enqueue(e){if("string"!=typeof e.id||0===e.id.length)throw new Error("coverScheduler: job id must not be empty");if(this.jobs.has(e.id))throw new Error("coverScheduler: job id is already queued or admitted");if("real"!==e.kind&&"control"!==e.kind)throw new Error("coverScheduler: unsupported job kind");if(zl("declared cell count",e.declaredCellCount),e.declaredCellCount<1||e.declaredCellCount>this.slotsPerLane)throw new Error("coverScheduler: job does not fit the configured F x D lane capacity");if("function"!=typeof e.nextCell)throw new Error("coverScheduler: job nextCell must be a function");void 0!==e.priority&&zl("job priority",e.priority);const t={job:e,sequence:this.sequence++,state:"queued",everAdmitted:!1,sentCells:0,cancelRequested:!1,cancelSent:!1,completed:!1,settled:!1};this.jobs.set(e.id,t),this.queued.push(t),this.sortQueue()}cancel(e){const t=this.jobs.get(e);if(!t||t.settled)return"not-found";if(!t.everAdmitted)return this.removeQueued(t),this.settle(t,{jobId:e,outcome:"cancelled-before-admission"}),"cancelled-before-admission";if("function"!=typeof t.job.cancelCell)throw new Error("coverScheduler: an admitted cancellable job requires cancelCell");return t.cancelRequested=!0,t.completed=!1,this.sortQueue(),"cancel-pending"}complete(e){const t=this.jobs.get(e);return!(!t||t.settled)&&(this.removeQueued(t),t.completed=!0,t.pendingCell=void 0,this.settle(t,{jobId:e,outcome:"completed"}),!0)}start(){if("stopped"!==this.status)return!1;this.running=!0,this.setStatus("starting");const e=this.assertClockNow();return this.cycle?(this.armCycleBoundary(this.cycle.endMs),!0):(this.armOpenBoundary(this.nextCycleBoundary(e,!0)),!0)}suspend(e="suspended"){if("stopped"===this.status||"suspended"===this.status)return!1;this.disarm(),this.setStatus("suspended",e);const t=this.assertClockNow();return!this.cycle||(this.interruptCycle("suspended"),t<=this.cycle.endMs?this.armCycleBoundary(this.cycle.endMs):this.closeCurrentCycle("late-cleanup"),!0)}resume(){if("suspended"!==this.status)return!1;this.running=!0,this.disarm(),this.setStatus("starting");const e=this.assertClockNow();return this.cycle&&e<this.cycle.endMs?(this.armCycleBoundary(this.cycle.endMs),!0):(this.cycle&&this.closeCurrentCycle("late-cleanup"),this.armOpenBoundary(this.nextCycleBoundary(e,!1)),!0)}stop(){if("stopped"===this.status&&!this.cycle)return!1;this.running=!1,this.disarm(),this.setStatus("stopped");for(const e of[...this.jobs.values()])this.removeQueued(e),this.settle(e,{jobId:e.job.id,outcome:"failed",reason:"stopped"});if(this.cycle){for(const e of this.cycle.lanes)e.job=void 0;this.assertClockNow()<=this.cycle.endMs?this.armCycleBoundary(this.cycle.endMs):this.closeCurrentCycle("late-cleanup")}return!0}assertClockNow(){const e=this.clock.now();if(!Number.isFinite(e))throw new Error("coverScheduler: clock returned a non-finite time");return e}nextCycleBoundary(e,t){const n=(e-this.schedule.phaseOffsetMs)/this.cycleDurationMs;let r=Math.ceil(n),a=this.schedule.phaseOffsetMs+r*this.cycleDurationMs;if(!t&&a<=e&&(r++,a=this.schedule.phaseOffsetMs+r*this.cycleDurationMs),!Number.isSafeInteger(a))throw new Error("coverScheduler: next cycle boundary is out of range");return a}cycleIndexAtBoundary(e){const t=Math.round((e-this.schedule.phaseOffsetMs)/this.cycleDurationMs);return zl("cycle index",t),t}sortQueue(){this.queued.sort(Vl)}removeQueued(e){const t=this.queued.indexOf(e);-1!==t&&this.queued.splice(t,1)}dequeue(){return this.sortQueue(),this.queued.shift()}requeue(e,t){e.settled||e.completed||e.cancelSent||(e.state="queued",this.queued.includes(e)||this.queued.push(e),this.sortQueue(),this.safeNotify(()=>this.onJobInterrupted?.({jobId:e.job.id,reason:t})))}settle(e,t){e.settled||(e.settled=!0,e.state="terminal",this.removeQueued(e),this.jobs.get(e.job.id)===e&&this.jobs.delete(e.job.id),this.safeNotify(()=>this.onJobResult?.(t)))}setStatus(e,t){if(this.status===e)return;const n=this.status;this.status=e,this.safeNotify(()=>this.onStatusChange?.({previous:n,status:e,reason:t}))}safeNotify(e){try{e()}catch{}}disarm(){this.generation++,this.hasTimer&&(this.clock.clearTimeout(this.timer),this.hasTimer=!1,this.timer=void 0)}arm(e,t,n){this.disarm();const r=this.generation,a=()=>{if(r!==this.generation)return;const o=this.assertClockNow(),i=e-o,s=Math.min(2147483647,Math.max(0,i));this.hasTimer=!0,this.timer=this.clock.setTimeout(()=>{if(r!==this.generation)return;this.hasTimer=!1,this.timer=void 0;const o=this.assertClockNow();o<e?a():o>e+this.maxTimerDriftMs?this.handleLateTimer(t,e,o):Promise.resolve(n(r)).catch(()=>{"slot"===t?this.degrade("cell-production-failed"):this.suspend("boundary-handler-failed")})},s)};a()}armOpenBoundary(e){this.arm(e,"open-boundary",t=>this.openCycle(e,t))}armCycleBoundary(e){this.arm(e,"cycle-boundary",()=>this.handleCycleBoundary(e))}armSlot(e){const t=this.slotAt(e,e.nextSlotOrdinal);this.arm(t.deadlineMs,"slot",e=>this.sendSlot(t,e))}handleLateTimer(e,t,n){"slot"!==e?(this.cycle&&(this.interruptCycle("suspended"),this.closeCurrentCycle("late-cleanup")),"stopped"!==this.status&&this.setStatus("suspended","timer-drift")):this.degrade("missed-deadline")}async openCycle(e,t){if(t!==this.generation||!this.running||"stopped"===this.status||"suspended"===this.status)return;const n=this.cycleIndexAtBoundary(e),r=e+this.cycleDurationMs;if(!Number.isSafeInteger(r))throw new Error("coverScheduler: cycle end is out of range");const a=[];for(let e=0;e<this.schedule.coverLanes;e++)a.push(this.dequeue());for(const e of a)e&&(e.state="admitted",e.everAdmitted=!0);const o=[];let i=!1;for(let t=0;t<this.schedule.coverLanes;t++){const s=a[t],c={cycleIndex:n,cycleStartMs:e,cycleEndMs:r,laneIndex:t,job:s?$l(s):null};try{const e=this.laneFactory(c);if(null===e||"object"!=typeof e||"function"!=typeof e.send||"function"!=typeof e.close)throw new Error("invalid lane");o.push({laneIndex:t,handle:e,openContext:c,job:s})}catch{i=!0}}if(this.cycle={index:n,startMs:e,endMs:r,lanes:o,nextSlotOrdinal:0},i){this.setStatus("degraded","lane-open-failed");for(const e of this.cycle.lanes)e.job=void 0;for(const e of a)e&&this.requeue(e,"lane-open-failed");this.armCycleBoundary(r)}else this.setStatus("active"),t===this.generation&&"active"===this.status&&this.cycle?.index===n&&this.armSlot(this.cycle)}slotAt(e,t){const n=Math.floor(t/this.slotsPerEpoch),r=t%this.slotsPerEpoch,a=Math.floor(r/this.schedule.coverLanes),o=r%this.schedule.coverLanes,i=e.startMs+n*this.schedule.coverCadenceMs,s=(2*r+1)*this.schedule.coverCadenceMs;return{deadlineMs:i+Math.floor(s/(2*this.slotsPerEpoch)),cycleIndex:e.index,cycleStartMs:e.startMs,cycleEndMs:e.endMs,epochIndex:e.index*this.schedule.coverDurationEpochs+n,epochInCycle:n,laneIndex:o,frameIndex:a,laneSlotIndex:n*this.schedule.coverFramesPerCell+a}}jobSlot(e,t){return{...t,jobId:e.job.id,jobKind:e.job.kind,jobCellIndex:e.sentCells}}async requestForSlot(e,t){const n=e.job;if(n&&!n.settled){const e=this.jobSlot(n,t);if(n.cancelRequested&&!n.cancelSent){return{cell:n.pendingCancelCell??jl("cancelCell",await(n.job.cancelCell?.(e))),source:"cancel",slot:t,jobId:n.job.id,jobCellIndex:n.sentCells}}if(!n.completed&&n.sentCells<n.job.declaredCellCount){const r=n.pendingCell??await n.job.nextCell(e);if(null!==r){return{cell:jl("nextCell",r),source:n.job.kind,slot:t,jobId:n.job.id,jobCellIndex:n.sentCells}}}}return{cell:jl("makeDummy",await this.makeDummy(t)),source:"dummy",slot:t,...n?{jobId:n.job.id}:{}}}cacheUnsent(e,t){const n=(t.jobId?this.jobs.get(t.jobId):void 0)??e.job;n&&!n.settled&&("cancel"===t.source?n.pendingCancelCell=t.cell:"real"!==t.source&&"control"!==t.source||(n.pendingCell=t.cell))}acceptSent(e,t){const n=e.job;if(n&&!n.settled)return"cancel"===t.source?(n.pendingCancelCell=void 0,n.cancelSent=!0,void this.settle(n,{jobId:n.job.id,outcome:"cancelled"})):void("real"!==t.source&&"control"!==t.source||(n.pendingCell=void 0,n.sentCells++,n.sentCells===n.job.declaredCellCount&&(n.completed=!0,this.settle(n,{jobId:n.job.id,outcome:"completed"}))))}async sendSlot(e,t){const n=this.cycle;if(t!==this.generation||!n||"active"!==this.status)return;const r=n.lanes.find(({laneIndex:t})=>t===e.laneIndex);if(!r)return void this.degrade("lane-open-failed");let a,o;try{a=await this.requestForSlot(r,e)}catch{return void this.degrade("cell-production-failed")}if(t!==this.generation)return void this.cacheUnsent(r,a);if(this.assertClockNow()>e.deadlineMs+this.maxTimerDriftMs)return this.cacheUnsent(r,a),void this.degrade("missed-deadline");try{o=await r.handle.send(a)}catch{return this.cacheUnsent(r,a),void this.degrade("send-failed")}if(!1===o)return this.cacheUnsent(r,a),void this.degrade("backpressure");if(this.acceptSent(r,a),t!==this.generation||this.cycle!==n)return;n.nextSlotOrdinal++;const i=this.slotsPerEpoch*this.schedule.coverDurationEpochs;n.nextSlotOrdinal<i?this.armSlot(n):this.armCycleBoundary(n.endMs)}degrade(e){if("stopped"===this.status||"suspended"===this.status)return;this.disarm(),this.setStatus("degraded",e);const t=this.assertClockNow();if(this.cycle){if(this.interruptCycle(e),t<=this.cycle.endMs)return void this.armCycleBoundary(this.cycle.endMs);this.closeCurrentCycle("late-cleanup")}this.running&&this.armOpenBoundary(this.nextCycleBoundary(t,!1))}interruptCycle(e){if(this.cycle)for(const t of this.cycle.lanes){const n=t.job;t.job=void 0,n&&this.requeue(n,e)}}finalizeCycleJobs(){if(this.cycle)for(const e of this.cycle.lanes){const t=e.job;e.job=void 0,t&&!t.settled&&(t.cancelRequested&&!t.cancelSent?this.requeue(t,"missed-deadline"):this.settle(t,{jobId:t.job.id,outcome:"failed",reason:"capacity-exhausted"}))}}closeCurrentCycle(e){const t=this.cycle;if(!t)return!0;let n=!0;for(const r of[...t.lanes].sort((e,t)=>e.laneIndex-t.laneIndex))try{r.handle.close({...r.openContext,reason:e})}catch{n=!1}return this.cycle=void 0,n}handleCycleBoundary(e){const t=this.cycle;if(!t||t.endMs!==e)return;this.finalizeCycleJobs();if(!this.closeCurrentCycle("boundary"))return"stopped"!==this.status&&this.setStatus("degraded","lane-close-failed"),void(this.running&&this.armOpenBoundary(this.nextCycleBoundary(this.assertClockNow(),!1)));this.running&&"stopped"!==this.status&&"suspended"!==this.status&&this.openCycle(e,this.generation).catch(()=>{this.suspend("boundary-handler-failed")})}}const Wl=e=>e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell),Xl=e=>{if(null===e||"object"!=typeof e)throw new Error("coverScheduler: schedule must be an object");if(zl("phase offset",e.phaseOffsetMs),zl("cover cadence",e.coverCadenceMs),zl("cover lanes",e.coverLanes),zl("cover frames per cell",e.coverFramesPerCell),zl("cover duration epochs",e.coverDurationEpochs),e.coverCadenceMs<1)throw new Error("coverScheduler: cover cadence must be positive");if(e.coverLanes<1||e.coverLanes>16)throw new Error("coverScheduler: cover lanes must be between 1 and 16");if(e.coverFramesPerCell<1)throw new Error("coverScheduler: cover frames per cell must be positive");if(e.coverDurationEpochs<1)throw new Error("coverScheduler: cover duration epochs must be positive");const t=e.coverLanes*e.coverFramesPerCell,n=e.coverFramesPerCell*e.coverDurationEpochs,r=e.coverCadenceMs*e.coverDurationEpochs;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||!Number.isSafeInteger(r))throw new Error("coverScheduler: schedule geometry is out of range");if(Wl(e)<25)throw new Error("coverScheduler: schedule requires at least 25ms per staggered slot")},Gl=de-69-H,Jl=N,Yl=Gl-1-4,Zl=(1n<<64n)-1n,ed=(new TextEncoder).encode("p2party/cover-cell/key/v1\0");class td extends Error{code;constructor(e,t){super(`coverCell: ${t}`),this.name="CoverCellError",this.code=e}}const nd=(e,t)=>{throw new td(e,t)},rd=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&nd("invalid-cell",`${t} must be exactly ${String(n)} bytes`),e):nd("invalid-cell",`${t} must be a Uint8Array`),ad=(e,t)=>"bigint"!=typeof e||e<0n||e>Zl?nd("invalid-cell",`${t} must be an unsigned 64-bit bigint`):e,od=(e,t,n,r,a,o)=>{rd(n,"PQ message root",32),rd(r,"edge binding",32);const i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,ad(o,"keyEpoch"),!1);const s=new Uint8Array(ed.length+1+1+r.length+i.length);s.set(ed,0),s[ed.length]=(e=>e===fe?1:e===he?2:e===pe?3:nd("invalid-cell","authenticated room suite is unsupported"))(t),s[ed.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:nd("invalid-direction","cover-cell direction is unknown"))(a),s.set(r,ed.length+2),s.set(i,ed.length+2+r.length);const c=No(n,r,e);try{return qo(c,s,z,e)}finally{c.fill(0),i.fill(0)}},id=e=>{const t=rd(e.binding,"edge binding",32),n=ad(e.keyEpoch,"keyEpoch"),r=ad(e.counter,"counter"),a=(e=>{if("dummy"===e.subtype)return new Uint8Array(0);if("cancel"===e.subtype)return Uint8Array.from(rd(e.merkleRoot,"cancel transfer root",Jl));const t=rd(e.merkleRoot,"receipt transfer root",Jl),n=rd(e.token,"receipt token",Jl),r=new Uint8Array(t.length+n.length);return r.set(t,0),r.set(n,t.length),r})(e.content);a.length>Yl&&nd("invalid-cell","cover payload does not fit the uniform cell");const o=(()=>{const e=new Uint8Array(j);return crypto.getRandomValues(e),e})(),i=new Uint8Array(69);i[0]=4,i.set(t,1);const s=new DataView(i.buffer,i.byteOffset,i.byteLength);s.setBigUint64(33,r,!1),s.setBigUint64(49,n,!1),i.set(o,57);const c=new Uint8Array(Gl);var l;c[0]="dummy"===(l=e.content.subtype)?1:"cancel"===l?2:"receipt"===l?3:nd("invalid-cell","cover-cell subtype is unknown"),new DataView(c.buffer,c.byteOffset,c.byteLength).setUint32(1,a.length,!1),c.set(a,5);const d=od(e.module,e.rootSuite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+H,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{return new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a),0!==e._encrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?nd("invalid-cell","cover-cell AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{Da(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),Da(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),Da(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,d,o,c,i),n=new Uint8Array(de);return n.set(i,0),n.set(t,69),n}finally{d.fill(0),c.fill(0),a.fill(0)}},sd=e=>{const t=rd(e.frame,"cover cell",de),n=rd(e.binding,"edge binding",32),r=ad(e.keyEpoch,"keyEpoch");4!==t[0]&&nd("invalid-cell","frame type is not a cover cell"),((e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n})(t.subarray(1,33),n)||nd("binding-mismatch","cover cell belongs to another edge");const a=t.subarray(0,69),o=new DataView(t.buffer,t.byteOffset,t.byteLength),i=o.getBigUint64(33,!1);0n!==o.getBigUint64(41,!1)&&nd("invalid-cell","cover-cell reserved header must be zero"),o.getBigUint64(49,!1)!==r&&nd("epoch-mismatch","cover-cell epoch is not the expected epoch"),void 0!==e.counterAbove&&(ad(e.counterAbove,"counterAbove"),i<=e.counterAbove&&nd("replayed-counter","cover-cell counter is not strictly newer"));const s=t.subarray(57,69),c=t.subarray(69),l=od(e.module,e.rootSuite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-H,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a);const u=new Uint8Array(e.wasmMemory.buffer,d,o);return u.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?nd("authentication-failed","cover-cell authentication failed"):Uint8Array.from(u)}finally{Da(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),Da(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,l,s,c,a);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(1,!1);t>Yl&&nd("invalid-padding","encrypted cover payload length is invalid");const n=5,r=n+t;let o=0;for(let e=r;e<d.length;e+=1)o|=d[e];0!==o&&nd("invalid-padding","encrypted cover padding must be all zero");return{content:(u=d[0],h=d.subarray(n,r),1===u?(0!==h.length&&nd("invalid-cell","dummy cover cells carry no payload"),{subtype:"dummy"}):2===u?(h.length!==Jl&&nd("invalid-cell","CANCEL payload must be one 64-byte transfer root"),{subtype:"cancel",merkleRoot:Uint8Array.from(h)}):3===u?(h.length!==2*Jl&&nd("invalid-cell","receipt payload must be root ‖ token"),{subtype:"receipt",merkleRoot:h.slice(0,Jl),token:h.slice(Jl)}):nd("invalid-cell","cover-cell subtype is unknown")),counter:i}}finally{l.fill(0),d?.fill(0)}var u,h},cd={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},ld=(e,t)=>{if(e.length<8)throw new Error("coverRuntime: policy hash must be at least 8 bytes");if(!Number.isSafeInteger(t)||t<=0)throw new Error("coverRuntime: cover cadence must be a positive integer");const n=new DataView(e.buffer,e.byteOffset,e.byteLength);return Number(n.getBigUint64(0,!1)%BigInt(t))};class dd{#Q;#e;#W;#_;#U;#X;#G=0n;#J=null;#Y=new Set;static#Z=1024n;#ee=new Map;#te=!1;#p=!1;#ne="stopped";constructor(e){this.#Q=e.epc,this.#e=e.module,this.#W=e,this.#_=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#U=e.amInitiator?"responder-to-initiator":"initiator-to-responder";const t={...e.schedule,phaseOffsetMs:ld(e.policyHash,e.schedule.coverCadenceMs)},n=Wl(t),r=e.maxTimerDriftMs??Math.max(0,Math.min(Math.floor(n)-1,500));this.#X=(e=>new Ql(e))({schedule:t,maxTimerDriftMs:r,clock:e.clock??cd,laneFactory:e=>this.#re(e),makeDummy:e=>this.#ae(e),onStatusChange:t=>{this.#ne=t.status,e.onStatusChange?.(t)},onJobResult:t=>{const n=this.#ee.get(t.jobId);n&&(this.#ee.delete(t.jobId),n()),e.onJobResult?.(t)},onJobInterrupted:e.onJobInterrupted})}cellsPerLanePerCycle(){return this.#W.schedule.coverFramesPerCell*this.#W.schedule.coverDurationEpochs}onJobSettled(e,t){this.#j(),this.#ee.set(e,t)}randomLaneLabel(){return this.#oe()}get status(){return this.#ne}start(){this.#j(),this.#ie(),this.#X.start()}stop(){this.#se(),this.#X.stop()}destroy(){this.#p||(this.stop(),this.#p=!0)}suspend(e){this.#j(),this.#X.suspend(e)}resume(){this.#j(),this.#X.resume()}enqueue(e){this.#j(),this.#X.enqueue(e)}cancel(e){return this.#j(),this.#X.cancel(e)}complete(e){this.#j(),this.#X.complete(e)}getQueuedJobIds(){return this.#X.getQueuedJobIds()}sealCoverContent(e){return this.#j(),this.#ce(e)}processInboundCoverCell(e){this.#j();const t=this.#Q.pqHealingState;if(!t||e.length!==de)return!1;const n=t.currentMessageContext();try{const t=sd({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#U,keyEpoch:n.epoch,frame:e});return!!this.#le(t.counter)&&("cancel"===t.content.subtype?this.#W.onRemoteCancel?.(ca(t.content.merkleRoot)):"receipt"===t.content.subtype&&this.#W.onScheduledReceipt?.(ca(t.content.merkleRoot),t.content.token),!0)}catch{return!1}}async makeDummyLaneLabel(){const e=new Uint8Array(64);return crypto.getRandomValues(e),po(this.#W.laneLabelName,e)}#le(e){const t=this.#J;if(null!==t&&t>=dd.#Z&&e<=t-dd.#Z)return!1;if(this.#Y.has(e))return!1;if(this.#Y.add(e),(null===t||e>t)&&(this.#J=e,e>=dd.#Z)){const t=e-dd.#Z;for(const e of this.#Y)e<=t&&this.#Y.delete(e)}return!0}#ce(e){const t=this.#Q.pqHealingState;if(!t)throw new Error("coverRuntime: edge has no live PQ runtime");const n=t.currentMessageContext(),r=this.#G;return this.#G+=1n,id({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#_,keyEpoch:n.epoch,counter:r,content:e})}#ae(e){return this.#ce({subtype:"dummy"})}#re(e){const t=null!==e.job?e.job.id:this.#oe(),n=this.#W.openLaneChannel(t);return{send:e=>{if(e.cell.length!==de)throw new Error("coverRuntime: refusing a non-uniform cell at the lane boundary");if("open"!==n.readyState)return!1;if(n.bufferedAmount>=Z)return!1;const t=Uint8Array.from(e.cell);return n.send(t.buffer),!0},close:e=>{"closed"!==n.readyState&&n.close()}}}#oe(){const e=(new TextEncoder).encode(this.#W.laneLabelName),t=new Uint8Array(32);t.set(e.subarray(0,Math.min(32,e.length)));const n=new Uint8Array(64);return crypto.getRandomValues(n),`${ca(t)}~${ca(n)}`}#de=()=>{"undefined"!=typeof document&&("hidden"===document.visibilityState?this.#X.suspend("page-hidden"):this.#X.resume())};#ue=()=>{this.#X.suspend("pagehide")};#he=()=>{this.#X.suspend("freeze")};#fe=()=>{this.#X.suspend("offline")};#pe=()=>{this.#X.resume()};#ie(){this.#te||(this.#te=!0,"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.#de),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.#ue),window.addEventListener("freeze",this.#he),window.addEventListener("offline",this.#fe),window.addEventListener("online",this.#pe)))}#se(){this.#te&&(this.#te=!1,"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.#de),"undefined"!=typeof window&&(window.removeEventListener("pagehide",this.#ue),window.removeEventListener("freeze",this.#he),window.removeEventListener("offline",this.#fe),window.removeEventListener("online",this.#pe)))}#j(){if(this.#p)throw new Error("coverRuntime: runtime is destroyed")}}const ud=new WeakMap,hd=e=>{if(e.coverRuntime&&(e.coverRuntime.destroy(),e.coverRuntime=void 0),e.coverChannels){for(const t of e.coverChannels)"closed"!==t.readyState&&t.close();e.coverChannels.clear(),e.coverChannels=void 0}},fd=(e,t,n,r,a)=>{let o=ud.get(e);o||(o=new Map,ud.set(e,o)),o.set(r,{transferId:a,peerId:n,roomId:t})},pd=e=>{const t=e.epc.coverRuntime;if(!t)return!1;const n=is({runtime:t,channelMessageLabel:e.channelMessageLabel,totalChunks:e.totalChunks,sealSlotCell:e.sealSlotCell,getAckedChunks:e.getAckedChunks});return t.enqueue(n),!0},md=new Map,yd=(e,t)=>{const n=md.get(e);n&&(n.delete(t),0===n.size&&md.delete(e))},gd=(e,t)=>{e.controller.signal.aborted||e.controller.abort(t)},wd=()=>{const e=new Uint8Array(32);globalThis.crypto.getRandomValues(e);let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t},bd=e=>/^[0-9a-f]{64}$/.test(e),vd=(e,t=wd())=>{if(0===e.length)throw new Error("Transfer roomId must not be empty");if(!bd(t))throw new Error("Transfer ID must be 32-byte lowercase hex");if([...md.get(e)??[]].some(e=>e.transferId===t))throw new Error("Transfer ID is already active in this room");const n={transferId:t,controller:new AbortController,finished:!1};let r=md.get(e);return r||(r=new Set,md.set(e,r)),r.add(n),{transferId:t,signal:n.controller.signal,bindHash(e){n.hashHex=e},bindMerkleRoot(e){n.merkleRootHex=e},finish(){n.finished||(n.finished=!0,yd(e,n))}}},kd=(e,t)=>{if(!t.transferId&&!t.hashHex&&!t.merkleRootHex)throw new Error("Transfer cancellation requires a transfer ID, hash, or Merkle root");if(t.transferId&&!bd(t.transferId))throw new Error("Transfer ID must be 32-byte lowercase hex");const n=md.get(e);if(!n)return 0;const r=[...n].filter(e=>void 0!==t.transferId?e.transferId===t.transferId:void 0!==t.merkleRootHex?e.merkleRootHex===t.merkleRootHex:e.hashHex===t.hashHex);if(void 0===t.transferId&&r.length>1)throw new Error("Transfer selector is ambiguous; cancel with the random transfer ID");let a=0;for(const e of r)gd(e,new Error("Message transfer cancelled")),a++;return a},Id=e=>{const t=md.get(e);if(!t)return 0;let n=0;for(const e of t)gd(e,new Error("Room transfers cancelled")),n++;return n},Sd=()=>{let e=0;for(const t of[...md.keys()])e+=Id(t);return e},Cd=e=>{if(e?.aborted){if(e.reason instanceof Error)throw e.reason;throw new Error("Message transfer cancelled")}},Ad=async(e,t)=>(Cd(t),t?new Promise((n,r)=>{const a=()=>{o(),r(t.reason instanceof Error?t.reason:new Error("Message transfer cancelled"))},o=()=>t.removeEventListener("abort",a);t.addEventListener("abort",a,{once:!0}),e.then(e=>{o(),n(e)},e=>{o(),r(e)})}):e),Ed=e=>{e.fill(0)},Pd=e=>{if("string"!=typeof e||0===e.length)throw new Error("roomPinVault: room context must be a non-empty string")};const xd=new class{#me=new Map;#ye;constructor(e=Ed){this.#ye=e}put(e,t){Pd(e),(e=>{if(!(e instanceof Uint8Array))throw new Error("roomPinVault: PIN must be a Uint8Array");if(0===e.length)throw new Error("roomPinVault: PIN must not be empty")})(t);const n=Uint8Array.from(t),r=this.#me.get(e);r&&this.#ye(r),this.#me.set(e,n)}get(e){Pd(e);const t=this.#me.get(e);return t?Uint8Array.from(t):void 0}has(e){return Pd(e),this.#me.has(e)}delete(e){Pd(e);const t=this.#me.get(e);return!!t&&(this.#ye(t),this.#me.delete(e))}clear(){for(const e of this.#me.values())this.#ye(e);this.#me.clear()}},Kd=e=>xd.delete(e),Rd=()=>{xd.clear()},Md=3e5,_d=new Map,Ud=(e,t)=>{const n=t-Md,r=(_d.get(e)??[]).filter(e=>e>n);return 0===r.length?_d.delete(e):_d.set(e,r),r},Dd=async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=Ud(e,t);if(!(n.length<30))throw new Error(`PIN retries for this room are temporarily throttled until ${new Date(n[0]+Md).toISOString()}`)})(e,n);const r=await co(e,t);if(r&&r.retryAfter>n)throw new Error(`PIN retry for this peer identity is throttled until ${new Date(r.retryAfter).toISOString()}`)},Td=async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=Ud(e,t);n.push(t),_d.set(e,n)})(e,n),await((e,t,n,r,a,o)=>Wa("incrementPinAttemptState",e,t,n,r,a,o))(e,t,n,3,500,3e5)},Nd=(e,t)=>(void 0===t&&(e=>{_d.delete(e)})(e),((e,t)=>Wa("deletePinAttemptState",e,t))(e,t)),qd=new Map,Od=(new TextEncoder).encode("p2party/room-channel/v1\0"),Bd=(e,t,n)=>{const r=la(e);if(32!==r.length)throw new Error("Room capability must be 32 bytes");if(32!==n.length)throw new Error("Room policy hash must be 32 bytes");const a=(new TextEncoder).encode(t),o=new Uint8Array(Od.length+r.length+n.length+a.length);let i=0;return o.set(Od,i),i+=Od.length,o.set(r,i),i+=r.length,o.set(n,i),i+=n.length,o.set(a,i),o},Ld=async({channel:e,epc:t,roomId:n,dataChannels:r,incoming:a=!1},o)=>{const{keyPair:i,rooms:s}=o.getState(),c=s.findIndex(e=>e.id===n),l=[],d=new Set,u={value:!1},h=new AbortController,f=((e,t)=>({roomId:e,peerId:t,pending:[],seen:new Set,draining:!1,released:!1}))(n,t.withPeerId);if("string"==typeof e){const a=r.findIndex(r=>r.label===e&&r.withPeerId===t.withPeerId&&r.roomIds.includes(n));if(a>-1&&"open"===r[a].readyState)return r[a]}const p="string"==typeof e?e:e.label;if(0===p.length||p.length>193||!p.includes("~")&&(new TextEncoder).encode(p).length>32)throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected invalid or oversized DataChannel label");if(a&&"main"===p&&(m=i.publicKey,y=t.withPeerPublicKey,Fa(m,y)))throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected incoming main DataChannel on the designated opener side");var m,y;if(!a&&"main"===p&&!Fa(i.publicKey,t.withPeerPublicKey))throw new Error("Only the designated identity may create main DataChannel");if("main"===p&&t.mainChannel&&"closing"!==t.mainChannel.readyState&&"closed"!==t.mainChannel.readyState){if(!a)return t.mainChannel;if(t.mainChannel!==e)throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected duplicate main DataChannel")}const g="string"==typeof e?t.createDataChannel(e,{ordered:"main"===e,protocol:"raw"}):e;g.binaryType="arraybuffer";const w=g;w.withPeerId=t.withPeerId,w.roomIds=[n],"main"===w.label&&(t.mainChannel=w);const b="main"!==w.label&&void 0!==t.coverRuntime;if(b)t.coverChannels??=new Set,t.coverChannels.add(w);else if("main"!==w.label){if(t.messageChannels??=new Set,!t.messageChannels.has(w)&&t.messageChannels.size>=64)throw"closed"!==w.readyState&&w.close(),new Error("Too many message DataChannels on one peer edge");t.messageChannels.add(w)}const v=t.ratchetGateLease,k="main"===w.label?t.ratchetGateLease:void 0,I="main"===w.label?((e,t,n,r="hybrid-mlkem768",a=!1)=>{const o=Pl(e,t),i=El.get(o);if(i){const e=new Error("Handshake channel replaced");for(const t of i.waiters)t.reject(e)}const s={token:Symbol("handshake-inbox")};return El.set(o,{lease:s,pqMode:r,expectFinish:a,channel:n,queue:[],nextStep:1,waiters:[]}),s})(n,t.withPeerId,w,s[c]?.policy.pqMode??"hybrid-mlkem768",Fa(i.publicKey,t.withPeerPublicKey)):void 0;let S;try{S=await mo(p)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw t.messageChannels?.delete(w),t.mainChannel===w&&(t.mainChannel=void 0),I&&xl(n,t.withPeerId,r,I),"closed"!==w.readyState&&w.close(),r}const{channelLabel:C,merkleRoot:A,merkleRootHex:E}=S;let P=!1,x=!1;const K=()=>{x||(x=!0,(e=>{if(e.released)return;e.released=!0;const t=e.pending.length;e.pending.length=0,e.seen.clear(),t>0&&ws(e,-t)})(f),t.messageChannels?.delete(w))},R=()=>{P||(P=!0,h.signal.aborted||h.abort(new Error("Message channel processing stopped")),((e,t,n,r)=>{r&&(r.released=!0);const a=e.reduce((e,t)=>e+t.byteLength,0);e.length=0,a>0&&ys(e,t,n,-a),r&&ps(e,r)})(l,n,t.withPeerId,u),K())};w.releaseProtocolResources=R;let M,_=!1;const U=()=>M||(_=!0,R(),M=(async()=>{await ms(l,u),""!==E&&(await Fi(t,n,E),await ro(E))})(),M);return"main"!==w.label&&(w.cancelReceiveTransfer=U),w.onclose=async()=>{if(St(`Channel with label ${w.label} has closed.`),b){if(t.coverChannels?.delete(w),K(),await ms(l,u),""!==E)try{const e=await Ya(E);await zi(t,n,E,e)}catch(e){console.error(e)}R()}else if("main"===w.label){if(R(),k&&!Gi(n,t.withPeerId,k))return;I&&xl(n,t.withPeerId,new Error("Main data channel closed"),I),await o.dispatch(Du.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}));const e=Date.now(),r=qd.get(n)??0;e-r>2e3?(qd.set(n,e),o.dispatch(Ze({roomId:n,connectingToPeers:!0}))):St(`Skipping reconnection for ${n} - debounce (${String(e-r)}ms since last)`)}else{if(!r.includes(w))return;K(),await ms(l,u);let e,a=!1;if(_)try{await M,a=!0}catch(e){console.error(e)}else if(""!==E)try{e=await Ya(E);const r="connected"===t.connectionState&&Gi(n,t.withPeerId,v);a=void 0===t.coverRuntime&&((e,t,n)=>n&&void 0!==e&&e.fromPeerId===t&&Number.isFinite(e.totalSize)&&Number.isFinite(e.savedSize)&&e.totalSize>0&&e.savedSize>=0&&e.savedSize<e.totalSize)(e,t.withPeerId,r),void 0===t.coverRuntime&&!e&&r&&t.messageKeyByMerkleRoot?.has(E)&&(a=!0)}catch(e){console.error(e),a=!1}if(a)try{await U()}catch(e){console.error(e),a=!1}else{if(""!==E)try{await zi(t,n,E,e)}catch(e){console.error(e)}R()}await o.dispatch(Du.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:w.label,channel:w,alsoDeleteData:a}))}},w.onerror=async e=>{if(console.error(e),"main"===w.label){if(k&&!Gi(n,t.withPeerId,k))return;await o.dispatch(Du.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}))}else{if(!r.includes(w))return R(),void("closed"!==w.readyState&&w.close());await o.dispatch(Du.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:w.label,channel:w}))}const a=Date.now(),i=qd.get(n)??0;a-i>2e3?(qd.set(n,a),o.dispatch(Ze({roomId:n,connectingToPeers:!0}))):St(`Skipping reconnection for ${n} - debounce (${String(a-i)}ms since last)`)},w.onmessage=async e=>{const r=new Uint8Array(e.data);if("main"!==w.label&&!Ji(n,t.withPeerId,v))return console.error("Rejected application data before peer authentication"),R(),void("closed"!==w.readyState&&w.close());const a=(e=>{const t=e.length>=1?e[0]:-1,n=3===t&&e.length!==ie?-1:t;return{type:n,payload:-1===n?e.subarray(e.length):e.subarray(1)}})(r);if("main"!==w.label&&3===a.type){return void(((e,t,n)=>{if(t.released)return!1;const r=cs(e);if(t.seen.has(r))return!0;const a=hs.get(fs(t.roomId,t.peerId))??0;return!(t.pending.length>=2048||a>=8192||(t.seen.add(r),t.seen.size>4096&&t.seen.clear(),t.pending.push(e),ws(t,1),t.draining||bs(t,n),0))})(a.payload,f,async e=>{Ji(n,t.withPeerId,v)&&await Ao(e,w.label,w.withPeerId,n,o)})||(console.error("Closing message DataChannel: receipt queue budget exceeded"),R(),"closed"!==w.readyState&&w.close()))}if(2===a.type&&r.length===de){const e=((e,t,n,r,a,o,i,s,c,l,d,u,h,f)=>{if(r.released||f?.aborted)return!1;const p=cs(e);if(n.has(p))return!0;const m=ds.get(fs(o,i))??0;return!(t.length>=64||m+e.byteLength>16777216)&&(n.add(p),n.size>4096&&n.clear(),t.push(e),ys(t,o,i,e.byteLength),r.value||ks(t,n,r,a,o,i,s,c,l,d,u,h,f),!0)})(r,l,d,u,o,n,w.withPeerId,C,E,A,w,t,t.receiveMessageModule,h.signal);return void(e||(console.error("Closing message DataChannel: receive queue budget exceeded"),R(),"closed"!==w.readyState&&w.close()))}if(("main"===w.label||b)&&5===a.type&&r.length===de)return Ji(n,t.withPeerId,v)?void Fl(t,n,r):void console.error("Rejected PQ control cell before peer authentication");if(4===a.type&&r.length===de&&t.coverRuntime)return Ji(n,t.withPeerId,v)?void t.coverRuntime.processInboundCoverCell(r):void console.error("Rejected cover cell before peer authentication");if("main"===w.label){const{type:e,payload:r}=a;if(1===e)return void(I&&!Kl(n,t.withPeerId,r,I)&&(console.error("Closing main DataChannel: malformed or surplus handshake frame"),R(),"closed"!==w.readyState&&w.close()))}console.error(new Error("Wrong data length received"))},w.onopen=()=>{if("main"!==w.label&&!Gi(n,t.withPeerId,v))return R(),void("closed"!==w.readyState&&w.close());St(`Channel with label "${w.label}" and client ${t.withPeerId} is open.`),r.includes(w)||r.push(w),""===E&&C.length>0&&o.dispatch(it({roomId:n,label:p,peerId:w.withPeerId})),"main"===w.label&&(async()=>{let e,r=!1,a=!1;o.dispatch(ot({roomId:n,peerId:t.withPeerId,status:"authenticating"}));try{if(!k||!I)throw new Error("Main channel has no transport ownership lease");const d=s[c];if(!d)throw new Error("Handshake room is unavailable");if("pin"===d.policy.authMode&&(r=!0,l=d.url,e=xd.get(l),!e))throw new Error("PIN room has no local PIN");r&&await Dd(n,t.withPeerPublicKey);const u=Fa(i.publicKey,t.withPeerPublicKey),h=la(i.publicKey),f=la(t.withPeerPublicKey),p=Cl(t.localDescription?.sdp??""),m=Cl(t.remoteDescription?.sdp??""),y=await $e(d.policy),g=sl({channelId:Bd(d.url,w.label,y),ikInitiator:u?h:f,ikResponder:u?f:h,fpInitiator:u?p:m,fpResponder:u?m:p,pqMode:d.policy.pqMode});a=!0,await Rl(t,n,d.policy.authMode,d.policy.pqMode,e??null,g,t.receiveMessageModule,I,k),o.dispatch(ot({roomId:n,peerId:t.withPeerId,status:"authenticated"})),((e,t,n)=>{e.pqHealingState||Ul("cannot install an orchestrator without a PQ runtime"),Ol(e);const r={roomId:t,hooks:n,now:n.now??Date.now,persistEdge:n.persistEdge??_l,interval:null,busy:!1,inboundBlocked:!1,destroyed:!1,failed:!1};Ml.set(e,r);const a=n.tickMs??1e3;a>0&&(r.interval=setInterval(()=>{Ll(e)},a))})(t,n,{sendControlFrame:e=>"open"===w.readyState&&(w.send(e.buffer),!0),failEdge:e=>{console.error(e),"closed"!==w.readyState&&w.close(),"closed"!==t.connectionState&&t.close()}}),(e=>{const{epc:t,roomId:n,policy:r}=e;if("scheduled"!==r.coverMode)return;hd(t),t.coverChannels??=new Set;const a=new dd({epc:t,roomId:n,module:e.module,amInitiator:e.amInitiator,schedule:{coverCadenceMs:r.coverCadenceMs,coverLanes:r.coverLanes,coverFramesPerCell:r.coverFramesPerCell,coverDurationEpochs:r.coverDurationEpochs},policyHash:e.policyHash,laneLabelName:"p2party-cover",openLaneChannel:e=>{const r=t.createDataChannel(e,{ordered:!0,protocol:"raw"});return r.binaryType="arraybuffer",r.withPeerId=t.withPeerId,r.roomIds=[n],t.coverChannels.add(r),r.addEventListener("close",()=>{t.coverChannels?.delete(r)}),{label:r.label,get readyState(){return r.readyState},get bufferedAmount(){return r.bufferedAmount},send:e=>r.send(e),close:()=>{"closed"!==r.readyState&&r.close()}}},onStatusChange:e.onStatusChange,onRemoteCancel:e.onRemoteCancel,onScheduledReceipt:e=>{const n=ud.get(t)?.get(e);n&&ko(n.roomId,n.peerId,n.transferId)}});t.coverRuntime=a,a.start()})({epc:t,roomId:n,policy:d.policy,policyHash:y,amInitiator:u,module:t.receiveMessageModule,onStatusChange:({status:e})=>{o.dispatch(at({roomId:n,peerId:t.withPeerId,status:e}))},onRemoteCancel:e=>{try{kd(n,{merkleRootHex:e})}catch(e){console.error("scheduled CANCEL abort failed",e)}}}),r&&await Nd(n,t.withPeerPublicKey).catch(e=>{console.error("Could not clear successful PIN attempt state:",e)})}catch(e){const i=e instanceof Error?e:new Error(String(e));r&&a&&/key-confirmation/i.test(i.message)&&await Td(n,t.withPeerPublicKey).catch(e=>{console.error("Could not persist PIN attempt state:",e)});let s,c="transport";const l=/throttled until (\S+)/.exec(i.message);if(l){c="pin-throttled";const e=Date.parse(l[1]);Number.isFinite(e)&&(s=e)}else if(a&&/key-confirmation/i.test(i.message)&&(c=r?"pin-mismatch":"policy",r))try{const e=await co(n,t.withPeerPublicKey);e&&e.retryAfter>Date.now()&&(s=e.retryAfter)}catch{}o.dispatch(ot({roomId:n,peerId:t.withPeerId,status:"failed",reason:c,retryAfter:s})),k&&Yi(n,t.withPeerId,i,k),I&&xl(n,t.withPeerId,i,I),console.error("protocol-v4 handshake failed:",i),"closed"!==w.readyState&&w.close(),"closed"!==t.connectionState&&t.close()}finally{e?.fill(0)}var l})(),""!==E&&"string"!=typeof e&&(async()=>{try{if(!await(async()=>!!Gi(n,t.withPeerId,v)&&(await Xi(n,t.withPeerId),Gi(n,t.withPeerId,v)))())return;const e=await(e=>Wa("getDBAllChunkLeafHashes",e))(E);if(0===e.length)return;let r=[];for(const{chunkIndex:t,leafHash:n}of e)if(n?.length===2*N&&(r.push(await _o(A,t,la(n))),32===r.length)){if(!await ts(w,r))return;r=[]}if(r.length>0&&!await ts(w,r))return;const a=await Ya(E);a&&a.totalSize>0&&a.savedSize===a.totalSize&&a.hash.length===2*N&&es(w,la(a.hash))}catch(e){console.error(e)}})()},w},Fd=/(?:^|\r?\n)a=ice-ufrag:([^\r\n]+)/g,zd=/(?:^|\s)ufrag\s+([^\s]+)/i,jd=(e,t)=>{const n=(e=>{const t=new Set,n=e?.sdp;if(!n)return t;for(const e of n.matchAll(Fd)){const n=e[1].trim();n&&t.add(n)}return t})(t);if(0===n.size)return!0;const r=(e=>{const t=e.usernameFragment?.trim();if(t)return t;const n=e.candidate?.match(zd)?.[1];return n?.trim()||null})(e);return null===r||n.has(r)},Hd=async(e,t)=>{if(!("closed"===e.connectionState||"closed"===e.signalingState))try{return e.restartIce(),"restarted"}catch{}return await t(),"disconnected"},Vd=(e,t,n)=>e.findIndex(e=>((e,t,n)=>e.roomId===t&&e.withPeerId===n)(e,t,n)),$d=(e,t,n)=>{const r=Vd(e,t,n);return r<0?void 0:e[r]};class Qd{queue=[];locked=!1;idleWaiters=[];async acquire(){if(this.locked)return new Promise(e=>{this.queue.push(e)});this.locked=!0}release(){const e=this.queue.shift();if(e)e();else{this.locked=!1;for(const e of this.idleWaiters.splice(0))e()}}isIdle(){return!this.locked&&0===this.queue.length}whenIdle(){return this.isIdle()?Promise.resolve():new Promise(e=>{this.idleWaiters.push(e)})}async runExclusive(e){await this.acquire();try{return await e()}finally{this.release()}}}const Wd=new Map,Xd=new Map,Gd=(e,t)=>`${String(e.length)}:${e}${t}`,Jd=(e,t)=>`${String(e.length)}:${e}${t}`,Yd=(e,t)=>{const n=Gd(e,t);let r=Wd.get(n);return r||(r=new Qd,Wd.set(n,r)),r},Zd=(e,t)=>{const n=Gd(e,t),r=Wd.get(n);r&&(async()=>{for(;;)if(await r.whenIdle(),r.isIdle())return void(Wd.get(n)===r&&Wd.delete(n))})()},eu=async({peerId:t,peerPublicKey:n,roomId:r,peerConnections:a,rtcConfig:o},i)=>{const{keyPair:s,signalingServer:c}=i.getState();if(o??=We,!e(t))throw new Error("PeerId is not a valid uuidv4");if(La(s.publicKey,"Self Ed25519 identity"),La(n,"Peer Ed25519 identity"),n===s.publicKey)throw new Error("Cannot connect to the same Ed25519 identity");const l=((e,t)=>{const n=Jd(e,t);let r=Xd.get(n);return r||(r=new Qd,Xd.set(n,r)),r})(r,n);await l.acquire();try{const e=((e,t,n,r)=>e.filter(e=>e.roomId===t&&e.withPeerPublicKey===r&&e.withPeerId!==n))(a,r,t,n);for(const t of e)await i.dispatch(Du.endpoints.disconnectFromPeer.initiate({roomId:r,peerId:t.withPeerId}));let l=$d(a,r,t);if(l&&l.withPeerPublicKey!==n&&(await i.dispatch(Du.endpoints.disconnectFromPeer.initiate({roomId:r,peerId:t})),l=void 0),l)return await l.initialization,l;const d=((e,t,n=new Error("Ratchet gate reset"))=>{const r=Qi(e,t),a=$i.get(r);return a&&!a.settled&&(a.settled=!0,a.outcome="rejected",a.reject(n)),$i.delete(r),Wi(e,t).lease})(r,t,new Error("Ratchet transport replaced by a new room/peer connection")),u=new RTCPeerConnection(o);u.roomId=r,u.withPeerId=t,u.withPeerPublicKey=n,u.makingOffer=!1,u.ignoreOffer=!1,u.iceCandidates=[],u.ratchetGateLease=d,Ri(u,r),a.push(u);const h=()=>{if(!a.includes(u))throw new Error("WebRTC transport was replaced during initialization")},f=(async()=>{const e=ya(),a=await Ua(e);h(),u.receiveMessageModule=a,c.isConnected&&(await i.dispatch(Vu.endpoints.connectWithPeer.initiate({roomId:r,peerId:t,peerPublicKey:n})),h())})();u.initialization=f;try{await f}catch(e){const t=a.indexOf(u);throw t>-1&&a.splice(t,1),"closed"!==u.connectionState&&u.close(),e}finally{u.initialization=void 0}u.onnegotiationneeded=async()=>{if(u.makingOffer||"stable"!==u.signalingState)St(`Skipping negotiation with ${t} - already making offer: ${String(u.makingOffer)}, state: ${u.signalingState}`);else try{u.makingOffer=!0,await u.setLocalDescription(),u.localDescription&&(await i.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"description",description:u.localDescription,fromPeerId:s.peerId,fromPeerPublicKey:s.publicKey,toPeerId:t,roomId:r,protocolVersion:4}})),St(`Negotiation was needed with ${t} and you sent a description ${u.localDescription.type}.`))}catch(e){console.error(e)}finally{u.makingOffer=!1}},u.onicecandidate=async({candidate:e})=>{e&&""!==e.candidate&&await i.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"candidate",candidate:e,fromPeerId:s.peerId,toPeerId:t,roomId:r,protocolVersion:4}}))},u.onicecandidateerror=e=>{console.error(e)};let p=0;const m=3e3;let y;return u.oniceconnectionstatechange=async()=>{if("failed"===u.iceConnectionState||"disconnected"===u.iceConnectionState){const{signalingServer:e}=i.getState();!e.isConnected&&!e.isEstablishingConnection&&e.serverUrl.length>0&&await i.dispatch(Vu.endpoints.connectWebSocket.initiate(e.serverUrl));const n=Date.now();n-p>m&&(p=n,St(`ICE ${u.iceConnectionState} with ${t}, restarting`),u.restartIce())}St(`ICE candidate connection state with ${t} is ${u.iceConnectionState}.`)},u.onicegatheringstatechange=()=>{St(`ICE gathering state with ${t} is ${u.iceGatheringState}.`)},u.onsignalingstatechange=async()=>{St(`Signaling state with ${t} is ${u.signalingState}.`),"stable"===u.signalingState&&u.remoteDescription&&await(async e=>{for(;e.iceCandidates.length>0&&"stable"===e.signalingState&&e.remoteDescription;){const t=e.iceCandidates.shift();if(t&&jd(t,e.remoteDescription))try{await e.addIceCandidate(t)}catch(e){console.warn("Could not add queued ICE candidate:",e)}}})(u)},u.onconnectionstatechange=async()=>{if("disconnected"===u.connectionState)await Hd(u,()=>{}).catch(()=>{}),y&&clearTimeout(y),y=setTimeout(()=>{"disconnected"===u.connectionState&&(i.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:r})),console.error(`RTC Connection with peer ${t} in room ${r} has disconnected.`))},8e3);else if("closed"===u.connectionState||"failed"===u.connectionState){if(y&&(clearTimeout(y),y=void 0),await i.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:r})),console.error(`RTC Connection with peer ${t} in room ${r} has ${u.connectionState}.`),"closed"===u.connectionState){const{signalingServer:e}=i.getState();e.isConnected&&await i.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:s.peerId,roomId:r,protocolVersion:4}}))}}else y&&(clearTimeout(y),y=void 0),"connected"===u.connectionState&&(i.dispatch(rt({roomId:r,peerId:t,peerPublicKey:n})),St(`RTC Connection status with peer ${t} is ${u.connectionState}.`))},u}finally{l.release(),((e,t)=>{const n=Jd(e,t),r=Xd.get(n);r&&r.whenIdle().then(()=>{r.isIdle()&&Xd.get(n)===r&&Xd.delete(n)})})(r,n)}},tu=async(e,t,n)=>{const r=e.createDataChannel("main",{ordered:!0,protocol:"raw"});e.mainChannel=await Ld({channel:r,epc:e,roomId:e.roomId,dataChannels:t},n)},nu=(e,t,n)=>{for(let r=e.length-1;r>=0;r--)e[r].roomId===t&&e[r].withPeerId===n&&e.splice(r,1)},ru=async({peerId:e,peerPublicKey:t,roomId:n,description:r,rtcConfig:a,peerConnections:o,iceCandidates:i,dataChannels:s},c)=>Yd(n,e).runExclusive(async()=>{const{keyPair:l}=c.getState(),d=Vd(o,n,e),u=d>-1?o[d]:await eu({peerId:e,peerPublicKey:t,roomId:n,peerConnections:o,rtcConfig:a},c);-1!==d&&null!=o[d].ondatachannel||(u.ondatachannel=async e=>{try{const t=await Ld({channel:e.channel,epc:u,roomId:u.roomId,dataChannels:s,incoming:!0},c);"main"===t.label&&(u.mainChannel=t)}catch(e){console.error("Rejected incoming DataChannel:",e)}});const h="offer"===r.type&&(u.makingOffer||"stable"!==u.signalingState),f=l.peerId<u.withPeerId,p=!f&&h;u.ignoreOffer=p;const m=()=>{((e,t,n,r)=>{e.length=0,nu(t,n,r)})(u.iceCandidates,i,n,e)};if(p)return m(),{data:void 0};if(h&&f)try{await u.setLocalDescription({type:"rollback"}),St(`Polite peer rolled back local description for ${e}`)}catch(t){console.error(`Failed to rollback for ${e}:`,t)}if(u.iceCandidates.push(...((e,t,n)=>{const r=[];for(let a=e.length-1;a>=0;a--){const o=e[a];o.roomId===t&&o.withPeerId===n&&(r.unshift(o),e.splice(a,1))}return r})(i,n,e)),-1===Vd(o,n,e)&&o.push(u),"closed"===u.signalingState)return m(),{data:void 0};if("answer"===r.type&&"have-local-offer"!==u.signalingState)return console.warn(`Ignoring stale answer from ${e} in signaling state ${u.signalingState}`),m(),{data:void 0};try{await u.setRemoteDescription(r)}catch(t){const n=t;if("answer"===r.type&&n.message?.includes("Called in wrong state"))return console.warn(`Ignoring late answer from ${e}: ${n.message}`),m(),{data:void 0};if(!n.message?.includes("ICE restart"))return console.error(`setRemoteDescription failed for ${e}:`,t),m(),{data:void 0};console.warn(`ICE restart mismatch with ${e}, accepting remote restart`);try{"stable"!==u.signalingState&&await u.setLocalDescription({type:"rollback"}),await u.setRemoteDescription(r)}catch(t){return console.error(`Failed to handle ICE restart for ${e}:`,t),m(),{data:void 0}}}if("offer"===r.type){try{await u.setLocalDescription()}catch(t){return console.error(`setLocalDescription failed for ${e}:`,t),m(),{data:void 0}}const t=u.localDescription;t&&await c.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"description",description:t,fromPeerId:l.peerId,fromPeerPublicKey:l.publicKey,toPeerId:e,roomId:n,protocolVersion:4}}))}if("connected"===u.connectionState&&d>-1&&Fa(l.publicKey,u.withPeerPublicKey)&&(!u.mainChannel||"closing"===u.mainChannel.readyState||"closed"===u.mainChannel.readyState)){const e=u.createDataChannel("main",{ordered:!0,protocol:"raw"});u.mainChannel=await Ld({channel:e,epc:u,roomId:u.roomId,dataChannels:s},c)}return{data:void 0}}),au=(e,t)=>new Promise((n,r)=>{try{if(e===t)return void n(e);if(t<e)throw new RangeError("randomNumberInRange: max must be >= min");const r=BigInt(t)-BigInt(e),a=Math.ceil(r.toString(2).length/8),o=(1n<<BigInt(8*a))/r*r,i=new Uint8Array(a);let s=o;for(;s>=o;){window.crypto.getRandomValues(i),s=0n;for(let e=0;e<a;e++)s=(s<<8n)+BigInt(i[e])}n(e+Number(s%r))}catch(e){r(e instanceof Error?e:new Error(String(e)))}}),ou=async(e,t,n=!0,r=!0,a=!0)=>{if(t??=e,0===t&&e===t)return"";const o=t>e?await au(e,t):e,i=await((e,t=!0,n=!0,r=!0)=>new Promise((a,o)=>{try{let o="";t&&(o+="abcdefghijklmnopqrstuvwxyz"),n&&(o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"),r&&(o+="0123456789");let i="";for(let t=0;t<e;t++)i+=o[iu(0,o.length)];a(i)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}))(o,n,r,a);return i};function iu(e,t){if(!(t>e))return e;const n=t-e,r=Math.floor(4294967296/n)*n;let a;do{a=crypto.getRandomValues(new Uint32Array(1))[0]}while(a>=r);return e+a%n}const su=(e,t)=>{const n=t._malloc(q),r=t._malloc(1+e.length),a=t._malloc(N);try{const o=new Uint8Array(t.wasmMemory.buffer,r,1+e.length);if(o[0]=0,o.set(e,1),0!==t._sha512_init(n))throw new Error("hashMerkleLeafWasm: sha512_init failed");if(0!==t._sha512_update(n,r,1+e.length))throw new Error("hashMerkleLeafWasm: sha512_update failed");if(0!==t._sha512_final(n,a))throw new Error("hashMerkleLeafWasm: sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,a,N))}finally{t._free(n),t._free(r),t._free(a)}},cu=async e=>{const t=new Uint8Array(1+e.length);t[0]=0,t.set(e,1);const n=await window.crypto.subtle.digest("SHA-512",t);return new Uint8Array(n)},lu=async(e,t)=>{if(e.length%N!==0)throw new Error("Hashes were not passed");const n=e.length/N;if(0===n)throw new Error("Cannot calculate Merkle root of tree with no leaves.");if(1===n)return e;const r=t?.wasmMemory??ga(n),a=t??await Ua(r),o=a._malloc(n*N),i=new Uint8Array(r.buffer,o,n*N);i.set(e);const s=a._malloc(N),c=new Uint8Array(r.buffer,s,N),l=a._get_merkle_root(n,i.byteOffset,c.byteOffset);switch(a._free(o),l){case 0:{const e=Uint8Array.from([...c]);return a._free(s),e}case-1:throw a._free(s),new Error("Could not allocate memory for hash concatenation helper array.");case-2:throw a._free(s),new Error("Could not calculate hash.");default:throw a._free(s),new Error("Unexpected error occured.")}},du=async(e,t,n,r)=>{if(e.length%N!==0)throw new Error("Hashes were not passed");const a=e.length/N;if(0===a)throw new Error("Cannot calculate Merkle proof of element of empty tree.");if(1===a){const e=new Uint8Array(N+1);if(e.set(t),r){const t=N+1,n=globalThis.crypto.getRandomValues(new Uint8Array(r));let a=0;const o=4;return new DataView(n.buffer,a,o).setUint32(0,t,!1),a+=o,n.set(e,a),n}return e}const o=n?.wasmMemory??wa(a),i=n??await Ua(o),s=i._malloc(a*N),c=new Uint8Array(o.buffer,s,a*N);c.set(e);const l=i._malloc(N),d=new Uint8Array(o.buffer,l,N);d.set(t);const u=a*(N+1),h=i._malloc(u),f=new Uint8Array(o.buffer,h,u),p=i._get_merkle_proof(a,c.byteOffset,d.byteOffset,f.byteOffset);switch(i._free(s),i._free(l),p){case-1:throw i._free(h),new Error("Element not in tree.");case-2:throw i._free(h),new Error("Could not allocate memory for hash concatenation helper array.");case-3:throw i._free(h),new Error("Could not calculate hash.");default:if(p>0){if(r&&r>=p){const e=globalThis.crypto.getRandomValues(new Uint8Array(r));let t=0;const n=4;return new DataView(e.buffer,t,n).setUint32(0,p,!1),t+=n,e.set(f.slice(0,p),t),i._free(h),e}{const e=Uint8Array.from([...f.slice(0,p)]);return i._free(h),e}}throw i._free(h),new Error("An unexpected error occured")}},uu=[1],hu=(e,t=1,n=ne,r=.9)=>{if(t<1)throw new Error("Need at least one chunk.");if(r<1e-4||r>.99)throw new Error("Percentage of useful data in chunk should be in (0, 0.99].");if(n>ne||n<=re)throw new Error(`Chunk length needs to be between ${String(re)} and ${String(ne)}`);if(!Number.isSafeInteger(e)||e<1)throw new Error("No data to split in chunks");if(e>Y)throw new Error(`Message exceeds the ${String(Y)} byte protocol limit`);const a=Math.ceil(n*r),o=Math.ceil(e/a);return Math.max(t,o)},fu=async(e,t,n,r,a,o,i=1,s=ne,c=.9,l=1)=>{const{keyPair:d}=t.getState();if(!uu.includes(l))throw new Error("Unknown metadata version schema.");const u=(e=>{if("string"==typeof e)return xo.Text;const t=e.name.split(".").pop()?.toLowerCase()??"";return{png:xo.ImagePNG,jpeg:xo.ImageJPEG,jpg:xo.ImageJPG,gif:xo.ImageGIF,bmp:xo.ImageBMP,tiff:xo.ImageTIFF,svg:xo.ImageSVG,webp:xo.ImageWEBP,heic:xo.ImageHEIC,pdf:xo.DocumentPDF,doc:xo.DocumentDOC,docx:xo.DocumentDOCX,xls:xo.DocumentXLS,xlsx:xo.DocumentXLSX,ppt:xo.DocumentPPT,pptx:xo.DocumentPPTX,txt:xo.DocumentTXT,rtf:xo.DocumentRTF,odt:xo.DocumentODT,mp3:xo.AudioMP3,wav:xo.AudioWAV,aac:xo.AudioAAC,flac:xo.AudioFLAC,ogg:xo.AudioOGG,m4a:xo.AudioM4A,mp4:xo.VideoMP4,avi:xo.VideoAVI,mkv:xo.VideoMKV,mov:xo.VideoMOV,wmv:xo.VideoWMV,flv:xo.VideoFLV,webm:xo.VideoWEBM,zip:xo.CompressedZIP,rar:xo.CompressedRAR,"7z":xo.Compressed7Z,tar:xo.CompressedTAR,gz:xo.CompressedGZ,html:xo.CodeHTML,css:xo.CodeCSS,js:xo.CodeJS,ts:xo.CodeTS,jsx:xo.CodeJSX,tsx:xo.CodeTSX,json:xo.CodeJSON,xml:xo.CodeXML,py:xo.CodePY,java:xo.CodeJAVA,c:xo.CodeC,cpp:xo.CodeCPP,cs:xo.CodeCS,rb:xo.CodeRB,php:xo.CodePHP,sql:xo.CodeSQL,epub:xo.EbookEPUB,mobi:xo.EbookMOBI,azw:xo.EbookAZW,ttf:xo.FontTTF,otf:xo.FontOTF,ico:xo.ImageICO,exe:xo.ExecutableEXE,dmg:xo.ExecutableDMG,apk:xo.ExecutableAPK}[t]??xo.Unknown})(e),h=u===xo.Text?await ou(256):e.name.substring(0,255),f="string"==typeof e?(new TextEncoder).encode(e):e,p="string"==typeof e?f.length:f.size,m=hu(p,i,s,c),y=await navigator.storage.estimate(),g=y.quota??10737418240,w=y.usage??65536,b=Math.max(0,g-w),v=((e,t,n)=>{if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<1||!Number.isSafeInteger(n)||n<1)throw new Error("Invalid outbound staging geometry");const r=e+t*(n+ee+te+2048);return Number.isSafeInteger(r)?r:Number.POSITIVE_INFINITY})(p,m,s);if(v>b)throw new Error("Not enough space to stage the padded encrypted transfer in the browser.");const k=new Date;let I;if(o.signal.aborted)throw o.signal.reason instanceof Error?o.signal.reason:new Error("Message transfer cancelled");if("string"==typeof e){const e=await window.crypto.subtle.digest("SHA-512",f.buffer);I=new Uint8Array(e)}else I=await(async(e,t,n)=>{const r=()=>{if(n?.aborted){if(n.reason instanceof Error)throw n.reason;throw new Error("Message transfer cancelled")}},a=t._malloc(q),o=t._malloc(be),i=t._malloc(N);try{if(r(),0!==t._sha512_init(a))throw new Error("sha512_init failed");const n=new Uint8Array(t.wasmMemory.buffer,o,be);for(let i=0;i<e.size;i+=we){r();const s=Math.min(i+we,e.size),c=new Uint8Array(await e.slice(i,s).arrayBuffer());r();for(let e=0;e<c.length;e+=be){r();const i=Math.min(be,c.length-e);if(n.set(c.subarray(e,e+i),0),0!==t._sha512_update(a,o,i))throw new Error("sha512_update failed")}}if(r(),0!==t._sha512_final(a,i))throw new Error("sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,i,N))}finally{t._free(a),t._free(o),t._free(i)}})(f,a,o.signal);if(o.signal.aborted)throw o.signal.reason instanceof Error?o.signal.reason:new Error("Message transfer cancelled");const S=ca(I);o.bindHash(S);const C={schemaVersion:l,messageType:u,hash:I,name:h,totalSize:p,date:k};let A=0;const E=new Uint8Array(s),P=new Uint8Array(m*N),x=Math.floor(s*(1-c)),K=Math.ceil(s*c);for(let a=0;a<m&&!o.signal.aborted;a++){window.crypto.getRandomValues(E);const i=await au(0,x),s=p-A,c=Math.min(Math.max(s,0),K);let l=i+c;if(s>0){const t=f.slice(A,A+c);if("string"==typeof e)E.set(t,i);else{const e=await t.arrayBuffer();if(o.signal.aborted)break;E.set(new Uint8Array(e),i)}A+=c}else{const e=l+p+1,t=Number.MAX_SAFE_INTEGER-e;l+=await au(e,t)}const y=await cu(E),g=ca(y);P.set(y,a*N);const w=Eo({...C,chunkStartIndex:i,chunkEndIndex:l,chunkIndex:a});await ao({transferId:o.transferId,hash:S,merkleRoot:"",chunkIndex:a,leafHash:g,receiptToken:"",data:E.slice().buffer,metadata:w.buffer,merkleProof:(new Uint8Array).buffer}),t.dispatch(ct({roomId:r.id,transferId:o.transferId,merkleRootHex:"",sha512Hex:S,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:a+1,totalChunks:m,messageType:u,filename:h,channelLabel:n,timestamp:k.getTime()}))}if(o.signal.aborted)return await oo({transferId:o.transferId}),t.dispatch(ft({roomId:r.id,transferId:o.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};const R=await lu(P,a),M=ca(R);try{const e=Ro(u);for(let t=0;t<m&&!o.signal.aborted;t++){const n=await eo(o.transferId,t);if(!n)throw new Error(`Missing staged outbound chunk ${String(t)}`);const r=Po(new Uint8Array(n.metadata)),a=r.chunkEndIndex-r.chunkStartIndex;a<=0||a>r.totalSize||await to({merkleRoot:M,hash:S,chunkIndex:r.chunkIndex,data:n.data.slice(r.chunkStartIndex,r.chunkEndIndex),mimeType:e})}}catch(e){throw await ro(M),e}if(o.signal.aborted)return await oo({transferId:o.transferId}),await ro(M),t.dispatch(ft({roomId:r.id,transferId:o.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};try{await((e,t,n,r,a,o,i,s,c,l,d)=>Wa("setDBRoomMessageData",e,t,n,r,a,o,i,s,c,l,d))(r.id,M,S,d.peerId,p,p,u,h,n,k.getTime(),o.transferId)}catch(e){throw await ro(M),e}return t.dispatch(ct({roomId:r.id,transferId:o.transferId,merkleRootHex:M,sha512Hex:S,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:m,totalChunks:m,messageType:u,filename:h,channelLabel:n,timestamp:k.getTime()})),{merkleRoot:R,merkleRootHex:M,hash:I,hashHex:S,totalSize:p,totalChunks:m,messageType:u,chunkHashes:P}},pu=async(e,t=3e3,n=25,r)=>{const a=Date.now();for(;"connecting"===e.readyState&&Date.now()-a<t&&!r?.aborted;)await new Promise(e=>setTimeout(e,n));return!r?.aborted&&"open"===e.readyState},mu=(e,t)=>`${e}\0${t}`,yu=async e=>{let t=e.inFlight(),n=Date.now();for(;e.isOpen()&&e.inFlight()>=e.windowSize;){Cd(e.signal);const r=e.inFlight();if(r<t&&(t=r,n=Date.now()),Date.now()-n>=e.stallTimeoutMs)return;await new Promise(t=>setTimeout(t,e.pollMs)),Cd(e.signal)}Cd(e.signal)},gu=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f)=>{Cd(u);const{merkleRootHex:p}=await mo(e.label);if(p!==ca(i))throw new Error("Outbound channel label does not match its Merkle root");const m=f?.()??0;let y=0;const g=function(e){const t=e.slice();for(let e=t.length-1;e>0;e--){const n=iu(0,e+1);[t[e],t[n]]=[t[n],t[e]]}return t}(Array.from({length:a},(e,t)=>t));for(let w=0;w<a;w++){Cd(u);const a=g[w],b=await eo(s,a);if(Cd(u),!b)throw new Error(`Missing staged outbound chunk ${String(a)}`);const v=new Uint8Array(b.metadata),k=Po(v);if(k.chunkIndex!==a||b.chunkIndex!==a)throw new Error("Outbound chunk index does not match its staging key");const I=k.chunkEndIndex>k.chunkStartIndex&&k.chunkEndIndex-k.chunkStartIndex<=k.totalSize;if(void 0!==h&&(!I||h.has(k.chunkIndex)))continue;I&&f&&await yu({windowSize:32,stallTimeoutMs:1e4,pollMs:25,isOpen:()=>"open"===e.readyState,inFlight:()=>y-Math.max(0,f()-m),signal:u});const S=new Uint8Array(te);if(0===b.merkleProof.byteLength){const e=await du(o,la(b.leafHash),d,te);Cd(u),S.set(e)}else S.set(new Uint8Array(b.merkleProof));const C=b.receiptToken.length===2*N?b.receiptToken:ca(await _o(i,k.chunkIndex,la(b.leafHash)));if(Cd(u),0!==b.merkleProof.byteLength&&b.merkleRoot===p&&b.receiptToken===C||await ao({transferId:s,hash:c,merkleRoot:p,leafHash:b.leafHash,receiptToken:C,chunkIndex:a,data:b.data,metadata:b.metadata,merkleProof:S.buffer}),ae!==v.length+S.length+new Uint8Array(b.data).length)throw new Error("Outbound staged chunk has invalid cell length");const A=await ia([v,S,new Uint8Array(b.data)]);for(Cd(u);"open"===e.readyState&&e.bufferedAmount>=Z;)await new Promise(e=>setTimeout(e,25)),Cd(u);if("open"!==e.readyState){St("Cannot send message because channel is "+e.readyState+" and bufferedAmount is "+String(e.bufferedAmount));break}let E;try{E=Ii(t,n,A,i,l,r??void 0)}catch(e){throw new Error("Could not seal outbound message chunk",{cause:e})}Cd(u);try{e.send(E.buffer),I&&y++}catch(t){if("open"!==e.readyState)break;throw t}}},wu=async(e,t,n,r,a,o,i,s)=>{const c=Date.now()+i;for(;Date.now()<c;){Cd(s);const i=a.find(e=>e.roomId===t&&e.withPeerId===n&&"connected"===e.connectionState);if(i)try{await io(mu(t,r),n);const a=await Ld({channel:r,epc:i,roomId:t,dataChannels:o},e);if(await pu(a,c-Date.now(),void 0,s))return{epc:i,channel:a};try{bu(a)}catch(e){console.error(e)}Cd(s)}catch(e){console.error(e)}else await new Promise(e=>setTimeout(e,500)),Cd(s)}return null},bu=e=>{e.releaseProtocolResources?.(),"closed"!==e.readyState&&e.close()},vu=async(e,t)=>{if(!e.pqHealingState)return;const n=Date.now()+6e4;for(;Tl(e);){if(Cd(t),Date.now()>n)throw new Error("v4 send: sparse-PQ healing did not settle before the send timeout");await new Promise(e=>setTimeout(e,25))}},ku=async(e,t,n,r,a=Xi,o=Oi,i)=>{if(Cd(i),e.epc===t)return e;if(await Ad(a(n,t.withPeerId),i),!t.ratchetState)throw new Error("v3 send: replacement connection has no ratchet state");const s=await o(t,n,r);return i?.aborted&&(s.messageKey.fill(0),s.pqContext?.rootKey.fill(0),Cd(i)),e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),{epc:t,messageKey:s.messageKey,header:s.header,pqContext:s.pqContext}},Iu=(e,t,n,r)=>"connected"===e.connectionState&&t.some(t=>t===e&&t.roomId===n&&t.withPeerId===r);class Su extends AggregateError{result;constructor(e,t){super(e.outcomes.filter(e=>"failed"===e.status).map(e=>e.reason),t),this.name="MessageDeliveryError",this.result=e}}const Cu=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f,p)=>{Cd(p),So(n,l,s),await io(mu(n,e.label),l),Cd(p);try{await Ad(Xi(n,l),p)}catch(e){throw new Error("v3 send: ratchet gate rejected",{cause:e})}if(!r.ratchetState)throw new Error("v3 send: no ratchet state for peer");let m,y,g;await vu(r,p);try{const e=await Oi(r,n,d);p?.aborted&&(e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),Cd(p)),m=e.messageKey,y=e.header,g=e.pqContext}catch(e){throw new Error("v3 send: durable ratchet advance failed",{cause:e})}let w=e,b=r;const v=async()=>{const r=e.label;if(!await pu(w,void 0,void 0,p))throw new Error("Message DataChannel did not open before send timeout");Cd(p),await gu(w,m,y,g,a,o,i,s,c,d,u,p,void 0,()=>vo(n,l,s));let v=0,k=0,I=!1;for(;v<5;){const e=await Co(n,l,s,2e3*(v+1),p);if(Cd(p),e){I=!0;break}if("closed"===w.readyState||"closing"===w.readyState){if(Iu(b,h,n,l))throw new Error("Message transfer cancelled by peer");if(k>=3)break;k++;const e=await wu(t,n,l,r,h,f,3e4,p);if(!e)break;const a=await ku({epc:b,messageKey:m,header:y},e.epc,n,d,Xi,Oi,p);b=a.epc,m=a.messageKey,y=a.header,g=a.pqContext??null,w=e.channel,v=0,t.dispatch(dt({roomId:n,sha512Hex:c,retransmit:!0}));continue}await gu(w,m,y,g,a,o,i,s,c,d,u,p,bo(n,l,s),()=>vo(n,l,s)),v++,t.dispatch(dt({roomId:n,sha512Hex:c,retransmit:!0}))}if(!I)throw new Error("Message transfer ended without receiver confirmation")};try{await(async(e,t)=>{try{return await t()}finally{bu(e())}})(()=>w,v)}finally{m.fill(0),g?.rootKey.fill(0),So(n,l,s)}},Au=(e,t,n,r,a,o,i,s,c,l)=>async d=>{const u=await eo(e,d);if(!u)return null;const h=new Uint8Array(u.metadata),f=Po(h),p=new Uint8Array(te);0===u.merkleProof.byteLength?p.set(await du(n,la(u.leafHash),l,te)):p.set(new Uint8Array(u.merkleProof));const m=u.receiptToken.length===2*N?u.receiptToken:ca(await _o(r,f.chunkIndex,la(u.leafHash)));0!==u.merkleProof.byteLength&&u.merkleRoot===a&&u.receiptToken===m||await ao({transferId:e,hash:t,merkleRoot:a,leafHash:u.leafHash,receiptToken:m,chunkIndex:d,data:u.data,metadata:u.metadata,merkleProof:p.buffer});const y=await ia([h,p,new Uint8Array(u.data)]);return Ii(o,i,y,r,c,s??void 0)},Eu=12e4,Pu=async(e,t,n,r,a,o,i,s,c,l=1,d=ne,u=.9,h=1)=>{const f=((e,t)=>{const n=[...md.get(e)??[]].find(e=>e.transferId===t);return n?{transferId:t,signal:n.controller.signal,bindHash(e){n.hashHex=e},bindMerkleRoot(e){n.merkleRootHex=e},finish(){n.finished||(n.finished=!0,yd(e,n))}}:vd(e,t)})(r,c);let p="",m=!1,y=!1;try{Cd(f.signal);const{rooms:c}=t.getState(),g=c.findIndex(e=>e.id===r);if(-1===g)throw new Error("No room with id "+r);if(g>-1){const w=c[g].channels.findIndex(e=>e.label===n);if(-1===w)throw new Error("No channel with label "+n);const{merkleRoot:b,merkleRootHex:v,hashHex:k,totalChunks:I,chunkHashes:S}=await fu(e,t,n,c[g],s,f,l,d,u,h);if(f.bindMerkleRoot(v),p=v,Cd(f.signal),0===b.length||0===k.length||0===I||0===S.length)return;m=!0;const C=await po(n,v),A=c[g].channels[w].peerIds.map(e=>({peerId:e,epc:a.find(t=>t.roomId===r&&t.withPeerId===e)})),E="scheduled"===c[g].policy.coverMode?await(async(e,t,n,r,a,o,i,s,c,l,d,u,h)=>{const f=[];let p=0;for(const m of n){if(u?.aborted){f.push({peerId:m.peerId,status:"skipped",reason:"cancelled"});continue}const n=m.epc;if(n&&"connected"===n.connectionState&&n.coverRuntime)try{if(await Ad(Xi(e,m.peerId),u),!n.ratchetState)throw new Error("v4 scheduled send: no ratchet state");await vu(n,u);const y=await Oi(n,e,l),g=await po(t,i),w=Au(s,c,a,o,i,y.messageKey,y.header,y.pqContext,l,d);if(!pd({epc:n,channelMessageLabel:g,totalChunks:r,sealSlotCell:w,getAckedChunks:()=>bo(e,m.peerId,s)}))throw new Error("v4 scheduled send: edge has no cover runtime");fd(n,e,m.peerId,i,s),p+=1,h?.();const b=await Co(e,m.peerId,s,Eu,u);y.messageKey.fill(0),y.pqContext?.rootKey.fill(0),f.push(b?{peerId:m.peerId,status:"delivered"}:{peerId:m.peerId,status:"failed",phase:"transfer",reason:new Error("scheduled delivery not confirmed")})}catch(e){f.push({peerId:m.peerId,status:"failed",phase:"transfer",reason:e})}else f.push({peerId:m.peerId,status:"skipped",reason:"not-connected"})}return{outcomes:f,startedTransfers:p}})(r,n,A,I,S,b,v,f.transferId,k,i,s,f.signal,()=>{y=!0}):await(async(e,t,n,r,a)=>{const o=[];let i=0;for(const s of e){if(r?.aborted){o.push({peerId:s.peerId,status:"skipped",reason:"cancelled"});continue}if(!s.epc||"connected"!==s.epc.connectionState){o.push({peerId:s.peerId,status:"skipped",reason:"not-connected"});continue}if(s.epc.withPeerPublicKey.length!==2*L){o.push({peerId:s.peerId,status:"skipped",reason:"unauthenticated"});continue}const e=s;let c;try{c=await t(e)}catch(e){o.push({peerId:s.peerId,status:"failed",phase:"setup",reason:e});continue}if(r?.aborted)bu(c),o.push({peerId:s.peerId,status:"skipped",reason:"cancelled"});else{i++,a?.();try{const t=n(e,c);o.push(Promise.resolve(t).then(()=>({peerId:s.peerId,status:"delivered"}),e=>({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})))}catch(e){bu(c),o.push({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})}}}return{outcomes:await Promise.all(o),startedTransfers:i}})(A,({epc:e})=>Ld({channel:C,epc:e,roomId:r,dataChannels:o},t),({peerId:e,epc:n},c)=>Cu(c,t,r,n,I,S,b,f.transferId,k,e,i,s,a,o,f.signal),f.signal,()=>{y=!0}),P={transferId:f.transferId,merkleRootHex:v,...E};Cd(f.signal);const x=P.outcomes.filter(e=>"delivered"===e.status).length;if(0===P.startedTransfers)throw new Su(P,"No authenticated connected peers accepted the send");if(0===x)throw new Su(P,"Message was not delivered to any peer");return P}return}catch(e){if(((e,t,n)=>n||!e&&!t)(m,y,f.signal.aborted)&&(p.length>0&&await ro(p),t.dispatch(ft({roomId:r,transferId:f.transferId}))),f.signal.aborted)throw f.signal.reason instanceof Error?f.signal.reason:new Error("Message transfer cancelled");throw console.trace(e),e}finally{await oo({transferId:f.transferId}),f.finish()}},xu=async({alsoDeleteDB:e,peerConnections:t,dataChannels:n},r)=>{for(let e=n.length-1;e>=0;e--){const t=n[e];t.releaseProtocolResources?.(),t.onopen=null,t.onclose=null,t.onerror=null,t.onclosing=null,t.onmessage=null,t.onbufferedamountlow=null,"closed"!==t.readyState&&t.close(),n.splice(e,1)}const a=[...new Set(t.map(e=>e.withPeerId))];for(const e of a)await r.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:e}));return e&&await Wa("deleteDB"),{data:void 0}},Ku=async({roomId:e,deleteMessages:t,peerConnections:n,dataChannels:r},a)=>{for(let t=r.length-1;t>=0;t--){const n=r[t];n.roomIds.includes(e)&&(n.releaseProtocolResources?.(),n.onopen=null,n.onclose=null,n.onerror=null,n.onclosing=null,n.onmessage=null,n.onbufferedamountlow=null,"closed"!==n.readyState&&n.close(),r.splice(t,1))}const o=n.filter(t=>t.roomId===e).map(e=>e.withPeerId);for(const t of o)await a.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:e})),a.dispatch(ut({peerId:t,roomId:e}));if(t){if((await Ja()).findIndex(t=>t.roomId===e)>-1){await(e=>Wa("deleteDBUniqueRoom",e))(e);const t=await Za(e),n=t.length;for(let r=0;r<n;r++)a.dispatch(ft({roomId:e,merkleRootHex:t[r].merkleRoot}))}}return{data:void 0}},Ru=async(e,t=5e3,n=25)=>{if("open"!==e.readyState){try{e.close()}catch{}return}const r=Date.now();for(;"open"===e.readyState&&e.bufferedAmount>0&&Date.now()-r<t;)await new Promise(e=>setTimeout(e,n));try{"open"===e.readyState&&e.close()}catch{}},Mu=[],_u=[],Uu=[],Du=na({reducerPath:"webrtcApi",baseQuery:async({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:a,dataChannels:o},i)=>Yd(n,e).runExclusive(async()=>{const{keyPair:s}=i.getState();if(e===s.peerId)throw new Error("Cannot create a connection with oneself.");const c=Fa(s.publicKey,t);if(await Ga(e))return{data:void 0};const l=Vd(a,n,e);if(l>-1){const e=a[l];if("closed"!==e.connectionState&&"failed"!==e.connectionState)return!c||e.mainChannel&&"closing"!==e.mainChannel.readyState&&"closed"!==e.mainChannel.readyState||await tu(e,o,i),{data:void 0};hd(e),(e=>{e.ontrack=null,e.ondatachannel=null,e.onicecandidate=null,e.onicecandidateerror=null,e.onnegotiationneeded=null,e.onsignalingstatechange=null,e.onconnectionstatechange=null,e.onicegatheringstatechange=null,e.oniceconnectionstatechange=null})(e),"closed"!==e.connectionState&&e.close(),a.splice(l,1)}const d=await eu({peerId:e,peerPublicKey:t,roomId:n,peerConnections:a,rtcConfig:r},i);return((e,t,n)=>{e.ondatachannel=async r=>{try{const a=await Ld({channel:r.channel,epc:e,roomId:e.roomId,dataChannels:t,incoming:!0},n);"main"===a.label&&(e.mainChannel=a)}catch(e){console.error("Rejected incoming DataChannel:",e)}}})(d,o,i),a.includes(d)||a.push(d),c&&await tu(d,o,i),{data:void 0}}),endpoints:e=>({connectWithPeer:e.mutation({query:({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceCandidatePoolSize:2}})=>({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:Mu,dataChannels:Uu})}),setDescription:e.mutation({queryFn:(e,t,n)=>ru({...e,peerConnections:Mu,iceCandidates:_u,dataChannels:Uu},t)}),setCandidate:e.mutation({queryFn:(e,t,n)=>(async({peerId:e,roomId:t,candidate:n,peerConnections:r,iceCandidates:a},o)=>Yd(t,e).runExclusive(async()=>{const{keyPair:i}=o.getState(),s=(e=>{if("function"==typeof e.toJSON)return e.toJSON();const t=e;return{candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,usernameFragment:t.usernameFragment}})(n),c=Vd(r,t,e);if(c>-1){const e=r[c];if(e.ignoreOffer)return{data:void 0};if(e.remoteDescription&&"stable"===e.signalingState){if(jd(s,e.remoteDescription))try{await e.addIceCandidate(s)}catch{const t=e.makingOffer||"stable"!==e.signalingState;!(i.peerId<e.withPeerId)&&t||await Hd(e,async()=>{e.iceCandidates.length=0,await o.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:e.withPeerId,roomId:e.roomId}))})}}else((e,t)=>{for(;e.length>=64;)e.shift();e.push(t)})(e.iceCandidates,s)}else((e,t,n,r)=>{let a=0;for(let r=e.length-1;r>=0;r--)if(e[r].roomId===t&&e[r].withPeerId===n&&(a+=1,a>=64)){e.splice(r,1);break}for(;e.length>=1024;)e.shift();e.push({...r,roomId:t,withPeerId:n})})(a,t,e,s);return{data:void 0}}))({...e,peerConnections:Mu,iceCandidates:_u},t)}),openChannel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,channel:t,withPeers:n,peerConnections:r,dataChannels:a},o)=>{const{keyPair:i}=o.getState(),s=async e=>{if("string"!=typeof t){const n=await Ld({channel:t,epc:e,roomId:e.roomId,dataChannels:a},o);return void("main"===n.label&&(e.mainChannel=n))}if(a.find(n=>n.withPeerId===e.withPeerId&&n.roomIds.includes(e.roomId)&&n.label===t&&"closing"!==n.readyState&&"closed"!==n.readyState))return;if("main"===t&&!Fa(i.publicKey,e.withPeerPublicKey))return;const n=e.createDataChannel(t,{ordered:"main"===t,protocol:"raw"}),r=await Ld({channel:n,epc:e,roomId:e.roomId,dataChannels:a},o);"main"===r.label&&(e.mainChannel=r)};if(n&&n.length>0){const t=n.length;for(let a=0;a<t;a++){if(i.peerId===n[a].peerId)continue;const t=$d(r,e,n[a].peerId);t&&await s(t)}}else{const t=r.filter(t=>t.roomId===e),n=t.length;for(let e=0;e<n;e++){const n=t[e];await s(n)}}return{data:void 0}})({...e,peerConnections:Mu,dataChannels:Uu},t)}),sendMessage:e.mutation({queryFn:(e,t,n)=>(async({data:e,transferId:t,label:n,roomId:r,peerConnections:a,dataChannels:o,minChunks:i,chunkSize:s,percentageFilledChunk:c,metadataSchemaVersion:l},d)=>{const u=i??1,h=s??ne,f=c??.9,p="string"==typeof e?(new TextEncoder).encode(e).length:e.size,m=hu(p,u,h,f),y=await Ua(ya()),g=await Ua(wa(m));try{return{data:await async function(){return await Pu(e,d,n,r,a,o,y,g,t,u,h,f,l)}()}}catch(e){if(e instanceof Su)return{error:e};throw e}})({...e,peerConnections:Mu,dataChannels:Uu},t)}),disconnect:e.mutation({queryFn:(e,t,n)=>xu({...e,peerConnections:Mu,dataChannels:Uu},t)}),disconnectFromRoom:e.mutation({queryFn:(e,t,n)=>Ku({...e,peerConnections:Mu,dataChannels:Uu},t)}),disconnectFromAllRooms:e.mutation({queryFn:(e,t,n)=>(async({deleteMessages:e,exceptionRoomIds:t,peerConnections:n,dataChannels:r},a)=>{const o=new Set(t??[]);for(let e=r.length-1;e>=0;e--){const t=r[e];t.roomIds.some(e=>o.has(e))||(t.releaseProtocolResources?.(),t.onopen=null,t.onclose=null,t.onerror=null,t.onclosing=null,t.onmessage=null,t.onbufferedamountlow=null,"closed"!==t.readyState&&t.close(),r.splice(e,1))}const i=n.filter(e=>!o.has(e.roomId)).map(e=>({roomId:e.roomId,peerId:e.withPeerId}));for(const e of i)await a.dispatch(Du.endpoints.disconnectFromPeer.initiate(e)),a.dispatch(ut(e));if(e){const{rooms:e}=a.getState(),n=e.length;for(let r=0;r<n;r++){if(t?.includes(e[r].id))continue;const n=e[r].messages.length;for(let t=0;t<n;t++)a.dispatch(ft({roomId:e[r].id,merkleRootHex:e[r].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:Mu,dataChannels:Uu},t)}),disconnectFromPeer:e.mutation({queryFn:(e,t,n)=>(({peerId:e,roomId:t,alsoDeleteData:n,peerConnections:r,dataChannels:a,iceCandidates:o},i)=>{const s=new Set;for(let n=r.length-1;n>=0;n--){const a=r[n];if(a.withPeerId!==e||void 0!==t&&a.roomId!==t)continue;s.add(a.roomId);const o=new Error(`Room/peer transport closed (${a.roomId}, ${a.withPeerId})`);if(xl(a.roomId,a.withPeerId,o),Yi(a.roomId,a.withPeerId,o),a.ratchetState&&(ti(a.ratchetState),a.ratchetState=void 0),hd(a),os(a),Ol(a),a.pqHealingState&&(a.pqHealingState.destroy(),a.pqHealingState=void 0),a.serializeEdgeCryptoState=void 0,a.messageKeyCache){for(const e of a.messageKeyCache.values())e.fill(0);a.messageKeyCache.clear(),a.messageKeyCache=void 0}a.messageKeyByMerkleRoot?.clear(),a.messageKeyByMerkleRoot=void 0,a.messageChannels?.clear(),a.messageChannels=void 0,a.mainChannel=void 0,a.ontrack=null,a.ondatachannel=null,a.onicecandidate=null,a.onicecandidateerror=null,a.onnegotiationneeded=null,a.onsignalingstatechange=null,a.onconnectionstatechange=null,a.onicegatheringstatechange=null,a.oniceconnectionstatechange=null,"closed"!==a.connectionState&&a.close(),r.splice(n,1)}void 0!==t&&s.add(t);for(const t of s)nu(o,t,e),Zd(t,e);i.dispatch(ut({peerId:e,roomId:t})),i.dispatch(ht({peerId:e,roomId:t}));for(let n=a.length-1;n>=0;n--){const r=a[n];r.withPeerId!==e||void 0!==t&&!r.roomIds.includes(t)||(r.releaseProtocolResources?.(),r.onopen=null,r.onclose=null,r.onerror=null,r.onclosing=null,r.onmessage=null,r.onbufferedamountlow=null,"closed"!==r.readyState&&r.close(),a.splice(n,1))}if(n){const{rooms:n}=i.getState(),r=n.length;for(let a=0;a<r;a++){if(void 0!==t&&n[a].id!==t)continue;const r=n[a].messages.length;for(let t=0;t<r;t++)n[a].messages[t].fromPeerId===e&&i.dispatch(ft({roomId:n[a].id,merkleRootHex:n[a].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:Mu,dataChannels:Uu,iceCandidates:_u},t)}),disconnectFromChannelLabel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,label:t,messageHash:n,alsoDeleteData:r,alsoSendFinishedMessage:a,dataChannels:o},i)=>{const s=o.length;if(0===s)return{data:void 0};for(let c=0;c<s;c++){if(o[c]?.label!==t||!o[c].roomIds.includes(e)||"open"!==o[c].readyState)continue;const s=o[c];if(r&&s.cancelReceiveTransfer?await s.cancelReceiveTransfer():s.releaseProtocolResources?.(),n&&a&&n.length===N&&es(o[c],n),await Ru(o[c]),r){const{merkleRootHex:n}=await mo(t);i.dispatch(ft({roomId:e,merkleRootHex:n}))}}return{data:void 0}})({...e,dataChannels:Uu},t)}),disconnectFromPeerChannelLabel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,peerId:t,label:n,messageHash:r,alsoDeleteData:a,alsoSendFinishedMessage:o,channel:i,peerConnections:s,dataChannels:c},l)=>{const{rooms:d,signalingServer:u}=l.getState(),h=c.findIndex(r=>i?r===i:r.label===n&&r.withPeerId===t&&r.roomIds.includes(e));h>-1&&c[h]&&(a&&c[h].cancelReceiveTransfer?await c[h].cancelReceiveTransfer():c[h].releaseProtocolResources?.(),r&&o&&r.length===N&&es(c[h],r),c[h].onopen=null,c[h].onclose=null,c[h].onerror=null,c[h].onclosing=null,c[h].onmessage=null,c[h].onbufferedamountlow=null,"open"===c[h].readyState&&await Ru(c[h]),c.splice(h,1),await io(mu(e,n),t));const{merkleRootHex:f}=await mo(n);f.length>0?a&&l.dispatch(ft({roomId:e,merkleRootHex:f})):u.isConnected&&!a||l.dispatch(ht({roomId:e,peerId:t,label:n}));const p=d.find(t=>t.id===e);if(!p?.channels.some(e=>e.peerIds.includes(t))){const n=Vd(s,e,t);n>-1&&await l.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:s[n].withPeerId,roomId:e}))}return{data:void 0}})({...e,peerConnections:Mu,dataChannels:Uu},t)})})}),Tu=e=>"number"==typeof e&&Number.isInteger(e)&&4===e,Nu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),qu=(e,t)=>{const n=Object.keys(e);return n.length===t.length&&n.every(e=>t.includes(e))},Ou=new Map,Bu=async(n,r,a)=>{try{if("PING"===n.data)return void r.send("PONG");const c=String(n.data);if(c.length>524288)return void console.error("Rejecting oversized signaling message");const l=JSON.parse(c);switch(l.type){case"ping":{const{keyPair:e}=a.getState();await a.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"pong",fromPeerId:e.peerId}}));break}case"peerId":{if(!(Nu(s=l)&&qu(s,["type","peerId","challenge","protocolVersion","message"])&&"peerId"===s.type&&"string"==typeof s.peerId&&e(s.peerId)&&"string"==typeof s.challenge&&/^[0-9a-f]{64}$/.test(s.challenge)&&"number"==typeof s.protocolVersion&&Tu(s.protocolVersion)&&"string"==typeof s.message)){console.error("Rejecting malformed or incompatible auth challenge"),r.close(1002,"protocol-v4 auth required");break}const{keyPair:t}=a.getState();await(async(e,t,n,r)=>{const a=la(e.secretKey),o=n.match(/.{1,2}/g);if(!o)throw new Error("Invalid challenge format");const i=Uint8Array.from(o.map(e=>parseInt(e,16))),s=await Na(i,a),c=[...new Uint8Array(s)].map(e=>e.toString(16).padStart(2,"0")).join("");r.dispatch(M({peerId:t,challenge:n,signature:c}))})(t,l.peerId,l.challenge,a);break}case"roomId":{if(!Tu(l.protocolVersion)||!e(l.roomId)||!/^[0-9a-f]{64}$/.test(l.roomUrl)){console.error("Rejecting incompatible or malformed room response");break}let t;l.turnCredentials&&(t={...We,iceServers:[...We.iceServers??[],{urls:l.turnCredentials.urls,username:l.turnCredentials.username,credential:l.turnCredentials.credential}]}),a.dispatch(Je({id:l.roomId,url:l.roomUrl,rtcConfig:t}));break}case"challenge":if(!(t=>{if(!Nu(t))return!1;const n=Object.hasOwn(t,"username");return n===Object.hasOwn(t,"credential")&&qu(t,n?["type","challengeId","protocolVersion","username","credential"]:["type","challengeId","protocolVersion"])&&"challenge"===t.type&&"string"==typeof t.challengeId&&e(t.challengeId)&&"number"==typeof t.protocolVersion&&Tu(t.protocolVersion)&&(!n||"string"==typeof t.username&&t.username.length>0&&"string"==typeof t.credential&&t.credential.length>0)})(l)){console.error("Rejecting malformed or incompatible auth success"),r.close(1002,"protocol-v4 auth required");break}a.dispatch(_(l));break;case"peerConnection":{if(!Tu(l.protocolVersion)||!e(l.peer.id)||!Ba(l.peer.publicKey))break;if(await Ga(l.peer.id,l.peer.publicKey))break;const{keyPair:t,rooms:n}=a.getState(),r=n.findIndex(e=>e.id===l.roomId);if(r>-1&&n[r].onlyConnectWithKnownAddresses){if(!await Xa(l.peer.id,l.peer.publicKey))break}await a.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"peerConnection",roomId:l.roomId,fromPeerId:t.peerId,toPeerId:l.peer.id,protocolVersion:4}}));break}case"peers":{if(!Tu(l.protocolVersion)||!e(l.roomId)||!Array.isArray(l.peers)){console.error("Rejecting incompatible or malformed peer roster");break}St("[handleWebSocketMessage] Received peers response:",{roomId:l.roomId,peersCount:l.peers.length,peers:l.peers});const{keyPair:t,rooms:n}=a.getState(),r=n.findIndex(e=>e.id===l.roomId);if(r>-1){const o=((t,n,r)=>{const a=t.map(e=>({...e})),o=new Map(a.map(e=>[e.peerId,e])),i=new Map(a.map(e=>[e.peerPublicKey,e]));for(const t of n){if(!e(t.id)||!Ba(t.publicKey)||t.id===r.peerId||t.publicKey===r.publicKey)continue;if(o.has(t.id))continue;if(i.get(t.publicKey))continue;const n={peerId:t.id,peerPublicKey:t.publicKey};a.push(n),o.set(n.peerId,n),i.set(n.peerPublicKey,n)}return a})(n[r].peers,l.peers,t);for(const e of o)a.dispatch(rt({roomId:l.roomId,...e}));const i=l.peers.length;if(0===i){const{signalingServer:n}=a.getState(),r=Date.now(),o=Ou.get(l.roomId)??0;n.isConnected&&n.isVerified&&e(t.peerId)&&r-o>5e3&&(Ou.set(l.roomId,r),await a.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:t.peerId,roomId:l.roomId,protocolVersion:4}})));break}const s=n[r].onlyConnectWithKnownAddresses;for(let c=0;c<i;c++){if(l.peers[c].publicKey===t.publicKey||l.peers[c].id===t.peerId||!e(l.peers[c].id)||!Ba(l.peers[c].publicKey))continue;if(!o.some(e=>e.peerId===l.peers[c].id&&e.peerPublicKey===l.peers[c].publicKey))continue;if(!await Ga(l.peers[c].id,l.peers[c].publicKey)){if(s){if(!await Xa(l.peers[c].id,l.peers[c].publicKey))continue}await a.dispatch(Du.endpoints.connectWithPeer.initiate({roomId:l.roomId,peerId:l.peers[c].id,peerPublicKey:l.peers[c].publicKey,rtcConfig:n[r].rtcConfig}))}}}break}case"description":if(!(Tu(l.protocolVersion)&&e(l.fromPeerId)&&Ba(l.fromPeerPublicKey)&&e(l.roomId)&&(i=l.description,("offer"===i.type||"answer"===i.type||"pranswer"===i.type||"rollback"===i.type)&&"string"==typeof i.sdp&&i.sdp.length<=262144))){Tu(l.protocolVersion)||console.error(`Rejecting SDP from ${l.fromPeerId}: incompatible protocol version ${String(l.protocolVersion)} (expected v4). No fallback.`);break}if(!await Ga(l.fromPeerId,l.fromPeerPublicKey)){const{rooms:e}=a.getState(),t=e.findIndex(e=>e.id===l.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses){if(!await Xa(l.fromPeerId,l.fromPeerPublicKey))break}await a.dispatch(Du.endpoints.setDescription.initiate({peerId:l.fromPeerId,peerPublicKey:l.fromPeerPublicKey,roomId:l.roomId,description:l.description,rtcConfig:e[t].rtcConfig}))}break;case"candidate":if(!(Tu(l.protocolVersion)&&e(l.fromPeerId)&&e(l.roomId)&&(e=>{const t=e;return"string"==typeof t.candidate&&t.candidate.length<=4096&&(null==t.sdpMid||"string"==typeof t.sdpMid&&t.sdpMid.length<=256)&&(null==t.usernameFragment||"string"==typeof t.usernameFragment&&t.usernameFragment.length<=256)})(l.candidate))){console.error(`Rejecting ICE from ${l.fromPeerId}: incompatible protocol version ${String(l.protocolVersion)} (expected v4). No fallback.`);break}if(!await Ga(l.fromPeerId)){const{rooms:e}=a.getState(),t=e.findIndex(e=>e.id===l.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses){if(!await Xa(l.fromPeerId))break}await a.dispatch(Du.endpoints.setCandidate.initiate({peerId:l.fromPeerId,roomId:l.roomId,candidate:l.candidate}))}break;case"connection":{const{keyPair:n,rooms:r}=a.getState(),i=r.findIndex(e=>e.id===l.roomId);if(Tu(l.protocolVersion)&&e(n.peerId)&&t(n.challenge)&&t(n.signature)&&128===n.signature.length&&64===n.challenge.length&&e(l.fromPeerId)&&Ba(l.fromPeerPublicKey)&&l.fromPeerId!==n.peerId&&l.fromPeerPublicKey!==n.publicKey&&e(l.roomId)&&i>-1&&(o=l.labels,Array.isArray(o)&&o.length<=64&&o.every(e=>"string"==typeof e&&e.length>0&&e.length<=193))){if(await Ga(l.fromPeerId,l.fromPeerPublicKey))break;if(r[i].onlyConnectWithKnownAddresses){if(!await Xa(l.fromPeerId,l.fromPeerPublicKey))break}await(async(e,t,n)=>{n.recordPeer({roomId:e.roomId,peerId:e.fromPeerId,peerPublicKey:e.fromPeerPublicKey});for(const t of e.labels)n.recordChannel({roomId:e.roomId,peerId:e.fromPeerId,label:t});await n.ensureConnection({roomId:e.roomId,peerId:e.fromPeerId,peerPublicKey:e.fromPeerPublicKey,rtcConfig:t})})(l,r[i].rtcConfig,{recordPeer:e=>{a.dispatch(rt(e))},recordChannel:e=>{a.dispatch(it(e)),St(`Connected with ${n.peerId} on websocket channel ${e.label}`)},ensureConnection:async e=>{await a.dispatch(Du.endpoints.connectWithPeer.initiate(e))}})}else Tu(l.protocolVersion)||console.error(`Rejecting peer ${l.fromPeerId}: incompatible protocol version ${String(l.protocolVersion)} (expected v4). No fallback.`);break}case"error":console.error(l);break;default:console.error("Unknown message type "+JSON.stringify(l))}}catch(e){return void console.error("[p2party] WebSocket message handling error:",e)}var o,i,s},Lu=(e,t,n=10,r=20)=>{let a=0;const o=setInterval(()=>{e.readyState===WebSocket.OPEN?(clearInterval(o),t()):(a+=1,St(`Waiting for connection... Attempt ${String(a)}`),a>=n&&(clearInterval(o),St("WebSocket failed to connect after multiple attempts, closing..."),e.removeEventListener("message",()=>{}),e.removeEventListener("open",()=>{}),e.removeEventListener("close",()=>{}),e.close()))},r)};let Fu=null;const zu=(e,t)=>(Fu&&(Fu.removeEventListener("message",()=>{}),Fu.removeEventListener("open",()=>{}),Fu.removeEventListener("close",()=>{}),Fu.close(),Fu=null,St("WebSocket manually disconnected")),t.dispatch(bt.disconnect()),{data:void 0}),ju=(n,r)=>{if(Fu?.readyState===WebSocket.OPEN){const{keyPair:a}=r.getState();return e(a.peerId)&&t(a.challenge)&&t(a.signature)&&128===a.signature.length&&64===a.challenge.length&&Lu(Fu,()=>{Fu?.send(JSON.stringify(n.content))}),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},Hu=({peerId:n,peerPublicKey:r,roomId:a},o)=>{if(Fu?.readyState===WebSocket.OPEN){const{keyPair:i}=o.getState();return e(i.peerId)&&t(i.challenge)&&t(i.signature)&&128===i.signature.length&&64===i.challenge.length&&Ba(r)&&(o.dispatch(rt({roomId:a,peerId:n,peerPublicKey:r})),o.dispatch(it({roomId:a,label:"main",peerId:n})),St(`Connected with ${i.peerId} on channel main`),Lu(Fu,()=>{Fu?.send(JSON.stringify({type:"connection",roomId:a,fromPeerId:i.peerId,toPeerId:n,labels:["main"],protocolVersion:4}))})),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},Vu=na({reducerPath:"signalingServerApi",baseQuery:async({signalingServerUrl:e},t)=>{const{keyPair:n,signalingServer:r}=t.getState();if(Fu||r.isConnected||r.isEstablishingConnection)return St("WebSocket already connected"),{data:void 0};t.dispatch(bt.startConnecting(e));try{const r=e=>{const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t};let o=n.publicKey,i=n.secretKey;const s=await Wa("getIdentityEd25519"),c=s?ca(new Uint8Array(s.pub)):"",l=s?new Uint8Array(s.secret):void 0,d=l?ca(l):"";l?.fill(0);const u=/^[0-9a-f]{128}$/;if(Ba(o)&&u.test(i)){if(!s||c!==o||d!==i){const e=la(i);await ho({pub:r(la(o)),secret:r(e)}),e.fill(0)}}else{if(s)o=c,i=d;else{const e=localStorage.getItem("publicKey")??"",t=localStorage.getItem("secretKey")??"";if(Ba(e)&&u.test(t)){o=e,i=t;const n=la(i);await ho({pub:r(la(o)),secret:r(n)}),n.fill(0)}else{const e=await Ta();o=ca(e.publicKey),i=ca(e.secretKey),await ho({pub:r(e.publicKey),secret:r(e.secretKey)}),e.secretKey.fill(0)}}t.dispatch(K({publicKey:o,secretKey:i}))}La(o,"Self Ed25519 identity"),localStorage.removeItem("secretKey");const h=i.length>0?i:n.secretKey,f=o.length>0?o:n.publicKey;if(h.length>0&&f.length>0){const e=await lo();if(!(null!=e&&await il(new Uint8Array(e.pub),new Uint8Array(e.crossSig),la(f)))){const e=await Do(),t=await ol(e.publicKey,la(h));await(a={pub:r(e.publicKey),secret:r(e.secretKey),crossSig:r(t)},Wa("setIdentityX25519",a))}}const p=e+"?publickey="+o;return Fu=new WebSocket(p),Fu.binaryType="arraybuffer",await new Promise((e,n)=>{if(!Fu)return void n(new Error("WebSocket is null"));const r=Fu;try{r.onopen=()=>{St("WebSocket connected to:",p),t.dispatch(bt.connectionEstablished()),e({data:void 0})},r.onerror=e=>{console.error("WebSocket error:",e),Fu&&(Fu.removeEventListener("message",()=>{}),Fu.removeEventListener("open",()=>{}),Fu.removeEventListener("close",()=>{}),Fu.close(),Fu=null),t.dispatch(bt.disconnect()),n(new Error("WebSocket connection failed"))},r.onmessage=async e=>{await Bu(e,r,t)},r.onclose=()=>{Fu&&(Fu.removeEventListener("message",()=>{}),Fu.removeEventListener("open",()=>{}),Fu.removeEventListener("close",()=>{}),Fu.close(),Fu=null),t.dispatch(bt.disconnect()),St("WebSocket disconnected"),e({data:void 0})}}catch(e){n(e instanceof Error?e:new Error(String(e)))}return()=>{Fu&&(St("Cleaning up WebSocket connection..."),Fu.removeEventListener("message",()=>{}),Fu.removeEventListener("open",()=>{}),Fu.removeEventListener("close",()=>{}),Fu.close(),Fu=null)}})}catch(e){return Fu&&(Fu.removeEventListener("message",()=>{}),Fu.removeEventListener("open",()=>{}),Fu.removeEventListener("close",()=>{}),Fu.close(),Fu=null),t.dispatch(bt.disconnect()),console.error("Error during WebSocket setup:",e),{error:"WebSocket connection failed"}}var a},endpoints:e=>({connectWebSocket:e.mutation({query:e=>({signalingServerUrl:e})}),disconnectWebSocket:e.mutation({queryFn:zu}),sendMessage:e.mutation({queryFn:ju}),connectWithPeer:e.mutation({queryFn:Hu})})}),$u=new Map,Qu=k();Qu.startListening({matcher:l(Ze,Je,ct,ft,pt),effect:async(t,n)=>{try{if(Ze.match(t)){const{roomId:r,connectingToPeers:a}=t.payload;if(St("[roomListenerMiddleware] setConnectingToPeers:",{roomId:r,connectingToPeers:a}),a){const{signalingServer:t,keyPair:a,rooms:o}=n.getState(),i=o.findIndex(e=>e.id===r);if(St("[roomListenerMiddleware] setConnectingToPeers check:",{isConnected:t.isConnected,peerId:a.peerId,isPeerIdUUID:e(a.peerId),roomIndex:i,roomId:i>-1?o[i].id:"N/A"}),t.isConnected&&t.isVerified&&e(a.peerId)&&i>-1&&e(o[i].id)){const e=Date.now();e-($u.get(r)??0)<2e3?St("[roomListenerMiddleware] Skipping peers request - debounced"):($u.set(r,e),St("[roomListenerMiddleware] Sending peers request from setConnectingToPeers"),await n.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:a.peerId,roomId:r,protocolVersion:4}})))}n.dispatch(Ze({roomId:r,connectingToPeers:!1}))}}else if(Je.match(t)){const{signalingServer:i,keyPair:s,rooms:c}=n.getState(),{url:l,id:d,onlyConnectWithKnownPeers:u}=t.payload;if(St("[roomListenerMiddleware] setRoom:",{url:l,id:d,onlyConnectWithKnownPeers:u}),64===l.length&&null!=u&&localStorage.setItem(l+"-onlyConnectWithKnownPeers",String(u)),64===l.length&&e(d)){St("[roomListenerMiddleware] setRoom processed:",{url:l,id:d,isConnected:i.isConnected,peerId:s.peerId,roomsLen:c.length});const t=c.findIndex(e=>e.id===d);if(-1===t)return;const u=ze(c[t].policy).slice().buffer;await(r=l,a=d,o=u,Wa("setDBUniqueRoom",r,a,o));const h=await Za(d),f=h.length;for(let e=0;e<f;e++)n.dispatch(ct({roomId:h[e].roomId,transferId:h[e].transferId,merkleRootHex:h[e].merkleRoot,sha512Hex:h[e].hash,fromPeerId:h[e].fromPeerId,filename:h[e].filename,messageType:h[e].messageType,chunkSize:h[e].savedSize,totalSize:h[e].totalSize,channelLabel:h[e].channelLabel,timestamp:h[e].timestamp}));St("[roomListenerMiddleware] Checking peers request conditions:",{isConnected:i.isConnected,isPeerIdUUID:e(s.peerId),peerId:s.peerId,roomIndex:t,roomId:t>-1?c[t].id:"N/A"}),i.isConnected&&i.isVerified&&e(s.peerId)&&t>-1&&e(c[t].id)&&(St("[roomListenerMiddleware] Sending peers request for room:",c[t].id),await n.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:s.peerId,roomId:c[t].id,protocolVersion:4}})))}}else if(ct.match(t)){const{roomId:e,merkleRootHex:r,sha512Hex:a,chunkSize:o,totalSize:i}=t.payload,{rooms:s,keyPair:c}=n.getOriginalState(),l=s.findIndex(t=>t.id===e);if(l>-1){const t=s[l].messages.findLastIndex(e=>e.merkleRootHex===r&&e.fromPeerId!==c.peerId&&e.savedSize+o===i);if(t>-1){const r=await po(s[l].messages[t].channelLabel,s[l].messages[t].merkleRootHex),o=la(a);await n.dispatch(Du.endpoints.disconnectFromChannelLabel.initiate({roomId:e,label:r,messageHash:o,alsoDeleteData:!1,alsoSendFinishedMessage:!0}))}}}else if(ft.match(t)){const{merkleRootHex:e,hashHex:n}=t.payload;if(!e&&!n)return;if(e&&e.length!==2*N)return;if(n&&n.length!==2*N)return;e?(await ro(e),await oo({merkleRootHex:e})):n&&await oo({hashHex:n})}else if(pt.match(t)){const e=t.payload;await n.dispatch(Du.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:!0}))}}catch(e){console.error("p2party: room listener effect failed",e)}var r,a,o}});const Wu=k();Wu.startListening({matcher:l(K,R,M,_,U),effect:async(n,r)=>{if(K.match(n)){const{publicKey:e,secretKey:t}=n.payload;64===e.length&&128===t.length&&(localStorage.setItem("publicKey",n.payload.publicKey),localStorage.removeItem("secretKey"))}else if(R.match(n)){const{peerId:a,challenge:o,signature:i,challengeId:s,username:c,credential:l}=n.payload;if(e(a)&&e(s)&&t(o)&&t(i)&&64===o.length&&128===i.length){r.dispatch(bt.connectionVerified()),localStorage.setItem("peerId",a),localStorage.setItem("challenge",o),localStorage.setItem("signature",i),localStorage.setItem("challengeId",s);const{keyPair:t,rooms:d,commonState:u}=r.getState(),h=64===u.currentRoomUrl.length?d.findIndex(e=>e.url===u.currentRoomUrl):-1;h>-1?(n.payload.username&&n.payload.credential&&r.dispatch(st({roomId:d[h].id,iceServers:[{urls:["turn:turn.p2party.com:3478?transport=udp","turn:turn.p2party.com:3478?transport=tcp","turns:turn.p2party.com:443?transport=tcp"],username:c,credential:l}]})),e(d[h].id)&&r.dispatch(Ze({roomId:d[h].id,connectingToPeers:!0}))):e(t.peerId)&&64===u.currentRoomUrl.length&&await r.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:t.peerId,roomUrl:u.currentRoomUrl,protocolVersion:4}}))}}else if(M.match(n)){const{peerId:a,challenge:o,signature:i}=n.payload;e(a)&&t(o)&&t(i)&&64===o.length&&128===i.length&&(localStorage.setItem("peerId",a),localStorage.setItem("challenge",o),localStorage.setItem("signature",i),await r.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"challenge",fromPeerId:a,challenge:o,signature:i,protocolVersion:4}})))}else if(_.match(n)){const{challengeId:t}=n.payload;if(e(t)){r.dispatch(bt.connectionVerified()),localStorage.setItem("challengeId",t);const{keyPair:a,rooms:o,commonState:i}=r.getState(),s=64===i.currentRoomUrl.length?o.findIndex(e=>e.url===i.currentRoomUrl):-1;s>-1?(n.payload.username&&n.payload.credential&&r.dispatch(st({roomId:o[s].id,iceServers:[{urls:["turn:turn.p2party.com:3478?transport=udp","turn:turn.p2party.com:3478?transport=tcp","turns:turn.p2party.com:443?transport=tcp"],username:n.payload.username,credential:n.payload.credential}]})),e(o[s].id)?r.dispatch(Ze({roomId:o[s].id,connectingToPeers:!0})):e(a.peerId)&&64===i.currentRoomUrl.length&&await r.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:a.peerId,roomUrl:i.currentRoomUrl,protocolVersion:4}}))):e(a.peerId)&&64===i.currentRoomUrl.length&&await r.dispatch(Vu.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:a.peerId,roomUrl:i.currentRoomUrl,protocolVersion:4}}))}}else U.match(n)&&(console.trace("[keyPairListenerMiddleware] resetIdentity dispatched"),localStorage.setItem("peerId",""),localStorage.setItem("challengeId",""),localStorage.setItem("publicKey",""),localStorage.removeItem("secretKey"),localStorage.setItem("challenge",""),localStorage.setItem("signature",""))}});const Xu=I({reducer:{commonState:E,keyPair:D,rooms:yt,signalingServer:vt,[Vu.reducerPath]:Vu.reducer,[Du.reducerPath]:Du.reducer},middleware:e=>e({serializableCheck:{ignoredPaths:[`${Du.reducerPath}.mutations`,`${Du.reducerPath}.queries`,`${Vu.reducerPath}.mutations`,`${Vu.reducerPath}.queries`],ignoredActionPaths:["payload","error","meta.arg.originalArgs","meta.baseQueryMeta"]}}).concat([Vu.middleware,Du.middleware,Qu.middleware,Wu.middleware])}),Gu=Xu.dispatch,Ju=new Uint8Array([80,50,80,83,69,83,83,0]),Yu=262144,Zu=Ju.length+4+24+32+32+32+2,eh="p2party-session",th=e=>Uint8Array.from(e);function nh(e,t,n){if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(void 0!==n&&e.length!==n)throw new RangeError(`${t} must be ${String(n)} bytes`)}const rh=(e,t)=>{if(!Number.isSafeInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new RangeError(`${t} must be a non-negative safe integer`)},ah=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n},oh=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),ih=async e=>new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",e.slice().buffer)),sh=async e=>{const t=new WebAssembly.Memory({initial:32,maximum:32});return e?.wasmBinary?await Ca({wasmBinary:(n=e.wasmBinary,n instanceof Uint8Array?n.slice().buffer:n.slice(0)),wasmMemory:t,getRandomValue:Ea}):await Ua(t);var n},ch=async(e={})=>{const t=await sh(e);let n=null,r=null,a=null;try{if(e.ed25519KeyPair)nh(e.ed25519KeyPair.publicKey,"ed25519KeyPair.publicKey",L),nh(e.ed25519KeyPair.secretKey,"ed25519KeyPair.secretKey",F),n=th(e.ed25519KeyPair.publicKey),r=th(e.ed25519KeyPair.secretKey);else{const e=await Ta(t);n=e.publicKey,r=e.secretKey}const o=await Do(t);a=o.secretKey;const i=await ol(o.publicKey,r,t);if(!await il(o.publicKey,i,n,t))throw new Error("ed25519KeyPair public and secret keys do not match");const s={ed25519PublicKey:n,ed25519SecretKey:r,x25519PublicKey:o.publicKey,x25519SecretKey:a,x25519CrossSignature:i};return n=null,r=null,a=null,s}finally{n?.fill(0),r?.fill(0),a?.fill(0)}},lh=(e,t)=>e.N===t.N&&e.PN===t.PN&&ah(e.dhPub,t.dhPub);class dh{protocolVersion=4;#e;#ge=new Qd;#we;#be;#ve;#p=!1;constructor(e,t,n,r){this.#be=e,this.#e=t,this.#ve=n,this.#we=r}get pqMode(){return Ie(this.#be.rootSuite)}get canEncrypt(){return!this.#p&&null!==this.#be.sendingChainKey&&!this.#ve.trafficBlocked}get pqEpoch(){return this.#j(),this.#ve.epoch}get healingInProgress(){return!this.#p&&this.#ve.trafficBlocked}#j(){if(this.#p)throw new Error("session: session is destroyed")}async encrypt(e){nh(e,"plaintext");const t=th(e);return this.#ge.runExclusive(async()=>{let e=null,n=null,r=null,a=null,o=!1;try{if(this.#j(),this.#ve.trafficBlocked)throw new Error("session: sparse-PQ healing is in progress");if(!this.#be.sendingChainKey)throw new Error("ratchet: no sending chain");e=await(async(e,t)=>{const n=e.length,r=Math.max(1,Math.ceil(n/ne)),a=[],o=[];try{for(let t=0;t<r;t++){const r=t*ne,o=Math.min(ne,Math.max(0,n-r)),i=globalThis.crypto.getRandomValues(new Uint8Array(ne));i.set(e.subarray(r,r+o),0),a.push(i)}const i=await ih(e),s=new Uint8Array(r*N);for(let e=0;e<a.length;e++)s.set(su(a[e],t),e*N);const c=Uint8Array.from(await lu(s,t));for(let e=0;e<a.length;e++){const r=await du(s,su(a[e],t),t,te),c=Math.min(ne,Math.max(0,n-e*ne)),l=Eo({schemaVersion:1,messageType:xo.Unknown,hash:i,totalSize:n,date:new Date(0),name:eh,chunkStartIndex:0,chunkEndIndex:c,chunkIndex:e}),d=new Uint8Array(ae);d.set(l,0),d.set(r,ee),d.set(a[e],ee+te),o.push(d)}return i.fill(0),s.fill(0),{root:c,chunks:a,plaintexts:o}}catch(e){for(const e of a)e.fill(0);for(const e of o)e.fill(0);throw e}})(t,this.#e),n=ei(this.#be);const i=$o(n,this.#e);r=i.messageKey,a=this.#ve.currentMessageContext();const s=e.plaintexts.map(t=>Ii(r,i.header,t,e.root,this.#e,a));return ni(this.#be,n),this.#ve.noteApplicationMessage(),o=!0,{protocolVersion:4,root:th(e.root),frames:s}}finally{t.fill(0),r?.fill(0),n&&!o&&ti(n),e&&(e=>{for(const t of e.chunks)t.fill(0);for(const t of e.plaintexts)t.fill(0)})(e)}})}async decrypt(e){if(!e||"object"!=typeof e)throw new TypeError("message is required");if(4!==e.protocolVersion)throw new Error("session: unsupported protocol version");if(nh(e.root,"message.root",N),!Array.isArray(e.frames)||0===e.frames.length)throw new Error("session: encrypted message has no frames");for(const t of e.frames)if(nh(t,"message frame"),t.length!==de)throw new Error("session: invalid encrypted frame length");const t=th(e.root),n=e.frames.map(th);return this.#ge.runExclusive(async()=>{this.#j();const e=n.map(e=>si(e));for(let t=1;t<e.length;t++)if(!lh(e[0].header,e[t].header))throw new Error("session: mixed ratchet headers");const r=new Set;for(const t of e){const e=oh(t.nonce);if(r.has(e))throw new Error("session: duplicate chunk nonce");r.add(e)}const a=ei(this.#be),o=new Map(this.#ve.activeReceiveKeys),i=[];let s=!1;try{const e=[];for(const r of n){const n=Si(a,r,o,t,this.#e,e=>this.#ve.resolveMessageContext(e));if(!n.ok||!n.decrypted)throw new Error("session: encrypted frame authentication failed");i.push(n.decrypted);const s=Po(n.decrypted.subarray(0,ee));e.push({metadata:s,chunk:n.decrypted.subarray(ee+te)})}const r=await(async e=>{if(0===e.length)throw new Error("session: encrypted message has no frames");const t=e[0].metadata;rh(t.totalSize,"metadata.totalSize");const n=Math.max(1,Math.ceil(t.totalSize/ne));if(e.length!==n)throw new Error("session: incomplete or excessive frame set");const r=new Map;for(const a of e){const e=a.metadata;if(rh(e.chunkIndex,"metadata.chunkIndex"),rh(e.chunkStartIndex,"metadata.chunkStartIndex"),rh(e.chunkEndIndex,"metadata.chunkEndIndex"),rh(e.totalSize,"metadata.totalSize"),1!==e.schemaVersion||e.messageType!==xo.Unknown||e.name!==eh||0!==e.date.getTime())throw new Error("session: unsupported encrypted metadata");if(e.totalSize!==t.totalSize||!ah(e.hash,t.hash))throw new Error("session: inconsistent encrypted metadata");if(e.chunkIndex>=n||0!==e.chunkStartIndex)throw new Error("session: invalid encrypted chunk range");const o=Math.min(ne,Math.max(0,t.totalSize-e.chunkIndex*ne));if(e.chunkEndIndex!==o)throw new Error("session: invalid encrypted chunk length");if(r.has(e.chunkIndex))throw new Error("session: duplicate encrypted chunk");r.set(e.chunkIndex,a)}const a=new Uint8Array(t.totalSize);for(let e=0;e<n;e++){const t=r.get(e);if(!t)throw new Error("session: missing encrypted chunk");const n=t.metadata.chunkEndIndex;a.set(t.chunk.subarray(0,n),e*ne)}const o=await ih(a),i=ah(o,t.hash);if(o.fill(0),!i)throw a.fill(0),new Error("session: plaintext hash mismatch");return a})(e);return ni(this.#be,a),this.#ke(o),this.#ve.noteApplicationMessage(),s=!0,r}finally{t.fill(0);for(const e of i)e.fill(0);if(!s){for(const[e,t]of o)this.#ve.activeReceiveKeys.has(e)||t.fill(0);ti(a)}}})}#ke(e){const t=this.#ve.activeReceiveKeys;for(const[n,r]of e)t.has(n)||t.set(n,r)}async prepareHealing(){return this.#ge.runExclusive(async()=>{if(this.#j(),!this.#ve.healingDue())return uh;const e=await this.#ve.prepareHealingOffer();return this.#ve.markPendingDispatched(),{frame:e,requiresPersistBeforeSend:!0}})}async acceptControlFrame(e){nh(e,"control frame",de);const t=th(e);return this.#ge.runExclusive(async()=>{this.#j();const e=await this.#ve.acceptControlFrame(t);return e.changed&&e.dispatch&&null!==this.#ve.pendingRetryAt&&this.#ve.markPendingDispatched(),{frame:e.dispatch,requiresPersistBeforeSend:e.changed}})}async pendingControl(){return this.#ge.runExclusive(async()=>(this.#j(),this.#ve.copyPendingFrame()))}async serialize(){return this.#ge.runExclusive(async()=>(this.#j(),fh(this.#be,this.#ve,this.#we)))}async destroy(){await this.#ge.runExclusive(async()=>{this.#p||(ti(this.#be),this.#ve.destroy(),this.#p=!0)})}}const uh={frame:null,requiresPersistBeforeSend:!1},hh=(e,t,n)=>(rh(n,"snapshot counter"),e.setBigUint64(t,BigInt(n),!1),t+8),fh=(e,t,n)=>{(e=>{if(nh(e.rootKey,"snapshot.rootKey",32),nh(e.dhSelfPub,"snapshot.dhSelfPub",32),nh(e.dhSelfSec,"snapshot.dhSelfSec",32),e.sendingChainKey&&nh(e.sendingChainKey,"snapshot.sendingChainKey",32),e.receivingChainKey&&nh(e.receivingChainKey,"snapshot.receivingChainKey",32),e.dhRemotePub&&nh(e.dhRemotePub,"snapshot.dhRemotePub",32),rh(e.Ns,"snapshot.Ns"),rh(e.Nr,"snapshot.Nr"),rh(e.PN,"snapshot.PN"),(e.sendingChainKey||e.receivingChainKey||e.skipped.size>0)&&!e.dhRemotePub)throw new Error("snapshot: chain state requires a remote DH key");if(e.skipped.size>ge)throw new Error("snapshot: too many skipped message keys")})(e);const r=Yo(e),a=t.serialize();if(0===a.length||a.length>Yu)throw a.fill(0),new Error("snapshot: PQ checkpoint length is invalid");try{const e=(r.sendingChainKey?1:0)|(r.receivingChainKey?2:0)|(r.dhRemotePub?4:0)|(n?8:0),t=Number(Boolean(r.sendingChainKey))+Number(Boolean(r.receivingChainKey))+Number(Boolean(r.dhRemotePub)),o=new Uint8Array(Zu+32*t+72*r.skippedMessageKeys.length+4+a.length),i=new DataView(o.buffer);let s=0;o.set(Ju,s),s+=Ju.length,o[s++]=4,o[s++]=4,o[s++]=e,o[s++]=(e=>{if(e===fe)return 3;if(e===he)return 4;if(e===pe)return 5;throw new Error("snapshot: unsupported root suite")})(r.rootSuite),s=hh(i,s,r.Ns),s=hh(i,s,r.Nr),s=hh(i,s,r.PN),o.set(new Uint8Array(r.rootKey),s),s+=32,r.sendingChainKey&&(o.set(new Uint8Array(r.sendingChainKey),s),s+=32),r.receivingChainKey&&(o.set(new Uint8Array(r.receivingChainKey),s),s+=32),o.set(new Uint8Array(r.dhSelfPub),s),s+=32,o.set(new Uint8Array(r.dhSelfSec),s),s+=32,r.dhRemotePub&&(o.set(new Uint8Array(r.dhRemotePub),s),s+=32),i.setUint16(s,r.skippedMessageKeys.length,!1),s+=2;for(const e of r.skippedMessageKeys)nh(new Uint8Array(e.dhPub),"snapshot.skipped.dhPub",32),nh(new Uint8Array(e.messageKey),"snapshot.skipped.messageKey",32),o.set(new Uint8Array(e.dhPub),s),s+=32,s=hh(i,s,e.n),o.set(new Uint8Array(e.messageKey),s),s+=32;return i.setUint32(s,a.length,!1),s+=4,o.set(a,s),s+=a.length,o}finally{a.fill(0),new Uint8Array(r.rootKey).fill(0),r.sendingChainKey&&new Uint8Array(r.sendingChainKey).fill(0),r.receivingChainKey&&new Uint8Array(r.receivingChainKey).fill(0),new Uint8Array(r.dhSelfSec).fill(0);for(const e of r.skippedMessageKeys)new Uint8Array(e.messageKey).fill(0)}},ph=e=>{nh(e,"snapshot");const t=th(e);let n=0,r=!1;const a=[],o=e=>{if(!Number.isSafeInteger(e)||e<0||n+e>t.length)throw new Error("snapshot: truncated input");const r=t.subarray(n,n+e);return n+=e,r},i=(e,t=!1)=>{const n=o(e).slice().buffer;return t&&a.push(new Uint8Array(n)),n},s=()=>{if(n+8>t.length)throw new Error("snapshot: truncated counter");const e=new DataView(t.buffer,t.byteOffset+n,8).getBigUint64(0,!1);if(n+=8,e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("snapshot: counter exceeds safe-integer range");return Number(e)};try{if(!ah(o(Ju.length),Ju))throw new Error("snapshot: invalid magic");if(4!==o(1)[0])throw new Error("snapshot: unsupported snapshot version");if(4!==o(1)[0])throw new Error("snapshot: unsupported protocol version");const e=o(1)[0];if(-16&e)throw new Error("snapshot: unknown flags");const c=(e=>{if(3===e)return fe;if(4===e)return he;if(5===e)return pe;throw new Error("snapshot: unsupported root suite")})(o(1)[0]),l=s(),d=s(),u=s(),h=i(32,!0),f=1&e?i(32,!0):null,p=2&e?i(32,!0):null,m=i(32),y=i(32,!0),g=4&e?i(32):null;if((f||p)&&null===g)throw new Error("snapshot: chain state requires a remote DH key");if(n+2>t.length)throw new Error("snapshot: missing skipped-key count");const w=new DataView(t.buffer,t.byteOffset+n,2).getUint16(0,!1);if(n+=2,w>ge)throw new Error("snapshot: too many skipped message keys");if(null===g&&w>0)throw new Error("snapshot: skipped keys require a remote DH key");const b=72*w;if(t.length-n<b+4)throw new Error("snapshot: truncated input");const v=[],k=new Set;for(let e=0;e<w;e++){const e=o(32),t=s(),n=o(32),r=`${oh(e)}:${String(t)}`;if(k.has(r))throw new Error("snapshot: duplicate skipped message key");k.add(r),v.push({dhPub:e.slice().buffer,n:t,messageKey:(()=>{const e=n.slice().buffer;return a.push(new Uint8Array(e)),e})()})}const I=new DataView(t.buffer,t.byteOffset+n,4).getUint32(0,!1);if(n+=4,0===I||I>Yu)throw new Error("snapshot: PQ checkpoint length is invalid");if(t.length-n!==I)throw new Error("snapshot: truncated input or trailing bytes");const S=o(I).slice();a.push(S);const C=Zo({rootSuite:c,rootKey:h,sendingChainKey:f,receivingChainKey:p,dhSelfPub:m,dhSelfSec:y,dhRemotePub:g,Ns:l,Nr:d,PN:u,skippedMessageKeys:v});return r=!0,{state:C,pqCheckpoint:S,amInitiator:!!(8&e)}}finally{if(t.fill(0),!r)for(const e of a)e.fill(0)}},mh=async e=>{if(!e||"object"!=typeof e)throw new TypeError("session options are required");if("initiator"!==e.role&&"responder"!==e.role)throw new Error("role must be initiator or responder");if(!e.transport||"function"!=typeof e.transport.send||"function"!=typeof e.transport.recv)throw new TypeError("transport must provide send() and recv()");if((e=>{if(!e||"object"!=typeof e)throw new TypeError("identity is required");nh(e.ed25519PublicKey,"identity.ed25519PublicKey",L),nh(e.x25519PublicKey,"identity.x25519PublicKey",X),nh(e.x25519SecretKey,"identity.x25519SecretKey",G),nh(e.x25519CrossSignature,"identity.x25519CrossSignature",O)})(e.identity),nh(e.peerIdentityEd25519PublicKey,"peerIdentityEd25519PublicKey",L),!e.channel||"object"!=typeof e.channel)throw new TypeError("channel binding is required");if(nh(e.channel.channelId,"channel.channelId"),0===e.channel.channelId.length)throw new RangeError("channel.channelId must not be empty");nh(e.channel.localFingerprint,"channel.localFingerprint",32),nh(e.channel.remoteFingerprint,"channel.remoteFingerprint",32);const t=e;if("pin"!==t.mode&&"nopin"!==t.mode)throw new Error("mode must be pin or nopin");const n=t.mode,r=t.pqMode??"hybrid-mlkem768";if("hybrid-mlkem512"!==r&&"hybrid-mlkem768"!==r&&"hybrid-mlkem1024"!==r)throw new Error("pqMode must select ML-KEM-512, ML-KEM-768, or ML-KEM-1024");let a=null;if("pin"===n){if(nh(t.pin,"pin"),0===t.pin.length)throw new RangeError("pin must not be empty");a=th(t.pin)}else if(void 0!==t.pin)throw new Error("pin must not be provided in nopin mode");const o=th(e.identity.x25519SecretKey),i=th(e.identity.ed25519PublicKey),s=th(e.identity.x25519PublicKey),c=th(e.identity.x25519CrossSignature),l=th(e.peerIdentityEd25519PublicKey),d=th(e.channel.channelId),u=th(e.channel.localFingerprint),h=th(e.channel.remoteFingerprint);let f=null,p=null,m=null,y=null,g=null;try{const t=await sh(e.crypto);await(async(e,t)=>{const n=new Uint8Array(X);n[0]=9;const r=To(e.x25519SecretKey,n,t);try{if(!ah(r,e.x25519PublicKey))throw new Error("identity X25519 public and secret keys do not match")}finally{r.fill(0)}if(!await il(e.x25519PublicKey,e.x25519CrossSignature,e.ed25519PublicKey,t))throw new Error("identity X25519 cross-signature is invalid")})({ed25519PublicKey:i,x25519PublicKey:s,x25519SecretKey:o,x25519CrossSignature:c},t);const w="initiator"===e.role,b=sl({channelId:d,ikInitiator:w?i:l,ikResponder:w?l:i,fpInitiator:w?u:h,fpResponder:w?h:u,pqMode:r}),v=await Il(e.transport,{mode:n,pqMode:r,pin:a,channelInput:b,amInitiator:w,idSelfSec:o,selfIdentityX25519Pub:s,selfIdentityCrossSignature:c,peerIdentityEd25519Pub:l},t);y=v.state,f=v.secret,p=v.pqHealing.rootKey,m=v.pqHealing.binding,g=new $c({module:t,pqMode:r,rootSuite:y.rootSuite,binding:m,rootKey:p,nextOfferer:v.pqHealing.nextOfferer,amInitiator:w});const k=new dh(y,t,g,w);return y=null,g=null,k}finally{o.fill(0),a?.fill(0),f?.fill(0),p?.fill(0),m?.fill(0),y&&ti(y),g?.destroy()}},yh=async(e,t)=>{const n=ph(e);let r=null;try{const e=await sh(t),a=$c.readCheckpointBinding(n.pqCheckpoint);try{r=$c.restore(n.pqCheckpoint,{module:e,pqMode:Ie(n.state.rootSuite),rootSuite:n.state.rootSuite,binding:a,amInitiator:n.amInitiator})}finally{a.fill(0)}const o=new dh(n.state,e,r,n.amInitiator);return r=null,o}catch(e){throw ti(n.state),r?.destroy(),e}finally{n.pqCheckpoint.fill(0)}};var gh=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];const wh=e=>e.normalize("NFKD"),bh=async e=>{try{return await(async e=>{const t=wh(e).split(" ");if(t.length%3!=0)throw new Error("Number of words in mnemonic must be multiple of three.");const n=t.map(e=>{const t=gh.indexOf(e);if(-1===t)throw new Error("Could not find word in wordlist.");return t.toString(2).padStart(11,"0")}).join(""),r=32*Math.floor(n.length/33),a=n.slice(0,r),o=n.slice(r),i=a.match(/(.{1,8})/g).map(e=>parseInt(e,2));if(i.length<16)throw new Error("Entropy length too small (less than 128 bits).");if(i.length>64)throw new Error("Entropy length too large (more than 512 bits).");const s=i.length/4,c=Uint8Array.from(i),l=await window.crypto.subtle.digest("SHA-512",c);if(new Uint8Array(l).reduce((e,t)=>e+t.toString(2).padStart(8,"0"),"").slice(0,s)!==o)throw new Error("Invalid checksum.");return!0})(e)}catch{return!1}},vh=32,kh=`v${String(1)}.`,Ih="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Sh=/^[0-9a-fA-F]{64}$/u,Ch=/^[A-Za-z0-9_-]{43}$/u,Ah=(new TextEncoder).encode("p2party/room-invite/checksum/v1\0");if(2048!==gh.length||2048!==new Set(gh).size)throw new Error("Room invite word list must contain 2,048 unique words");const Eh=new Map(gh.map((e,t)=>[e,t])),Ph=e=>{if(!(e instanceof Uint8Array))throw new TypeError("Room capability must be a Uint8Array");if(e.length!==vh)throw new Error("Room capability must be exactly 32 bytes");return e},xh=()=>globalThis.crypto.getRandomValues(new Uint8Array(vh)),Kh=e=>{const t=Ph(e);let n="";for(let e=0;e<t.length;e+=3){const r=t.length-e,a=t[e]<<16|(r>1?t[e+1]:0)<<8|(r>2?t[e+2]:0);n+=Ih[a>>>18&63],n+=Ih[a>>>12&63],r>1&&(n+=Ih[a>>>6&63]),r>2&&(n+=Ih[63&a])}return n},Rh=e=>{if("string"!=typeof e||!Ch.test(e))throw new Error("Room capability must be exactly 43 unpadded base64url characters");if(3&Ih.indexOf(e.at(-1)??""))throw new Error("Room capability base64url encoding is not canonical");const t=new Uint8Array(vh);let n=0,r=0,a=0;for(const o of e)for(n=n<<6|Ih.indexOf(o),r+=6;r>=8;)r-=8,t[a]=n>>>r&255,a+=1,n&=(1<<r)-1;if(a!==vh||Kh(t)!==e)throw new Error("Room capability base64url encoding is not canonical");return t},Mh=e=>{if("string"!=typeof e)throw new TypeError("Room capability must be a string");return e.startsWith(kh)||e.startsWith(`#${kh}`)?Dh(e):64===e.length?(e=>{if(!Sh.test(e))throw new Error("Room capability hex must contain exactly 64 hex digits");const t=new Uint8Array(vh);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(2*n,2*n+2),16);return t})(e):Rh(e)},_h=e=>(e=>{let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t})(Mh(e)),Uh=e=>`${kh}${Kh(e)}`,Dh=e=>{if("string"!=typeof e)throw new TypeError("Room invite fragment must be a string");const t=e.startsWith("#")?e.slice(1):e;if(!t.startsWith(kh))throw new Error("Unsupported room invite version");return Rh(t.slice(kh.length))},Th=async e=>{const t=await globalThis.crypto.subtle.digest("SHA-256",((e,t)=>{const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n})(Ah,e));return new Uint8Array(t)[0]},Nh=async(t,n="wss://signaling.p2party.com/ws",r={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},a={})=>{if(t=_h(t),null===a||"object"!=typeof a||Array.isArray(a))throw new Error("Invalid room connection options");const{keyPair:o,signalingServer:i,rooms:s,commonState:c}=Xu.getState(),l=s.findIndex(e=>e.url===t);let d;if(-1===l){const e=(await Ja()).find(e=>e.roomUrl===t);e?.roomPolicy&&(d=je(new Uint8Array(e.roomPolicy)))}if(d&&a.policy&&!Ve(d,a.policy))throw new Error("Persisted room policy is immutable");const u=He(a.policy??(l>-1?s[l].policy:d??Qe));if("legacy-signaling"!==u.rendezvousMode)throw new Error("Private rendezvous room connections are not wired yet");if("pin"===u.authMode){if(void 0!==a.pin){h=t,f=a.pin,xd.put(h,f);const e=l>-1?s[l].id:"";e&&await Nd(e)}else if(!(e=>xd.has(e))(t))throw new Error("PIN room connection requires a PIN")}else{if(void 0!==a.pin)throw new Error("PIN must not be provided for a no-PIN room");Kd(t)}var h,f;Gu(-1===l?Je({url:t,id:"",rtcConfig:r,policy:u}):Ye({roomContext:t,policy:u})),c.currentRoomUrl!==t&&Gu(A(t)),i.isConnected&&i.isVerified&&e(o.peerId)?-1===l?await Gu(Vu.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:o.peerId,roomUrl:t,protocolVersion:4}})):Gu(Ze({roomId:s[l].id,connectingToPeers:!0})):await Gu(Vu.endpoints.connectWebSocket.initiate(n))},qh=3e4,Oh=async(e,t={})=>{const n=_h(e),{timeoutMs:r=qh,signal:a}=t,o=()=>{const e=mt(Xu.getState()).find(e=>e.url===n);return e?.id?e:void 0},i=o();if(i)return i;if(a?.aborted)throw new Error("Waiting for the room was aborted before it started");return await new Promise((e,t)=>{let n=!1,i=()=>{};const s=setTimeout(()=>{l(()=>{t(new Error(`The signaling service did not assign a room id within ${String(r)}ms. The socket may be connected but not yet verified, or the room may be unreachable.`))})},r),c=()=>{l(()=>{t(new Error("Waiting for the room was aborted"))})};function l(e){n||(n=!0,clearTimeout(s),a?.removeEventListener("abort",c),i(),e())}const d=()=>{const t=o();t&&l(()=>{e(t)})};a?.addEventListener("abort",c,{once:!0}),i=Xu.subscribe(d),d()})},Bh=async(e,t,n,r={})=>{const{timeoutMs:a,signal:o,...i}=r;return await Nh(e,t,n,i),await Oh(e,{timeoutMs:a,signal:o})},Lh=async(e,t={})=>{const{count:n=1,timeoutMs:r=qh,signal:a}=t,o=()=>{const t=mt(Xu.getState()).find(t=>t.id===e);if(!t)return;const r=t.handshakeStatusByPeer,a=r?t.peers.filter(e=>"authenticated"===r[e.peerId]?.status):t.peers;return a.length>=n?a:void 0},i=o();if(i)return i;if(a?.aborted)throw new Error("Waiting for peers was aborted before it started");return await new Promise((e,t)=>{let i=!1,s=()=>{};const c=setTimeout(()=>{d(()=>{t(new Error(`Only ${String(o()?.length??0)} of ${String(n)} peer(s) authenticated within ${String(r)}ms`))})},r),l=()=>{d(()=>{t(new Error("Waiting for peers was aborted"))})};function d(e){i||(i=!0,clearTimeout(c),a?.removeEventListener("abort",l),s(),e())}const u=()=>{const t=o();t&&d(()=>{e(t)})};a?.addEventListener("abort",l,{once:!0}),s=Xu.subscribe(u),u()})},Fh=(e,t)=>{const n=new Set,r=()=>{const r=mt(Xu.getState()).find(t=>t.id===e);if(r)for(const a of r.messages){const r=a.merkleRootHex;r&&!n.has(r)&&(a.totalSize>0&&a.savedSize>=a.totalSize&&(n.add(r),zh(r,a.sha512Hex).then(n=>{try{t({roomId:e,fromPeerId:a.fromPeerId,merkleRootHex:r,filename:n.filename,size:n.size,message:n.message})}catch(e){console.error("p2party: onMessage handler threw",e)}}).catch(e=>{n.delete(r),console.error("p2party: could not read message",r,e)})))}},a=Xu.subscribe(r);return r(),a},zh=async(e,t,n=!0)=>{if(!e&&!t)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"txt",category:Ko.Text};try{const{keyPair:r,rooms:a}=Xu.getState(),o=a.length;let i=-1,s=-1;for(let n=0;n<o;n++)if(s=a[n].messages.findLastIndex(n=>n.merkleRootHex===e||r.peerId===n.fromPeerId&&n.sha512Hex===t&&""===n.merkleRootHex),s>-1){i=n;break}if(-1===i||-1===s)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"",category:Ko.Text};const c=a[i].messages[s].messageType,l=Ro(c),d=(e=>{switch(e){case xo.ImagePNG:return"png";case xo.ImageJPEG:return"jpeg";case xo.ImageJPG:return"jpg";case xo.ImageGIF:return"gif";case xo.ImageBMP:return"bmp";case xo.ImageTIFF:return"tiff";case xo.ImageSVG:return"svg";case xo.ImageWEBP:return"webp";case xo.ImageHEIC:return"heic";case xo.DocumentPDF:return"pdf";case xo.DocumentDOC:return"doc";case xo.DocumentDOCX:return"docx";case xo.DocumentXLS:return"xls";case xo.DocumentXLSX:return"xlsx";case xo.DocumentPPT:return"ppt";case xo.DocumentPPTX:return"pptx";case xo.DocumentTXT:return"txt";case xo.DocumentRTF:return"rtf";case xo.DocumentODT:return"odt";case xo.AudioMP3:return"mp3";case xo.AudioWAV:return"wav";case xo.AudioAAC:return"aac";case xo.AudioFLAC:return"flac";case xo.AudioOGG:return"ogg";case xo.AudioM4A:return"m4a";case xo.VideoMP4:return"mp4";case xo.VideoAVI:return"avi";case xo.VideoMKV:return"mkv";case xo.VideoMOV:return"mov";case xo.VideoWMV:return"wmv";case xo.VideoFLV:return"flv";case xo.VideoWEBM:return"webm";case xo.CompressedZIP:return"zip";case xo.CompressedRAR:return"rar";case xo.Compressed7Z:return"7z";case xo.CompressedTAR:return"tar";case xo.CompressedGZ:return"gz";case xo.CodeHTML:return"html";case xo.CodeCSS:return"css";case xo.CodeJS:return"js";case xo.CodeTS:return"ts";case xo.CodeJSX:return"jsx";case xo.CodeTSX:return"tsx";case xo.CodeJSON:return"json";case xo.CodeXML:return"xml";case xo.CodePY:return"py";case xo.CodeJAVA:return"java";case xo.CodeC:return"c";case xo.CodeCPP:return"cpp";case xo.CodeCS:return"cs";case xo.CodeRB:return"rb";case xo.CodePHP:return"php";case xo.CodeSQL:return"sql";case xo.EbookEPUB:return"epub";case xo.EbookMOBI:return"mobi";case xo.EbookAZW:return"azw";case xo.FontTTF:return"ttf";case xo.FontOTF:return"otf";case xo.ImageICO:return"ico";case xo.ExecutableEXE:return"exe";case xo.ExecutableDMG:return"dmg";case xo.ExecutableAPK:return"apk";default:return""}})(c),u=(e=>{switch(e){case xo.Text:return Ko.Text;case xo.ImagePNG:case xo.ImageJPEG:case xo.ImageJPG:case xo.ImageGIF:case xo.ImageBMP:case xo.ImageTIFF:case xo.ImageSVG:case xo.ImageWEBP:case xo.ImageHEIC:case xo.ImageICO:return Ko.Image;case xo.DocumentPDF:case xo.DocumentDOC:case xo.DocumentDOCX:case xo.DocumentXLS:case xo.DocumentXLSX:case xo.DocumentPPT:case xo.DocumentPPTX:case xo.DocumentTXT:case xo.DocumentRTF:case xo.DocumentODT:return Ko.Document;case xo.AudioMP3:case xo.AudioWAV:case xo.AudioAAC:case xo.AudioFLAC:case xo.AudioOGG:case xo.AudioM4A:return Ko.Audio;case xo.VideoMP4:case xo.VideoAVI:case xo.VideoMKV:case xo.VideoMOV:case xo.VideoWMV:case xo.VideoFLV:case xo.VideoWEBM:return Ko.Video;case xo.CompressedZIP:case xo.CompressedRAR:case xo.Compressed7Z:case xo.CompressedTAR:case xo.CompressedGZ:return Ko.Compressed;case xo.CodeHTML:case xo.CodeCSS:case xo.CodeJS:case xo.CodeJSX:case xo.CodeTS:case xo.CodeTSX:case xo.CodeJSON:case xo.CodeXML:case xo.CodePY:case xo.CodeJAVA:case xo.CodeC:case xo.CodeCPP:case xo.CodeCS:case xo.CodeRB:case xo.CodePHP:case xo.CodeSQL:return Ko.Code;case xo.EbookEPUB:case xo.EbookMOBI:case xo.EbookAZW:return Ko.Ebook;case xo.FontTTF:case xo.FontOTF:return Ko.Font;case xo.ExecutableEXE:case xo.ExecutableDMG:case xo.ExecutableAPK:return Ko.Executable;default:return Ko.Unknown}})(c),h=a[i].messages[s].fromPeerId===r.peerId?100:Math.floor(a[i].messages[s].savedSize/a[i].messages[s].totalSize*100),f={chunksReceivedTotal:a[i].messages[s].chunksReceivedTotal??0,chunksReceivedReal:a[i].messages[s].chunksReceivedReal??0,retransmits:a[i].messages[s].retransmits??0};if(c!==xo.Text&&!n)return{message:"",percentage:h,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u,...f};if(c!==xo.Text&&100===h){const e=a[i].messages[s].filename,t=a[i].messages[s].fromPeerId===r.peerId?await((e,t,n,r)=>Wa("assembleToOPFS",e,t,n,r))(a[i].messages[s].merkleRootHex,a[i].messages[s].totalSize,e,l):await((e,t,n,r)=>Wa("getReceiveFile",e,t,n,r))(a[i].messages[s].merkleRootHex,a[i].messages[s].totalSize,e,l);if(t)return{message:t,percentage:h,size:a[i].messages[s].totalSize,filename:e,mimeType:l,extension:d,category:u,...f}}const p=100===h?await((e,t)=>Wa("getDBAllChunks",e,t))(a[i].messages[s].merkleRootHex,a[i].messages[s].sha512Hex):[],m=p.map(e=>e.data).filter(e=>null!=e);try{const e=new Blob(m,{type:l});return c===xo.Text?{message:m.length>0?await e.text():a[i].messages[s].fromPeerId===r.peerId?"Outgoing message...":"Incoming message...",percentage:h,size:a[i].messages[s].totalSize,filename:"",mimeType:l,extension:d,category:u,...f}:100===h&&e.size!==a[i].messages[s].totalSize?{message:"Irretrievable message",percentage:0,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u}:{message:e,percentage:h,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u,...f}}catch{return{message:"Invalid message",percentage:0,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u}}}catch(e){return console.error(e),{message:"Irretrievable message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"",category:Ko.Text}}},jh=async(e,t,n,r,a)=>{if(!a&&!n&&!r)throw new Error("Need to provide a transfer ID, Merkle root, or hash");if(a&&!/^[0-9a-f]{64}$/.test(a))throw new Error("Invalid transfer ID");if(n&&"string"==typeof n&&n.length!==2*N)throw new Error("Invalid Merkle root length");if(n&&"string"!=typeof n&&n.length!==N)throw new Error("Invalid Merkle root length");if(r&&"string"==typeof r&&r.length!==2*N)throw new Error("Invalid hash length");if(r&&"string"!=typeof r&&r.length!==N)throw new Error("Invalid hash length");const o=n&&"string"==typeof n?n:n&&"string"!=typeof n?ca(n):"",i=r&&"string"==typeof r?r:r&&"string"!=typeof r?ca(r):"";kd(e,{transferId:a,merkleRootHex:o||void 0,hashHex:i||void 0});const{rooms:s}=Xu.getState(),c=s.findIndex(t=>t.id===e),l=c>-1?a?s[c].messages.findIndex(e=>e.transferId===a):n?s[c].messages.findIndex(e=>e.merkleRootHex===o):s[c].messages.findIndex(e=>e.sha512Hex===i):-1;if(c>-1&&l>-1&&s[c].messages[l].merkleRootHex.length===2*N){const n=await po(t,s[c].messages[l].merkleRootHex);await Xu.dispatch(Du.endpoints.disconnectFromChannelLabel.initiate({roomId:s[c].id,label:n,alsoDeleteData:!0})),Xu.dispatch(ft({roomId:e,merkleRootHex:s[c].messages[l].merkleRootHex}))}},Hh={store:Xu,commonStateSelector:e=>e.commonState,signalingServerSelector:e=>e.signalingServer,roomSelector:mt,keyPairSelector:e=>e.keyPair,connect:Nh,connectToSignalingServer:async(e,t="wss://signaling.p2party.com/ws")=>{e=_h(e);const{signalingServer:n,rooms:r,commonState:a}=Xu.getState();-1===r.findIndex(t=>t.url===e)&&Gu(Je({url:e,id:""})),a.currentRoomUrl!==e&&Gu(A(e)),n.serverUrl===t&&(n.isConnected||n.isEstablishingConnection)||await Gu(Vu.endpoints.connectWebSocket.initiate(t))},disconnectFromSignalingServer:async()=>{await Gu(Vu.endpoints.disconnectWebSocket.initiate(void 0))},disconnectFromRoom:async(e,t=!1)=>{await Gu(Du.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:t}))},disconnectFromAllRooms:async(e=!1,t=[])=>{await Gu(Du.endpoints.disconnectFromAllRooms.initiate({deleteMessages:e,exceptionRoomIds:t}))},disconnectFromPeer:async e=>{await Gu(Du.endpoints.disconnectFromPeer.initiate({peerId:e}))},allowConnectionRelay:(e,t=!0)=>{const{rooms:n}=Xu.getState(),r=n.findIndex(t=>t.id===e);r>-1&&Gu(tt({roomId:n[r].id,canBeConnectionRelay:t}))},onlyAllowConnectionsFromAddressBook:async(e,t)=>{let n;try{n=_h(e)}catch{return}e=n;const{rooms:r}=Xu.getState(),a=r.findIndex(t=>t.url===e);if(a>-1&&!r[a].onlyConnectWithKnownAddresses&&t&&r[a].peers.length>0){const e=r[a].peers.length;for(let t=0;t<e;t++){await Xa(r[a].peers[t].peerId,r[a].peers[t].peerPublicKey)||await Gu(Du.endpoints.disconnectFromPeer.initiate({peerId:r[a].peers[t].peerId,roomId:r[a].id,alsoDeleteData:!1}))}}Gu(Je({url:a>-1?r[a].url:e,id:a>-1?r[a].id:"",onlyConnectWithKnownPeers:t}))},addPeerToAddressBook:(e,t,n)=>Wa("setDBAddressBookEntry",e,t,n),getPeerAddressBookEntry:Xa,getAllPeersInAddressBook:()=>Wa("getAllDBAddressBookEntries"),getAllPeersInBlacklist:()=>Wa("getAllDBBlacklisted"),deletePeerFromAddressBook:async(t,n,r)=>{const a=await((e,t,n)=>Wa("deleteDBAddressBookEntry",e,t,n))(t,n,r);e(a)&&await Gu(Du.endpoints.disconnectFromPeer.initiate({peerId:a,alsoDeleteData:!1}))},blacklistPeer:async(e,t)=>{await((e,t)=>Wa("setDBPeerInBlacklist",e,t))(e,t),await Gu(Du.endpoints.disconnectFromPeer.initiate({peerId:e,alsoDeleteData:!0}))},getPeerIsBlacklisted:Ga,removePeerFromBlacklist:(e,t)=>Wa("deleteDBPeerFromBlacklist",e,t),getAllExistingRooms:Ja,getRoomStats:e=>Wa("getDBRoomStats",e),sendMessage:(e,t,n,r=.9,a=3,o=ne,i=1,s=wd())=>{if(!/^[0-9a-f]{64}$/.test(s))throw new Error("Invalid transfer ID");const c=vd(n,s),l=Gu(Du.endpoints.sendMessage.initiate({transferId:s,data:e,label:t,roomId:n,minChunks:a,chunkSize:o,percentageFilledChunk:r,metadataSchemaVersion:i})).unwrap().finally(()=>c.finish());return{transferId:s,done:l,cancel:()=>jh(n,t,void 0,void 0,s)}},readMessage:zh,getSendChunksCount:e=>Wa("getDBAllNewChunksCount",e),cancelMessage:jh,createTransferId:wd,deleteMessage:async(e,t,n)=>{if(!t&&!n)throw new Error("Need to provide either merkle root or hash");if(t&&"string"==typeof t&&t.length!==2*N)throw new Error("Invalid Merkle root length");if(t&&"string"!=typeof t&&t.length!==N)throw new Error("Invalid Merkle root length");if(n&&"string"==typeof n&&n.length!==2*N)throw new Error("Invalid hash length");if(n&&"string"!=typeof n&&n.length!==N)throw new Error("Invalid hash length");const r=t&&"string"==typeof t?t:t&&"string"!=typeof t?ca(t):"",a=n&&"string"==typeof n?n:n&&"string"!=typeof n?ca(n):"";kd(e,{merkleRootHex:r||void 0,hashHex:a||void 0});const{rooms:o}=Xu.getState(),i=o.findIndex(t=>t.id===e),s=i>-1?t?o[i].messages.findIndex(e=>e.merkleRootHex===r):n?o[i].messages.findIndex(e=>e.sha512Hex===a):-1:-1;if(i>-1&&s>-1&&o[i].messages[s].merkleRootHex.length===2*N){const t=await po(o[i].messages[s].channelLabel,o[i].messages[s].merkleRootHex);await Xu.dispatch(Du.endpoints.disconnectFromChannelLabel.initiate({roomId:o[i].id,label:t,alsoDeleteData:!0})),Xu.dispatch(ft({roomId:e,merkleRootHex:o[i].messages[s].merkleRootHex}))}},purgeIdentity:async()=>{Sd(),Rd(),Gu(U()),await uo(),await fo();const{rooms:e}=Xu.getState(),t=e.length;for(let n=0;n<t;n++)await Gu(Du.endpoints.disconnectFromRoom.initiate({roomId:e[n].id}));await Gu(Vu.endpoints.disconnectWebSocket.initiate(void 0))},purgeRoom:async e=>{e=_h(e),Kd(e);const{rooms:t}=Xu.getState(),n=t.findIndex(t=>t.url===e);n>-1&&(Id(t[n].id),t[n].id&&await Nd(t[n].id),Gu(pt(t[n].id))),await Gu(Vu.endpoints.disconnectWebSocket.initiate(void 0))},purge:async()=>{Sd(),Rd(),Gu(U()),await uo(),await fo(),await Gu(Vu.endpoints.disconnectWebSocket.initiate(void 0));const e=await Ja(),t=e.length;for(let n=0;n<t;n++)Gu(pt(e[n].roomId))},generateRandomRoomUrl:async()=>Kh(xh()),generateRoomInvite:()=>Uh(xh()),generateRoomCapability:xh,encodeRoomCapabilityBase64Url:Kh,decodeRoomCapabilityBase64Url:Rh,decodeRoomCapability:Mh,normalizeRoomCapability:_h,encodeRoomInviteFragment:Uh,decodeRoomInviteFragment:Dh,encodeRoomCapabilityWords:async e=>{const t=Ph(e),n=new Uint8Array(33);n.set(t),n[32]=await Th(t);const r=(e=>{const t=[];let n=0,r=0;for(const a of e)for(n=n<<8|a,r+=8;r>=11;)r-=11,t.push(n>>>r&2047),n&=(1<<r)-1;if(0!==r)throw new Error("Room invite word encoding is not byte-aligned");return t})(n);if(24!==r.length)throw new Error("Room invite word encoding has an unexpected length");return r.map(e=>gh[e]).join(" ")},decodeRoomCapabilityWords:async e=>{if("string"!=typeof e)throw new TypeError("Room invite words must be a string");const t=e.normalize("NFKD").trim().toLowerCase(),n=0===t.length?[]:t.split(/\s+/u);if(24!==n.length)throw new Error("Room invite must contain exactly 24 words");const r=(e=>{const t=new Uint8Array(33);let n=0,r=0,a=0;for(const o of e)for(n=n<<11|o,r+=11;r>=8;)r-=8,t[a]=n>>>r&255,a+=1,n&=(1<<r)-1;if(0!==r||a!==t.length)throw new Error("Room invite word encoding is not canonical");return t})(n.map(e=>{const t=Eh.get(e);if(void 0===t)throw new Error(`Unknown room invite word: ${e}`);return t})),a=r.slice(0,vh),o=await Th(a);if(r[32]!==o)throw new Error("Room invite checksum is invalid");return a},ROOM_INVITE_WORDLIST_ID:"p2party-invite-en-v1",sign:Na,verify:qa,createSession:mh,restoreSession:yh,generateSessionIdentity:ch,setWasmSourceUrl:_a,DEFAULT_ROOM_POLICY_V1:Qe,encodeRoomPolicyV1:ze,decodeRoomPolicyV1:je,hashRoomPolicyV1:$e,roomPoliciesEqualV1:Ve,generateKeyPair:Ta,newKeyPair:Ta,generateMnemonic:async(e=128)=>{if(e%32!=0)throw new TypeError("Mnemonic strength needs to be multiple of 32.");if(![128,160,192,224,256,288,320,352,384,416,448,480,512].includes(e))throw new Error("Wrong mnemonic strength");const t=window.crypto.getRandomValues(new Uint8Array(e/8)),n=t.reduce((e,t)=>e+t.toString(2).padStart(8,"0"),""),r=e/32,a=Uint8Array.from(t),o=await window.crypto.subtle.digest("SHA-512",a);return(n+new Uint8Array(o).reduce((e,t)=>e+t.toString(2).padStart(8,"0"),"").slice(0,r)).match(/(.{1,11})/g).map(e=>{const t=parseInt(e,2);return gh[t]}).join(" ")},keyPairFromMnemonic:async(e,t)=>{if(!await bh(e))throw new Error("Invalid mnemonic.");const n=new Uint8Array(V),r=new TextEncoder;r.encodeInto("password12345678",n);const a=new Uint8Array(V);if(t){const e=r.encode(t),n=await window.crypto.subtle.digest("SHA-512",e);a.set(new Uint8Array(n).slice(N-V,N))}else a.set(n);const o=await(async(e,t,n)=>{const r=wh(e),a=(new TextEncoder).encode(r).buffer,o=new Int8Array(a),i=o.length;t=t??window.crypto.getRandomValues(new Uint8Array(V));const s=n?.wasmMemory??ba(i),c=(n=n??await Ua(s))._malloc(B),l=new Uint8Array(s.buffer,c,B),d=n._malloc(i*Uint8Array.BYTES_PER_ELEMENT),u=new Int8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT),h=n._malloc(V),f=new Uint8Array(s.buffer,h,V);try{if(Pa(l),u.set(o),f.set(t),0!==n._argon2(i,l.byteOffset,u.byteOffset,f.byteOffset))throw new Error("Could not generate argon2id for mnemonic.");return Uint8Array.from(l)}finally{Da(n,l),Da(n,new Uint8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT)),n._free(h),o.fill(0)}})(e,a);return await(async e=>{const t=fa(),n=await Ua(t),r=n._malloc(L),a=new Uint8Array(t.buffer,r,L),o=n._malloc(F),i=new Uint8Array(t.buffer,o,F),s=n._malloc(B),c=new Uint8Array(t.buffer,s,B);c.set(e);const l=n._keypair_from_seed(a.byteOffset,i.byteOffset,c.byteOffset);if(Da(n,c),0===l){const e={publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(i)};return n._free(r),Da(n,i),e}throw n._free(r),Da(n,i),new Error("An unexpected error occured.")})(o)},MIN_CHUNKS:1,MIN_CHUNK_SIZE:re+1,MAX_CHUNK_SIZE:ne,WIRE_CHUNK_FRAME_LEN:de,MIN_COVER_CADENCE_MS:Se,MAX_COVER_CADENCE_MS:Ce,MAX_COVER_LANES:16,MAX_COVER_FRAMES_PER_CELL:Ee,MIN_COVER_SLOT_MS:25,validateRoomPolicyV1:Fe,MessageDeliveryError:Su,joinRoom:Bh,waitForRoom:Oh,waitForPeers:Lh,onMessage:Fh,setDebugLogging:It,MIN_PERCENTAGE_FILLED_CHUNK:.1,MAX_PERCENTAGE_FILLED_CHUNK:.99,ROOM_URL_LENGTH:64,MessageType:xo,MessageCategory:Ko,VERSION:S};"undefined"!=typeof window&&(window.p2party=Hh);export{Qe as DEFAULT_ROOM_POLICY_V1,Ce as MAX_COVER_CADENCE_MS,Ee as MAX_COVER_FRAMES_PER_CELL,Ae as MAX_COVER_LANES,Se as MIN_COVER_CADENCE_MS,Pe as MIN_COVER_SLOT_MS,Su as MessageDeliveryError,de as WIRE_CHUNK_FRAME_LEN,He as canonicalizeRoomPolicyV1,mh as createSession,je as decodeRoomPolicyV1,Hh as default,ze as encodeRoomPolicyV1,ch as generateSessionIdentity,$e as hashRoomPolicyV1,Bh as joinRoom,Fh as onMessage,Hh as p2party,yh as restoreSession,Ve as roomPoliciesEqualV1,It as setDebugLogging,_a as setWasmSourceUrl,Fe as validateRoomPolicyV1,Lh as waitForPeers,Oh as waitForRoom};
1
+ import{isUUID as e,isHexadecimal as t}from"class-validator";import{createSlice as n,nanoid as r,formatProdErrorMessage as a,createSelector as o,createAction as i,createAsyncThunk as s,prepareAutoBatched as c,isAnyOf as l,isFulfilled as d,isRejectedWithValue as u,combineReducers as h,isPlainObject as f,SHOULD_AUTOBATCH as p,isAllOf as m,isRejected as y,isPending as g,isAction as w,createNextState as b,isAsyncThunkAction as v,createListenerMiddleware as k,configureStore as I}from"@reduxjs/toolkit";var S="0.14.3";const C=n({name:"commonState",initialState:{currentRoomUrl:""},reducers:{setCurrentRoomUrl:(e,t)=>{e.currentRoomUrl=t.payload}}}),{setCurrentRoomUrl:A}=C.actions;var E=C.reducer;const P={peerId:localStorage.getItem("peerId")??"",challengeId:localStorage.getItem("challengeId")??"",publicKey:localStorage.getItem("publicKey")??"",secretKey:"",challenge:localStorage.getItem("challenge")??"",signature:localStorage.getItem("signature")??""},x=n({name:"keyPair",initialState:P,reducers:{setKeyPair:(e,t)=>{const{publicKey:n,secretKey:r}=t.payload;64===n.length&&128===r.length&&(e.publicKey=t.payload.publicKey,e.secretKey=t.payload.secretKey)},setReconnectData:(n,r)=>{const{peerId:a,challenge:o,signature:i,challengeId:s}=r.payload;e(a,4)&&e(s)&&t(o)&&t(i)&&64===o.length&&128===i.length&&(n.peerId=a,n.challenge=o,n.signature=i,n.challengeId=s)},setPeerData:(n,r)=>{const{peerId:a,challenge:o,signature:i}=r.payload;e(a,4)&&t(o)&&t(i)&&64===o.length&&128===i.length&&(n.peerId=a,n.challenge=o,n.signature=i)},setChallengeId:(t,n)=>{const{challengeId:r}=n.payload;e(r)&&(t.challengeId=r)},resetIdentity:()=>({peerId:"",challengeId:"",publicKey:"",secretKey:"",challenge:"",signature:""})}}),{setKeyPair:K,setReconnectData:R,setPeerData:M,setChallengeId:_,resetIdentity:U}=x.actions;var D=x.reducer;const T=64*Uint8Array.BYTES_PER_ELEMENT,N=64*Uint8Array.BYTES_PER_ELEMENT,q=208,O=64*Uint8Array.BYTES_PER_ELEMENT,B=32*Uint8Array.BYTES_PER_ELEMENT,L=32*Uint8Array.BYTES_PER_ELEMENT,F=64*Uint8Array.BYTES_PER_ELEMENT,z=32*Uint8Array.BYTES_PER_ELEMENT,j=12*Uint8Array.BYTES_PER_ELEMENT,H=16*Uint8Array.BYTES_PER_ELEMENT,$=16*Uint8Array.BYTES_PER_ELEMENT,V=32*Uint8Array.BYTES_PER_ELEMENT,Q=64*Uint8Array.BYTES_PER_ELEMENT,W=32*Uint8Array.BYTES_PER_ELEMENT,X=32*Uint8Array.BYTES_PER_ELEMENT,G=32*Uint8Array.BYTES_PER_ELEMENT,J=65536,Y=10737418240,Z=1048576,ee=9+N+8+8+256+8+8+8,te=4+48*(N+1),ne=65405-(ee+te),re=J-ne,ae=65405,oe=N,ie=1+oe,se=new Uint8Array([1]),ce=32,le=12,de=65474+H,ue=(new TextEncoder).encode("p2party-x25519-idsig-v1"),he="hybrid-3dh-mlkem512-cpace21-v4",fe="hybrid-3dh-mlkem768-cpace21-v4",pe="hybrid-3dh-mlkem1024-cpace21-v4",me=[he,fe,pe],ye=fe,ge=2e3,we=1048576,be=65536,ve=e=>{if("hybrid-mlkem512"===e)return 512;if("hybrid-mlkem768"===e)return 768;if("hybrid-mlkem1024"===e)return 1024;throw new Error("roomPolicy: unsupported PQ mode")},ke=e=>{if("hybrid-mlkem512"===e)return he;if("hybrid-mlkem768"===e)return fe;if("hybrid-mlkem1024"===e)return pe;throw new Error("roomPolicy: unsupported PQ mode")},Ie=e=>{if(e===he)return"hybrid-mlkem512";if(e===fe)return"hybrid-mlkem768";if(e===pe)return"hybrid-mlkem1024";throw new Error("roomPolicy: unsupported ratchet root suite")},Se=1e3,Ce=36e5,Ae=16,Ee=1024,Pe=25,xe=new Uint8Array([80,50,82,80]),Ke=(new TextEncoder).encode("p2party/room-policy/v1\0"),Re=new Set(["version","revision","wireVersion","authMode","pqMode","rendezvousMode","coverMode","coverCadenceMs","coverLanes","coverFramesPerCell","coverDurationEpochs"]),Me={nopin:0,pin:1},_e={"hybrid-mlkem768":1,"hybrid-mlkem512":2,"hybrid-mlkem1024":3},Ue={"legacy-signaling":0,"opaque-token":1,"blind-meeting-point":2},De={immediate:0,scheduled:1},Te=e=>{if(0===e)return"nopin";if(1===e)return"pin";throw new Error("roomPolicy: unsupported auth mode")},Ne=e=>{if(1===e)return"hybrid-mlkem768";if(2===e)return"hybrid-mlkem512";if(3===e)return"hybrid-mlkem1024";if(0===e)throw new Error("roomPolicy: v3 requires a hybrid ML-KEM suite");throw new Error("roomPolicy: unsupported PQ mode")},qe=e=>{if(0===e)return"legacy-signaling";if(1===e)return"opaque-token";if(2===e)return"blind-meeting-point";throw new Error("roomPolicy: unsupported rendezvous mode")},Oe=e=>{if(0===e)return"immediate";if(1===e)return"scheduled";throw new Error("roomPolicy: unsupported cover mode")},Be=(e,t,n)=>{if(!Number.isSafeInteger(t)||t<0||t>n)throw new Error(`roomPolicy: ${e} is out of range`)};function Le(e,t,n){if("string"!=typeof t||!Object.hasOwn(n,t))throw new Error(`roomPolicy: unsupported ${e}`)}const Fe=e=>{if((e=>{if(null===e||"object"!=typeof e||Array.isArray(e))throw new Error("roomPolicy: policy must be an object");const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)throw new Error("roomPolicy: policy must be a plain record");const n=Reflect.ownKeys(e);if(n.length!==Re.size||n.some(e=>"string"!=typeof e||!Re.has(e)))throw new Error("roomPolicy: policy has missing or unexpected fields (PIN bytes are never policy fields)");for(const t of Re){const n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n||!("value"in n)||!n.enumerable)throw new Error("roomPolicy: policy fields must be enumerable data properties")}})(e),1!==e.version)throw new Error("roomPolicy: unsupported policy version");if(4!==e.wireVersion)throw new Error("roomPolicy: unsupported wire version");if(Be("revision",e.revision,4294967295),Le("auth mode",e.authMode,Me),Le("PQ mode",e.pqMode,_e),Le("rendezvous mode",e.rendezvousMode,Ue),Le("cover mode",e.coverMode,De),Be("cover cadence",e.coverCadenceMs,4294967295),Be("cover lanes",e.coverLanes,65535),Be("cover frames per cell",e.coverFramesPerCell,65535),Be("cover duration epochs",e.coverDurationEpochs,65535),"immediate"!==e.coverMode){if(e.coverCadenceMs<Se||e.coverCadenceMs>Ce)throw new Error("roomPolicy: scheduled cover cadence is out of range");if(e.coverLanes<1||e.coverLanes>16)throw new Error("roomPolicy: scheduled cover lanes are out of range");if(e.coverFramesPerCell<1||e.coverFramesPerCell>Ee)throw new Error("roomPolicy: scheduled cover frames per cell are out of range");if(e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell)<25)throw new Error("roomPolicy: scheduled cover slots are below the transport timer granularity");if(e.coverDurationEpochs<1)throw new Error("roomPolicy: scheduled cover duration epochs are out of range")}else if(0!==e.coverCadenceMs||0!==e.coverLanes||0!==e.coverFramesPerCell||0!==e.coverDurationEpochs)throw new Error("roomPolicy: immediate cover mode requires zero schedule fields")},ze=e=>{Fe(e);const t=new Uint8Array(32);t.set(xe,0),t[4]=1,t[5]=e.wireVersion,t[6]=Me[e.authMode],t[7]=_e[e.pqMode],t[8]=Ue[e.rendezvousMode],t[9]=De[e.coverMode];const n=new DataView(t.buffer,t.byteOffset,t.byteLength);return n.setUint32(10,e.revision,!1),n.setUint32(14,e.coverCadenceMs,!1),n.setUint16(18,e.coverLanes,!1),n.setUint16(20,e.coverFramesPerCell,!1),n.setUint16(22,e.coverDurationEpochs,!1),t},je=e=>{if(!(e instanceof Uint8Array))throw new Error("roomPolicy: encoded policy must be a Uint8Array");if(32!==e.length)throw new Error("roomPolicy: invalid encoded policy length");for(let t=0;t<xe.length;t++)if(e[t]!==xe[t])throw new Error("roomPolicy: invalid policy magic");for(let t=24;t<e.length;t++)if(0!==e[t])throw new Error("roomPolicy: non-zero reserved policy byte");const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[4],wireVersion:e[5],authMode:Te(e[6]),pqMode:Ne(e[7]),rendezvousMode:qe(e[8]),coverMode:Oe(e[9]),revision:t.getUint32(10,!1),coverCadenceMs:t.getUint32(14,!1),coverLanes:t.getUint16(18,!1),coverFramesPerCell:t.getUint16(20,!1),coverDurationEpochs:t.getUint16(22,!1)};return Fe(n),n},He=e=>je(ze(e)),$e=(e,t)=>{const n=ze(e),r=ze(t);let a=0;for(let e=0;e<n.length;e++)a|=n[e]^r[e];return 0===a},Ve=async e=>{const t=ze(e),n=new Uint8Array(Ke.length+t.length);n.set(Ke,0),n.set(t,Ke.length);const r=await globalThis.crypto.subtle.digest("SHA-256",n);return new Uint8Array(r)},Qe=Object.freeze({version:1,revision:0,wireVersion:4,authMode:"nopin",pqMode:"hybrid-mlkem768",rendezvousMode:"legacy-signaling",coverMode:"immediate",coverCadenceMs:0,coverLanes:0,coverFramesPerCell:0,coverDurationEpochs:0}),We={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},Xe=(e,t)=>{const n=He(t);if(!$e(e,n))throw new Error("roomSlice: room policy is immutable after creation")},Ge=n({name:"rooms",initialState:[],reducers:{setRoom:(t,n)=>{const{url:r,id:a,canBeConnectionRelay:o,rtcConfig:i,onlyConnectWithKnownPeers:s,policy:c}=n.payload;if(64===r.length&&e(a)){const e=t.findIndex(e=>e.url===r||e.id===a);e>-1?(c&&Xe(t[e].policy,c),t[e].url=r,t[e].id=a,null!=o&&(t[e].canBeConnectionRelay=o),i&&(t[e].rtcConfig=i),t[e].onlyConnectWithKnownAddresses=null!=s?s:"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers")):t.push({url:r,id:a,connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:o??!0,onlyConnectWithKnownAddresses:s??"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers"),rtcConfig:i??We,policy:He(c??Qe),peers:[],channels:[],messages:[]})}else if(64===r.length){const e=t.findIndex(e=>e.url===r);e>-1?(c&&Xe(t[e].policy,c),t[e].url=r,t[e].id="",null!=o&&(t[e].canBeConnectionRelay=o),i&&(t[e].rtcConfig=i),t[e].onlyConnectWithKnownAddresses=null!=s?s:"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers")):t.push({url:r,id:"",connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:o??!0,onlyConnectWithKnownAddresses:s??"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers"),rtcConfig:i??We,policy:He(c??Qe),peers:[],channels:[],messages:[]})}},setRoomPolicy:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload.roomContext||e.id===t.payload.roomContext);n>-1&&Xe(e[n].policy,t.payload.policy)},setConnectingToPeers:(e,t)=>{const{roomId:n,connectingToPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].connectingToPeers=r)},setConnectedToPeers:(e,t)=>{const{roomId:n,connectedToPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].connectingToPeers=!1,e[a].connectedToPeers=r)},setConnectionRelay:(e,t)=>{const{roomId:n,canBeConnectionRelay:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].canBeConnectionRelay=r)},setPeer:(e,t)=>{const{roomId:n,peerId:r,peerPublicKey:a}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){-1===e[o].peers.findIndex(e=>e.peerId===r)&&e[o].peers.push({peerId:r,peerPublicKey:a})}},deletePeer:(e,t)=>{const n=e.length;for(let r=0;r<n;r++){if(void 0!==t.payload.roomId&&e[r].id!==t.payload.roomId)continue;const n=e[r].peers.findIndex(e=>e.peerId===t.payload.peerId);n>-1&&e[r].peers.splice(n,1);const a=e[r].coverStatusByPeer;a&&delete a[t.payload.peerId];const o=e[r].handshakeStatusByPeer;o&&"failed"!==o[t.payload.peerId]?.status&&delete o[t.payload.peerId]}},setPeerCoverStatus:(e,t)=>{const{roomId:n,peerId:r,status:a}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){const t=e[o];t.coverStatusByPeer??={},t.coverStatusByPeer[r]=a}},setPeerHandshakeStatus:(e,t)=>{const{roomId:n,peerId:r,status:a,reason:o,retryAfter:i}=t.payload,s=e.findIndex(e=>e.id===n);if(s>-1){const t=e[s];t.handshakeStatusByPeer??={},t.handshakeStatusByPeer[r]={status:a,reason:o,retryAfter:i}}},setChannel:(e,t)=>{const{roomId:n,label:r,peerId:a}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){const t=e[o].channels.findIndex(e=>e.label===r);if(t>-1){-1===e[o].channels[t].peerIds.findIndex(e=>e===a)&&e[o].channels[t].peerIds.push(a)}else e[o].channels.push({label:r,peerIds:[a]})}},deleteChannel:(e,t)=>{const{roomId:n,peerId:r,label:a}=t.payload,o=e.length;for(let t=0;t<o;t++)if(void 0===n||e[t].id===n)if(a&&!r){const n=e[t].channels.findIndex(e=>e.label===a);n>-1&&e[t].channels.splice(n,1)}else if(!a&&r)for(let n=e[t].channels.length-1;n>=0;n--){const a=e[t].channels[n].peerIds.findIndex(e=>e===r);a>-1&&(e[t].channels[n].peerIds.splice(a,1),0===e[t].channels[n].peerIds.length&&e[t].channels.splice(n,1))}else if(r&&a){const n=e[t].channels.findIndex(e=>e.label===a&&e.peerIds.includes(r));if(n>-1){const a=e[t].channels[n].peerIds.findIndex(e=>e===r);e[t].channels[n].peerIds.splice(a,1),0===e[t].channels[n].peerIds.length&&e[t].channels.splice(n,1)}}},setIceServers:(e,t)=>{const{roomId:n,iceServers:r}=t.payload,a=e.findIndex(e=>e.id===n);if(a>-1){const t=r.length,n=e[a].rtcConfig.iceServers?.flatMap(e=>Array.isArray(e.urls)?e.urls:[e.urls])??[];for(let o=0;o<t;o++){const t=r[o].urls.length;let i=!1;for(let e=0;e<t;e++)if(!n.includes(r[o].urls[e])){i=!0;break}i&&e[a].rtcConfig.iceServers?.push(r[o])}}},setMessage:(t,n)=>{const{roomId:r,transferId:a,merkleRootHex:o,sha512Hex:i,filename:s,channelLabel:c,fromPeerId:l,messageType:d,chunkSize:u,totalSize:h,chunksCreated:f,totalChunks:p,timestamp:m}=n.payload,y=t.findIndex(e=>e.id===r);if(y>-1){const n=t[y].messages.findLastIndex(e=>(void 0!==a?e.transferId===a:e.merkleRootHex===o)||void 0===a&&e.sha512Hex===i&&0===e.merkleRootHex.length);-1===n?c&&l&&e(l)&&d&&h&&t[y].messages.push({transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:c,filename:s.length>0?s:"txt",messageType:d,fromPeerId:l,timestamp:m??Date.now(),savedSize:u>0?u:0,totalSize:h,chunksCreated:f??0,totalChunks:p??0}):t[y].messages[n].timestamp!==m&&t[y].messages[n].sha512Hex===i&&t[y].messages[n].savedSize===t[y].messages[n].totalSize?t[y].messages.push({transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:c,filename:s.length>0?s:"txt",messageType:d,fromPeerId:l,timestamp:m??Date.now(),savedSize:u,totalSize:h,chunksCreated:f??0,totalChunks:p??0}):(o.length===2*N&&""===t[y].messages[n].merkleRootHex&&(t[y].messages[n].merkleRootHex=o),h>0&&t[y].messages[n].totalSize!==h&&(t[y].messages[n].totalSize=h),u>0&&t[y].messages[n].totalSize>=t[y].messages[n].savedSize+u&&(t[y].messages[n].savedSize+=u),f&&f<=t[y].messages[n].totalChunks&&(t[y].messages[n].chunksCreated=f+1))}},setMessageAllChunks:(t,n)=>{const{roomId:r,transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:s,filename:c,messageType:l,fromPeerId:d,timestamp:u,totalSize:h}=n.payload,f=t.findIndex(e=>e.id===r);if(f>-1){const n=t[f].messages.findLastIndex(e=>e.merkleRootHex===o);-1===n&&s&&d&&e(d)&&l&&h||n>-1&&t[f].messages[n].timestamp<u?t[f].messages.push({transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:s,filename:c.length>0?c:"txt",messageType:l,fromPeerId:d,timestamp:u,savedSize:h,totalSize:h,chunksCreated:0,totalChunks:0}):n>-1&&t[f].messages[n].savedSize!==h&&(t[f].messages[n].savedSize=h)}},deleteMessage:(e,t)=>{const{roomId:n,transferId:r,merkleRootHex:a,hashHex:o}=t.payload;if(!r&&!a&&!o)return;if(r&&!/^[0-9a-f]{64}$/.test(r))return;if(a&&a.length!==2*N)return;if(o&&o.length!==2*N)return;const i=e.findIndex(e=>e.id===n);if(-1!==i)if(r){const t=e[i].messages.findIndex(e=>e.transferId===r);t>-1&&e[i].messages.splice(t,1)}else if(a){const t=e[i].messages.findIndex(e=>e.merkleRootHex===a);t>-1&&e[i].messages.splice(t,1)}else if(o){const t=e[i].messages.findLastIndex(e=>e.sha512Hex===o);t>-1&&e[i].messages.splice(t,1)}},setOnlyConnectWithKnownPeers:(e,t)=>{const{roomId:n,onlyConnectWithKnownPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].onlyConnectWithKnownAddresses=r)},deleteRoom:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload||e.id===t.payload);if(n>-1){const t=e[n].url,r=e[n].policy;e[n]={url:t,id:"",connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:!0,onlyConnectWithKnownAddresses:!1,rtcConfig:We,policy:He(r),peers:[],channels:[],messages:[]}}},incrementMessageStats:(e,t)=>{const{roomId:n,merkleRootHex:r,sha512Hex:a,real:o,retransmit:i}=t.payload,s=e.findIndex(e=>e.id===n);if(s<0)return;const c=e[s].messages.findLastIndex(e=>void 0!==r&&e.merkleRootHex===r||void 0!==a&&e.sha512Hex===a);if(c<0)return;const l=e[s].messages[c];i?l.retransmits=(l.retransmits??0)+1:(l.chunksReceivedTotal=(l.chunksReceivedTotal??0)+1,o&&(l.chunksReceivedReal=(l.chunksReceivedReal??0)+1))}}}),{setRoom:Je,setRoomPolicy:Ye,setConnectingToPeers:Ze,setConnectedToPeers:et,setConnectionRelay:tt,setOnlyConnectWithKnownPeers:nt,setPeer:rt,setPeerCoverStatus:at,setPeerHandshakeStatus:ot,setChannel:it,setIceServers:st,setMessage:ct,setMessageAllChunks:lt,incrementMessageStats:dt,deletePeer:ut,deleteChannel:ht,deleteMessage:ft,deleteRoom:pt}=Ge.actions,mt=e=>e.rooms;var yt=Ge.reducer;const gt="wss://signaling.p2party.com/ws",wt=n({name:"signalingServer",initialState:{isEstablishingConnection:!1,isConnected:!1,isVerified:!1,serverUrl:gt},reducers:{startConnecting:(e,t)=>{e.isEstablishingConnection=!0,e.serverUrl=t.payload??gt},connectionEstablished:e=>{e.isConnected=!0,e.isEstablishingConnection=!1,e.isVerified=!1},connectionVerified:e=>{e.isConnected=!0,e.isEstablishingConnection=!1,e.isVerified=!0},disconnect:e=>{e.isConnected=!1,e.isEstablishingConnection=!1,e.isVerified=!1}}}),bt=wt.actions;var vt=wt.reducer;let kt=!1;kt=(()=>{try{return"1"===globalThis.localStorage?.getItem("p2party:debug")}catch{return!1}})();const It=e=>{kt=e},St=(...e)=>{kt&&console.log(...e)};var Ct=Symbol.for("immer-nothing"),At=Symbol.for("immer-draftable"),Et=Symbol.for("immer-state");function Pt(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var xt=Object,Kt=xt.getPrototypeOf,Rt="constructor",Mt="prototype",_t="configurable",Ut="enumerable",Dt="writable",Tt="value",Nt=e=>!!e&&!!e[Et];function qt(e){return!!e&&(Lt(e)||Vt(e)||!!e[At]||!!e[Rt]?.[At]||Qt(e)||Wt(e))}var Ot=xt[Mt][Rt].toString(),Bt=new WeakMap;function Lt(e){if(!e||!Xt(e))return!1;const t=Kt(e);if(null===t||t===xt[Mt])return!0;const n=xt.hasOwnProperty.call(t,Rt)&&t[Rt];if(n===Object)return!0;if(!Gt(n))return!1;let r=Bt.get(n);return void 0===r&&(r=Function.toString.call(n),Bt.set(n,r)),r===Ot}function Ft(e,t,n=!0){if(0===zt(e)){(n?Reflect.ownKeys(e):xt.keys(e)).forEach(n=>{t(n,e[n],e)})}else e.forEach((n,r)=>t(r,n,e))}function zt(e){const t=e[Et];return t?t.type_:Vt(e)?1:Qt(e)?2:Wt(e)?3:0}var jt=(e,t,n=zt(e))=>2===n?e.has(t):xt[Mt].hasOwnProperty.call(e,t),Ht=(e,t,n=zt(e))=>2===n?e.get(t):e[t],$t=(e,t,n,r=zt(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n};var Vt=Array.isArray,Qt=e=>e instanceof Map,Wt=e=>e instanceof Set,Xt=e=>"object"==typeof e,Gt=e=>"function"==typeof e,Jt=e=>"boolean"==typeof e;var Yt=e=>e.copy_||e.base_,Zt=e=>e.modified_?e.copy_:e.base_;function en(e,t){if(Qt(e))return new Map(e);if(Wt(e))return new Set(e);if(Vt(e))return Array[Mt].slice.call(e);const n=Lt(e);if(!0===t||"class_only"===t&&!n){const t=xt.getOwnPropertyDescriptors(e);delete t[Et];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const a=n[r],o=t[a];!1===o[Dt]&&(o[Dt]=!0,o[_t]=!0),(o.get||o.set)&&(t[a]={[_t]:!0,[Dt]:!0,[Ut]:o[Ut],[Tt]:e[a]})}return xt.create(Kt(e),t)}{const t=Kt(e);if(null!==t&&n)return{...e};const r=xt.create(t);return xt.assign(r,e)}}function tn(e,t=!1){return rn(e)||Nt(e)||!qt(e)||(zt(e)>1&&xt.defineProperties(e,{set:nn,add:nn,clear:nn,delete:nn}),xt.freeze(e),t&&Ft(e,(e,t)=>{tn(t,!0)},!1)),e}var nn={[Tt]:function(){Pt(2)}};function rn(e){return null===e||!Xt(e)||xt.isFrozen(e)}var an="MapSet",on="Patches",sn="ArrayMethods",cn={};function ln(e){const t=cn[e];return t||Pt(0),t}var dn,un=e=>!!cn[e];var hn=()=>dn;function fn(e,t){t&&(e.patchPlugin_=ln(on),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function pn(e){mn(e),e.drafts_.forEach(gn),e.drafts_=null}function mn(e){e===dn&&(dn=e.parent_)}var yn=e=>dn={drafts_:[],parent_:dn,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:un(an)?ln(an):void 0,arrayMethodsPlugin_:un(sn)?ln(sn):void 0};function gn(e){const t=e[Et];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function wn(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[Et].modified_&&(pn(t),Pt(4)),qt(e)&&(e=bn(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[Et].base_,e,t)}else e=bn(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&tn(t,n)}(t,e,!0),pn(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ct?e:void 0}function bn(e,t){if(rn(t))return t;const n=t[Et];if(!n){return An(t,e.handledSet_,e)}if(!kn(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:t}=n;if(t)for(;t.length>0;){t.pop()(e)}Cn(n,e)}return n.copy_}function vn(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var kn=(e,t)=>e.scope_===t,In=[];function Sn(e,t,n,r){const a=Yt(e),o=e.type_;if(void 0!==r){if(Ht(a,r,o)===t)return void $t(a,r,n,o)}if(!e.draftLocations_){const t=e.draftLocations_=new Map;Ft(a,(e,n)=>{if(Nt(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const i=e.draftLocations_.get(t)??In;for(const e of i)$t(a,e,n,o)}function Cn(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||1===e.type_&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){const{patchPlugin_:n}=t;if(n){const r=n.getPath(e);r&&n.generatePatches_(e,r,t)}vn(e)}}function An(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||Nt(e)||t.has(e)||!qt(e)||rn(e)||(t.add(e),Ft(e,(r,a)=>{if(Nt(a)){const t=a[Et];if(kn(t,n)){const n=Zt(t);$t(e,r,n,e.type_),vn(t)}}else qt(a)&&An(a,t,n)})),e}var En={get(e,t){if(t===Et)return e;let n=e.scope_.arrayMethodsPlugin_;const r=1===e.type_&&"string"==typeof t;if(r&&n?.isArrayOperationMethod(t))return n.createMethodInterceptor(e,t);const a=Yt(e);if(!jt(a,t,e.type_))return function(e,t,n){const r=Kn(t,n);return r?Tt in r?r[Tt]:r.get?.call(e.draft_):void 0}(e,a,t);const o=a[t];if(e.finalized_||!qt(o))return o;if(r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&function(e){const t=+e;return Number.isInteger(t)&&String(t)===e}(t))return o;if(o===xn(e.base_,t)||function(e,t,n){if(1!==e.type_||!e.allIndicesReassigned_||e.assigned_?.get(t)||!qt(n)||n[Et])return!1;return e.baseRefs_.has(n)}(e,t,o)){Mn(e);const n=1===e.type_?+t:t,r=_n(e.scope_,o,e,n);return e.copy_[n]=r}return o},has:(e,t)=>t in Yt(e),ownKeys:e=>Reflect.ownKeys(Yt(e)),set(e,t,n){const r=Kn(Yt(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=xn(Yt(e),t),i=r?.[Et];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(((a=n)===(o=r)?0!==a||1/a==1/o:a!=a&&o!=o)&&(void 0!==n||jt(e.base_,t,e.type_)))return!0;Mn(e),Rn(e)}var a,o;return e.copy_[t]===n&&(void 0!==n||jt(e.copy_,t,e.type_))||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),function(e,t,n){const{scope_:r}=e;if(Nt(n)){const a=n[Et];kn(a,r)&&a.callbacks_.push(function(){Mn(e);const r=Zt(a);Sn(e,n,r,t)})}else qt(n)&&e.callbacks_.push(function(){const a=Yt(e);3===e.type_?a.has(n)&&An(n,r.handledSet_,r):Ht(a,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&An(Ht(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(Mn(e),void 0!==xn(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),Rn(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Yt(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[Dt]:!0,[_t]:1!==e.type_||"length"!==t,[Ut]:r[Ut],[Tt]:n[t]}:r},defineProperty(){Pt(11)},getPrototypeOf:e=>Kt(e.base_),setPrototypeOf(){Pt(12)}},Pn={};for(let e in En){let t=En[e];Pn[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function xn(e,t){const n=e[Et];return(n?Yt(n):e)[t]}function Kn(e,t){if(!(t in e))return;let n=Kt(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=Kt(n)}}function Rn(e){e.modified_||(e.modified_=!0,e.parent_&&Rn(e.parent_))}function Mn(e){e.copy_||(e.assigned_=new Map,e.copy_=en(e.base_,e.scope_.immer_.useStrictShallowCopy_))}Pn.deleteProperty=function(e,t){return Pn.set.call(this,e,t,void 0)},Pn.set=function(e,t,n){return En.set.call(this,e[0],t,n,e[0])};function _n(e,t,n,r){const[a,o]=Qt(t)?ln(an).proxyMap_(t,n):Wt(t)?ln(an).proxySet_(t,n):function(e,t){const n=Vt(e),r={type_:n?1:0,scope_:t?t.scope_:hn(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=r,o=En;n&&(a=[r],o=Pn);const{revoke:i,proxy:s}=Proxy.revocable(a,o);return r.draft_=s,r.revoke_=i,[s,r]}(t,n);return(n?.scope_??hn()).drafts_.push(a),o.callbacks_=n?.callbacks_??[],o.key_=r,n&&void 0!==r?function(e,t,n){e.callbacks_.push(function(r){const a=t;if(!a||!kn(a,r))return;r.mapSetPlugin_?.fixSetContents(a);const o=Zt(a);Sn(e,a.draft_??a,o,n),Cn(a,r)})}(n,o,r):o.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(o);const{patchPlugin_:t}=e;o.modified_&&t&&t.generatePatches_(o,[],e)}),a}function Un(e){return Nt(e)||Pt(10),Dn(e)}function Dn(e){if(!qt(e)||rn(e))return e;const t=e[Et];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=en(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=en(e,!0);return Ft(n,(e,t)=>{$t(n,e,Dn(t))},r),t&&(t.finalized_=!1),n}function Tn(){const e="replace",t="add",n="remove";function r(e){if(!qt(e))return e;if(Vt(e))return e.map(r);if(Qt(e))return new Map(Array.from(e.entries()).map(([e,t])=>[e,r(t)]));if(Wt(e))return new Set(Array.from(e).map(r));const t=Object.create(Kt(e));for(const n in e)t[n]=r(e[n]);return jt(e,At)&&(t[At]=e[At]),t}function a(e){return Nt(e)?r(e):e}var o,i;i={applyPatches_:function(a,o){return o.forEach(o=>{const{path:i,op:s}=o;let c=a;for(let e=0;e<i.length-1;e++){const t=zt(c);let n=i[e];"string"!=typeof n&&"number"!=typeof n&&(n=""+n),0!==t&&1!==t||"__proto__"!==n&&n!==Rt||Pt(19),Gt(c)&&n===Mt&&Pt(19),c=Ht(c,n),null!==c&&Xt(c)||Pt(18,i.join("/"))}const l=zt(c),d=r(o.value),u=i[i.length-1];switch(s){case e:switch(l){case 2:return c.set(u,d);case 3:Pt(16);default:return c[u]=d}case t:switch(l){case 1:return"-"===u?c.push(d):c.splice(u,0,d);case 2:return c.set(u,d);case 3:return c.add(d);default:return c[u]=d}case n:switch(l){case 1:return c.splice(u,1);case 2:return c.delete(u);case 3:return c.delete(o.value);default:return delete c[u]}default:Pt(17)}}),a},generatePatches_:function(r,o,i){if(r.scope_.processedForPatches_.has(r))return;r.scope_.processedForPatches_.add(r);const{patches_:s,inversePatches_:c}=i;switch(r.type_){case 0:case 2:return function(r,o,i,s){const{base_:c,copy_:l,type_:d}=r;Ft(r.assigned_,(r,u)=>{const h=Ht(c,r,d),f=Ht(l,r,d),p=u?jt(c,r)?e:t:n;if(h===f&&p===e)return;const m=o.concat(r);i.push(p===n?{op:p,path:m}:{op:p,path:m,value:a(f)}),s.push(p===t?{op:n,path:m}:p===n?{op:t,path:m,value:a(h)}:{op:e,path:m,value:a(h)})})}(r,o,s,c);case 1:return function(r,o,i,s){let{base_:c,assigned_:l}=r,d=r.copy_;d.length<c.length&&([c,d]=[d,c],[i,s]=[s,i]);const u=!0===r.allIndicesReassigned_;for(let t=0;t<c.length;t++){const n=d[t],r=c[t];if((u||l?.get(t.toString()))&&n!==r){const c=n?.[Et];if(c&&c.modified_)continue;const l=o.concat([t]);i.push({op:e,path:l,value:a(n)}),s.push({op:e,path:l,value:a(r)})}}for(let e=c.length;e<d.length;e++){const n=o.concat([e]);i.push({op:t,path:n,value:a(d[e])})}for(let e=d.length-1;c.length<=e;--e){const t=o.concat([e]);s.push({op:n,path:t})}}(r,o,s,c);case 3:return function(e,r,a,o){let{base_:i,copy_:s}=e,c=0;i.forEach(e=>{if(!s.has(e)){const i=r.concat([c]);a.push({op:n,path:i,value:e}),o.unshift({op:t,path:i,value:e})}c++}),c=0,s.forEach(e=>{if(!i.has(e)){const i=r.concat([c]);a.push({op:t,path:i,value:e}),o.unshift({op:n,path:i,value:e})}c++})}(r,o,s,c)}},generateReplacementPatches_:function(t,n,r){const{patches_:a,inversePatches_:o}=r;a.push({op:e,path:[],value:n===Ct?void 0:n}),o.push({op:e,path:[],value:t})},getPath:function e(t,n=[]){if(void 0!==t.key_){const e=t.parent_.copy_??t.parent_.base_,a=(r=Ht(e,t.key_),Xt(r)?r?.[Et]:null),o=Ht(e,t.key_);if(void 0===o)return null;if(o!==t.draft_&&o!==t.base_&&o!==t.copy_)return null;if(null!=a&&a.base_!==t.base_)return null;const i=3===t.parent_.type_;let s;if(i){const e=t.parent_;s=Array.from(e.drafts_.keys()).indexOf(t.key_)}else s=t.key_;if(!(i&&e.size>s||jt(e,s)))return null;n.push(s)}var r;if(t.parent_)return e(t.parent_,n);n.reverse();try{!function(e,t){let n=e;for(let e=0;e<t.length-1;e++){const r=t[e];if(n=Ht(n,r),!Xt(n)||null===n)throw new Error(`Cannot resolve path at '${t.join("/")}'`)}}(t.copy_,n)}catch(e){return null}return n}},cn[o=on]||(cn[o]=i)}var Nn=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(Gt(e)&&!Gt(t)){const n=t;t=e;const r=this;return function(e=n,...a){return r.produce(e,e=>t.call(this,e,...a))}}let r;if(Gt(t)||Pt(6),void 0===n||Gt(n)||Pt(7),qt(e)){const a=yn(this),o=_n(a,e,void 0);let i=!0;try{r=t(o),i=!1}finally{i?pn(a):mn(a)}return fn(a,n),wn(r,a)}if(!e||!Xt(e)){if(r=t(e),void 0===r&&(r=e),r===Ct&&(r=void 0),this.autoFreeze_&&tn(r,!0),n){const t=[],a=[];ln(on).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:a}),n(t,a)}return r}Pt(1)},this.produceWithPatches=(e,t)=>{if(Gt(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},Jt(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),Jt(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),Jt(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){qt(e)||Pt(8),Nt(e)&&(e=Un(e));const t=yn(this),n=_n(t,e,void 0);return n[Et].isManual_=!0,mn(t),n}finishDraft(e,t){const n=e&&e[Et];n&&n.isManual_||Pt(9);const{scope_:r}=n;return fn(r,t),wn(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const r=t[n];if(0===r.path.length&&"replace"===r.op){e=r.value;break}}n>-1&&(t=t.slice(n+1));const r=ln(on).applyPatches_;return Nt(e)?r(e,t):this.produce(e,e=>r(e,t))}};Nn.produce;var qn=Nn.produceWithPatches.bind(Nn),On=Nn.applyPatches.bind(Nn),Bn=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}};var Ln=e=>Array.isArray(e)?e:[e];function Fn(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(e=>"function"==typeof e)){const n=e.map(e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e).join(", ");throw new TypeError(`${t}[${n}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}var zn="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function jn(){return{s:0,v:void 0,o:null,p:null}}function Hn(e,t={}){let n={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:r}=t;let a,o=0;function i(){let t=n;const{length:i}=arguments;for(let e=0,n=i;e<n;e++){const n=arguments[e];if("function"==typeof n||"object"==typeof n&&null!==n){let e=t.o;null===e&&(t.o=e=new WeakMap);const r=e.get(n);void 0===r?(t=jn(),e.set(n,t)):t=r}else{let e=t.p;null===e&&(t.p=e=new Map);const r=e.get(n);void 0===r?(t=jn(),e.set(n,t)):t=r}}const s=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),o++,r){const e=a?.deref?.()??a;null!=e&&r(e,c)&&(c=e,0!==o&&o--);a="object"==typeof c&&null!==c||"function"==typeof c?new zn(c):c}return s.s=1,s.v=c,c}return i.clearCache=()=>{n={s:0,v:void 0,o:null,p:null},i.resetResultsCount()},i.resultsCount=()=>o,i.resetResultsCount=()=>{o=0},i}function $n(e,...t){const n="function"==typeof e?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t,r=0,a=0,o={},i=e.pop();"object"==typeof i&&(o=i,i=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(i,`createSelector expects an output function after the inputs, but received: [${typeof i}]`);const s={...n,...o},{memoize:c,memoizeOptions:l=[],argsMemoize:d=Hn,argsMemoizeOptions:u=[]}=s,h=Ln(l),f=Ln(u),p=Fn(e),m=c(function(){return r++,i.apply(null,arguments)},...h),y=d(function(){a++;const e=function(e,t){const n=[],{length:r}=e;for(let a=0;a<r;a++)n.push(e[a].apply(null,t));return n}(p,arguments);return t=m.apply(null,e),t},...f);return Object.assign(y,{resultFunc:i,memoizedResultFunc:m,dependencies:p,dependencyRecomputations:()=>a,resetDependencyRecomputations:()=>{a=0},lastResult:()=>t,recomputations:()=>r,resetRecomputations:()=>{r=0},memoize:c,argsMemoize:d})};return Object.assign(r,{withTypes:()=>r}),r}var Vn=$n(Hn),Qn=Object.assign((e,t=Vn)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const n=Object.keys(e),r=n.map(t=>e[t]);return t(r,(...e)=>e.reduce((e,t,r)=>(e[n[r]]=t,e),{}))},{withTypes:()=>Qn}),Wn="uninitialized",Xn="pending",Gn="fulfilled",Jn="rejected";function Yn(e){return{status:e,isUninitialized:e===Wn,isLoading:e===Xn,isSuccess:e===Gn,isError:e===Jn}}var Zn=f;function er(e,t){if(e===t||!(Zn(e)&&Zn(t)||Array.isArray(e)&&Array.isArray(t)))return t;const n=Object.keys(t),r=Object.keys(e);let a=n.length===r.length;const o=Array.isArray(t)?[]:{};for(const r of n)o[r]=er(e[r],t[r]),a&&(a=e[r]===o[r]);return a?e:o}function tr(e,t,n){return e.reduce((e,r,a)=>(t(r,a)&&e.push(n(r,a)),e),[]).flat()}function nr(e){return null!=e}function rr(e){return[...e?.values()??[]].filter(nr)}function ar(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var or=()=>new Map,ir=class{constructor(e,t=void 0){this.value=e,this.meta=t}value;meta},sr="__rtkq/",cr="focused",lr=i(`${sr}${cr}`),dr=i(`${sr}un${cr}`),ur=i(`${sr}online`),hr=i(`${sr}offline`),fr="query",pr="mutation",mr="infinitequery";function yr(e){return e.type===fr}function gr(e){return e.type===mr}function wr(e){return yr(e)||gr(e)}function br(e,t,n,r,a,o){const i="function"==typeof e?e(t,n,r,a):e;return i?tr(i,nr,e=>o(vr(e))):[]}function vr(e){return"string"==typeof e?{type:e}:e}var kr=(e,t)=>e.endpointDefinitions[t],Ir=Symbol("forceQueryFn"),Sr=e=>"function"==typeof e[Ir];var Cr=class extends Bn{constructor(e,t,n,r){super(e),this.value=t,this.schemaName=n,this._bqMeta=r}value;schemaName;_bqMeta},Ar=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function Er(e,t,n,r){const a=await e["~standard"].validate(t);if(a.issues)throw new Cr(a.issues,t,n,r);return a.value}function Pr(e){return e}var xr=(e={})=>({...e,[p]:!0});function Kr(e,{pages:t,pageParams:n},r){const a=t.length-1;return e.getNextPageParam(t[a],t,n[a],n,r)}function Rr(e,{pages:t,pageParams:n},r){return e.getPreviousPageParam?.(t[0],t,n[0],n,r)}function Mr(e,t,n,r){return br(n[e.meta.arg.endpointName][t],d(e)?e.payload:void 0,u(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,r)}function _r(e){return Nt(e)?Un(e):e}function Ur(e,t,n){const r=e[t];r&&n(r)}function Dr(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function Tr(e,t,n){const r=e[Dr(t)];r&&n(r)}var Nr={};function qr({reducerPath:e,queryThunk:t,mutationThunk:a,serializeQueryArgs:o,context:{endpointDefinitions:s,apiUid:f,extractRehydrationInfo:m,hasRehydrationInfo:y},assertTagType:g,config:w}){const v=i(`${e}/resetApiState`);function k(e,t,n,r){e[t.queryCacheKey]??={status:Wn,endpointName:t.endpointName},Ur(e,t.queryCacheKey,e=>{e.status=Xn,e.requestId=n&&e.requestId?e.requestId:r.requestId,void 0!==t.originalArgs&&(e.originalArgs=t.originalArgs),e.startedTimeStamp=r.startedTimeStamp;gr(s[r.arg.endpointName])&&"direction"in t&&(e.direction=t.direction)})}function I(e,t,n,r){Ur(e,t.arg.queryCacheKey,e=>{if(e.requestId!==t.requestId&&!r)return;const{merge:a}=s[t.arg.endpointName];if(e.status=Gn,a)if(void 0!==e.data){const{fulfilledTimeStamp:r,arg:o,baseQueryMeta:i,requestId:s}=t;let c=b(e.data,e=>a(e,n,{arg:o.originalArgs,baseQueryMeta:i,fulfilledTimeStamp:r,requestId:s}));e.data=c}else e.data=n;else e.data=s[t.arg.endpointName].structuralSharing??1?er(Nt(e.data)?(o=e.data,Nt(o)||Pt(15),o[Et].base_):e.data,n):n;var o;delete e.error,e.fulfilledTimeStamp=t.fulfilledTimeStamp})}const S=n({name:`${e}/queries`,initialState:Nr,reducers:{removeQueryResult:{reducer(e,{payload:{queryCacheKey:t}}){delete e[t]},prepare:c()},cacheEntriesUpserted:{reducer(e,t){for(const n of t.payload){const{queryDescription:r,value:a}=n;k(e,r,!0,{arg:r,requestId:t.meta.requestId,startedTimeStamp:t.meta.timestamp}),I(e,{arg:r,requestId:t.meta.requestId,fulfilledTimeStamp:t.meta.timestamp,baseQueryMeta:{}},a,!0)}},prepare:e=>({payload:e.map(e=>{const{endpointName:t,arg:n,value:r}=e,a=s[t];return{queryDescription:{type:fr,endpointName:t,originalArgs:e.arg,queryCacheKey:o({queryArgs:n,endpointDefinition:a,endpointName:t})},value:r}}),meta:{[p]:!0,requestId:r(),timestamp:Date.now()}})},queryResultPatched:{reducer(e,{payload:{queryCacheKey:t,patches:n}}){Ur(e,t,e=>{e.data=On(e.data,n.concat())})},prepare:c()}},extraReducers(e){e.addCase(t.pending,(e,{meta:t,meta:{arg:n}})=>{k(e,n,Sr(n),t)}).addCase(t.fulfilled,(e,{meta:t,payload:n})=>{I(e,t,n,Sr(t.arg))}).addCase(t.rejected,(e,{meta:{condition:t,arg:n,requestId:r},error:a,payload:o})=>{Ur(e,n.queryCacheKey,e=>{if(t);else{if(e.requestId!==r)return;e.status=Jn,e.error=o??a}})}).addMatcher(y,(e,t)=>{const{queries:n}=m(t);for(const[t,r]of Object.entries(n))r?.status!==Gn&&r?.status!==Jn||(e[t]=r)})}}),C=n({name:`${e}/mutations`,initialState:Nr,reducers:{removeMutationResult:{reducer(e,{payload:t}){const n=Dr(t);n in e&&delete e[n]},prepare:c()}},extraReducers(e){e.addCase(a.pending,(e,{meta:t,meta:{requestId:n,arg:r,startedTimeStamp:a}})=>{r.track&&(e[Dr(t)]={requestId:n,status:Xn,endpointName:r.endpointName,startedTimeStamp:a})}).addCase(a.fulfilled,(e,{payload:t,meta:n})=>{n.arg.track&&Tr(e,n,e=>{e.requestId===n.requestId&&(e.status=Gn,e.data=t,e.fulfilledTimeStamp=n.fulfilledTimeStamp)})}).addCase(a.rejected,(e,{payload:t,error:n,meta:r})=>{r.arg.track&&Tr(e,r,e=>{e.requestId===r.requestId&&(e.status=Jn,e.error=t??n)})}).addMatcher(y,(e,t)=>{const{mutations:n}=m(t);for(const[t,r]of Object.entries(n))r?.status!==Gn&&r?.status!==Jn||t===r?.requestId||(e[t]=r)})}}),A=n({name:`${e}/invalidation`,initialState:{tags:{},keys:{}},reducers:{updateProvidedBy:{reducer(e,t){for(const{queryCacheKey:n,providedTags:r}of t.payload){E(e,n);for(const{type:t,id:a}of r){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];r.includes(n)||r.push(n)}e.keys[n]=r}},prepare:c()}},extraReducers(e){e.addCase(S.actions.removeQueryResult,(e,{payload:{queryCacheKey:t}})=>{E(e,t)}).addMatcher(y,(e,t)=>{const{provided:n}=m(t);for(const[t,r]of Object.entries(n.tags??{}))for(const[a,o]of Object.entries(r)){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];for(const t of o){r.includes(t)||r.push(t),e.keys[t]=n.keys[t]}}}).addMatcher(l(d(t),u(t)),(e,t)=>{P(e,[t])}).addMatcher(S.actions.cacheEntriesUpserted.match,(e,t)=>{P(e,t.payload.map(({queryDescription:e,value:t})=>({type:"UNKNOWN",payload:t,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:e}})))})}});function E(e,t){const n=_r(e.keys[t]??[]);for(const r of n){const n=r.type,a=r.id??"__internal_without_id",o=e.tags[n]?.[a];o&&(e.tags[n][a]=_r(o).filter(e=>e!==t))}delete e.keys[t]}function P(e,t){const n=t.map(e=>{const t=Mr(e,"providesTags",s,g),{queryCacheKey:n}=e.meta.arg;return{queryCacheKey:n,providedTags:t}});A.caseReducers.updateProvidedBy(e,A.actions.updateProvidedBy(n))}const x=n({name:`${e}/subscriptions`,initialState:Nr,reducers:{updateSubscriptionOptions(e,t){},unsubscribeQueryResult(e,t){},internal_getRTKQSubscriptions(){}}}),K=n({name:`${e}/internalSubscriptions`,initialState:Nr,reducers:{subscriptionsUpdated:{reducer:(e,t)=>On(e,t.payload),prepare:c()}}}),R=n({name:`${e}/config`,initialState:{online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine,focused:"undefined"==typeof document||"hidden"!==document.visibilityState,middlewareRegistered:!1,...w},reducers:{middlewareRegistered(e,{payload:t}){e.middlewareRegistered="conflict"!==e.middlewareRegistered&&f===t||"conflict"}},extraReducers:e=>{e.addCase(ur,e=>{e.online=!0}).addCase(hr,e=>{e.online=!1}).addCase(lr,e=>{e.focused=!0}).addCase(dr,e=>{e.focused=!1}).addMatcher(y,e=>({...e}))}}),M=h({queries:S.reducer,mutations:C.reducer,provided:A.reducer,subscriptions:K.reducer,config:R.reducer});return{reducer:(e,t)=>M(v.match(t)?void 0:e,t),actions:{...R.actions,...S.actions,...x.actions,...K.actions,...C.actions,...A.actions,resetApiState:v}}}var Or=Symbol.for("RTKQ/skipToken"),Br={status:Wn},Lr=b(Br,()=>{}),Fr=b(Br,()=>{});var zr=WeakMap?new WeakMap:void 0,jr=({endpointName:e,queryArgs:t})=>{let n="";const r=zr?.get(t);if("string"==typeof r)n=r;else{const e=JSON.stringify(t,(e,t)=>(t="bigint"==typeof t?{$bigint:t.toString()}:t,t=f(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t));f(t)&&zr?.set(t,e),n=e}return`${e}(${n})`};function Hr(...e){return function(t){const n=Hn(e=>t.extractRehydrationInfo?.(e,{reducerPath:t.reducerPath??"api"})),o={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...t,extractRehydrationInfo:n,serializeQueryArgs(e){let n=jr;if("serializeQueryArgs"in e.endpointDefinition){const t=e.endpointDefinition.serializeQueryArgs;n=e=>{const n=t(e);return"string"==typeof n?n:jr({...e,queryArgs:n})}}else t.serializeQueryArgs&&(n=t.serializeQueryArgs);return n(e)},tagTypes:[...t.tagTypes||[]]},i={endpointDefinitions:{},batch(e){e()},apiUid:r(),extractRehydrationInfo:n,hasRehydrationInfo:Hn(e=>null!=n(e))},s={injectEndpoints:function(e){const t=e.endpoints({query:e=>({...e,type:fr}),mutation:e=>({...e,type:pr}),infiniteQuery:e=>({...e,type:mr})});for(const[n,r]of Object.entries(t))if(!0!==e.overrideExisting&&n in i.endpointDefinitions){if("throw"===e.overrideExisting)throw new Error(a(39))}else{i.endpointDefinitions[n]=r;for(const e of c)e.injectEndpoint(n,r)}return s},enhanceEndpoints({addTagTypes:e,endpoints:t}){if(e)for(const t of e)o.tagTypes.includes(t)||o.tagTypes.push(t);if(t)for(const[e,n]of Object.entries(t))"function"==typeof n?n(kr(i,e)):Object.assign(kr(i,e)||{},n);return s}},c=e.map(e=>e.init(s,o,i));return s.injectEndpoints({endpoints:t.endpoints})}}function $r(e,...t){return Object.assign(e,...t)}var Vr=({api:e,queryThunk:t,internalState:n,mwApi:r})=>{const a=`${e.reducerPath}/subscriptions`;let o=null,i=null;const{updateSubscriptionOptions:s,unsubscribeQueryResult:c}=e.internalActions,l=()=>n.currentSubscriptions,d={getSubscriptions:l,getSubscriptionCount:e=>{const t=l().get(e);return t?.size??0},isRequestSubscribed:(e,t)=>{const n=l();return!!n?.get(e)?.get(t)}};function u(e){return JSON.parse(JSON.stringify(Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)]))))}return(r,l)=>{if(o||(o=u(n.currentSubscriptions)),e.util.resetApiState.match(r))return o={},n.currentSubscriptions.clear(),i=null,[!0,!1];if(e.internalActions.internal_getRTKQSubscriptions.match(r))return[!1,d];const h=((n,r)=>{if(s.match(r)){const{queryCacheKey:e,requestId:t,options:a}=r.payload,o=n.get(e);return o?.has(t)&&o.set(t,a),!0}if(c.match(r)){const{queryCacheKey:e,requestId:t}=r.payload,a=n.get(e);return a&&a.delete(t),!0}if(e.internalActions.removeQueryResult.match(r))return n.delete(r.payload.queryCacheKey),!0;if(t.pending.match(r)){const{meta:{arg:e,requestId:t}}=r,a=ar(n,e.queryCacheKey,or);return e.subscribe&&a.set(t,e.subscriptionOptions??a.get(t)??{}),!0}let a=!1;if(t.rejected.match(r)){const{meta:{condition:e,arg:t,requestId:o}}=r;if(e&&t.subscribe){const e=ar(n,t.queryCacheKey,or);e.set(o,t.subscriptionOptions??e.get(o)??{}),a=!0}}return a})(n.currentSubscriptions,r);let f=!0;if(h){i||(i=setTimeout(()=>{const t=u(n.currentSubscriptions),[,r]=qn(o,()=>t);l.next(e.internalActions.subscriptionsUpdated(r)),o=t,i=null},500));const s="string"==typeof r.type&&!!r.type.startsWith(a),c=t.rejected.match(r)&&r.meta.condition&&!!r.meta.arg.subscribe;f=!s&&!c}return[f,!1]}},Qr=({reducerPath:e,api:t,queryThunk:n,context:r,internalState:a,selectors:{selectQueryEntry:o,selectConfig:i},getRunningQueryThunk:s,mwApi:c})=>{const{removeQueryResult:d,unsubscribeQueryResult:u,cacheEntriesUpserted:h}=t.internalActions,f=l(u.match,n.fulfilled,n.rejected,h.match);function p(e){const t=a.currentSubscriptions.get(e);if(!t)return!1;return t.size>0}const m={};function y(e){for(const t of e.values())t?.abort?.()}function g(e,t,n){const r=t.getState();for(const a of e){const e=o(r,a);e?.endpointName&&w(a,e.endpointName,t,n)}}function w(e,t,n,a){const i=kr(r,t),c=i?.keepUnusedDataFor??a.keepUnusedDataFor;if(c===1/0)return;const l=Math.max(0,Math.min(c,2147482.647));if(!p(e)){const t=m[e];t&&clearTimeout(t),m[e]=setTimeout(()=>{if(!p(e)){const t=o(n.getState(),e);if(t?.endpointName){const e=n.dispatch(s(t.endpointName,t.originalArgs));e?.abort()}n.dispatch(d({queryCacheKey:e}))}delete m[e]},1e3*l)}}return(e,n)=>{const o=n.getState(),s=i(o);if(f(e)){let t;if(h.match(e))t=e.payload.map(e=>e.queryDescription.queryCacheKey);else{const{queryCacheKey:n}=u.match(e)?e.payload:e.meta.arg;t=[n]}g(t,n,s)}if(t.util.resetApiState.match(e)){for(const[e,t]of Object.entries(m))t&&clearTimeout(t),delete m[e];y(a.runningQueries),y(a.runningMutations)}if(r.hasRehydrationInfo(e)){const{queries:t}=r.extractRehydrationInfo(e);g(Object.keys(t),n,s)}}},Wr=new Error("Promise never resolved before cacheEntryRemoved."),Xr=({api:e,reducerPath:t,context:n,queryThunk:r,mutationThunk:a,internalState:o,selectors:{selectQueryEntry:i,selectApiState:s}})=>{const c=v(r),l=v(a),u=d(r,a),h={},{removeQueryResult:f,removeMutationResult:p,cacheEntriesUpserted:m}=e.internalActions;function y(e,t,n){const r=h[e];r?.valueResolved&&(r.valueResolved({data:t,meta:n}),delete r.valueResolved)}function g(e){const t=h[e];t&&(delete h[e],t.cacheEntryRemoved())}function w(e){const{arg:t,requestId:n}=e.meta,{endpointName:r,originalArgs:a}=t;return[r,a,n]}function b(t,r,a,o,i){const s=kr(n,t),c=s?.onCacheEntryAdded;if(!c)return;const l={},d=new Promise(e=>{l.cacheEntryRemoved=e}),u=Promise.race([new Promise(e=>{l.valueResolved=e}),d.then(()=>{throw Wr})]);u.catch(()=>{}),h[a]=l;const f=e.endpoints[t].select(wr(s)?r:a),p=o.dispatch((e,t,n)=>n),m={...o,getCacheEntry:()=>f(o.getState()),requestId:i,extra:p,updateCachedData:wr(s)?n=>o.dispatch(e.util.updateQueryData(t,r,n)):void 0,cacheDataLoaded:u,cacheEntryRemoved:d},y=c(r,m);Promise.resolve(y).catch(e=>{if(e!==Wr)throw e})}return(n,o,s)=>{const d=function(e){if(c(e))return e.meta.arg.queryCacheKey;if(l(e))return e.meta.arg.fixedCacheKey??e.meta.requestId;return f.match(e)?e.payload.queryCacheKey:p.match(e)?Dr(e.payload):""}(n);function v(e,t,n,r){const a=i(s,t),c=i(o.getState(),t);!a&&c&&b(e,r,t,o,n)}if(r.pending.match(n)){const[e,t,r]=w(n);v(e,d,r,t)}else if(m.match(n))for(const{queryDescription:e,value:t}of n.payload){const{endpointName:r,originalArgs:a,queryCacheKey:o}=e;v(r,o,n.meta.requestId,a),y(o,t,{})}else if(a.pending.match(n)){if(o.getState()[t].mutations[d]){const[e,t,r]=w(n);b(e,t,d,o,r)}}else if(u(n))y(d,n.payload,n.meta.baseQueryMeta);else if(f.match(n)||p.match(n))g(d);else if(e.util.resetApiState.match(n))for(const e of Object.keys(h))g(e)}},Gr=({api:e,context:{apiUid:t},reducerPath:n})=>(n,r)=>{e.util.resetApiState.match(n)&&r.dispatch(e.internalActions.middlewareRegistered(t))},Jr=({reducerPath:e,context:t,context:{endpointDefinitions:n},mutationThunk:r,queryThunk:a,api:o,assertTagType:i,refetchQuery:s,internalState:c})=>{const{removeQueryResult:h}=o.internalActions,f=l(d(r),u(r)),p=l(d(a,r),y(a,r));let m=[],g=0;function w(n,r){const a=r.getState(),i=a[e];if(m.push(...n),"delayed"===i.config.invalidationBehavior&&g>0)return;const l=m;if(m=[],0===l.length)return;const d=o.util.selectInvalidatedBy(a,l);t.batch(()=>{const e=Array.from(d.values());for(const{queryCacheKey:t}of e){const e=i.queries[t],n=ar(c.currentSubscriptions,t,or);e&&(0===n.size?r.dispatch(h({queryCacheKey:t})):e.status!==Wn&&r.dispatch(s(e)))}})}return(e,t)=>{(a.pending.match(e)||r.pending.match(e))&&g++,p(e)&&(g=Math.max(0,g-1)),f(e)?w(Mr(e,"invalidatesTags",n,i),t):p(e)?w([],t):o.util.invalidateTags.match(e)&&w(br(e.payload,void 0,void 0,void 0,void 0,i),t)}},Yr=({reducerPath:e,queryThunk:t,api:n,refetchQuery:r,internalState:a})=>{const{currentPolls:o,currentSubscriptions:i}=a,s=new Set;let c=null;function l(e,t){s.add(e),c||(c=setTimeout(()=>{for(const e of s)u({queryCacheKey:e},t);s.clear(),c=null},0))}function d({queryCacheKey:t},n){const a=n.getState()[e],s=a.queries[t],c=i.get(t);if(!s||s.status===Wn)return;const{lowestPollingInterval:l,skipPollingIfUnfocused:u}=f(c);if(!Number.isFinite(l))return;const h=o.get(t);h?.timeout&&(clearTimeout(h.timeout),h.timeout=void 0);const p=Date.now()+l;o.set(t,{nextPollTimestamp:p,pollingInterval:l,timeout:setTimeout(()=>{!a.config.focused&&u||n.dispatch(r(s)),d({queryCacheKey:t},n)},l)})}function u({queryCacheKey:t},n){const r=n.getState()[e].queries[t],a=i.get(t);if(!r||r.status===Wn)return;const{lowestPollingInterval:s}=f(a);if(!Number.isFinite(s))return void h(t);const c=o.get(t),l=Date.now()+s;(!c||l<c.nextPollTimestamp)&&d({queryCacheKey:t},n)}function h(e){const t=o.get(e);t?.timeout&&clearTimeout(t.timeout),o.delete(e)}function f(e=new Map){let t=!1,n=Number.POSITIVE_INFINITY;for(const r of e.values())r.pollingInterval&&(n=Math.min(r.pollingInterval,n),t=r.skipPollingIfUnfocused||t);return{lowestPollingInterval:n,skipPollingIfUnfocused:t}}return(e,r)=>{(n.internalActions.updateSubscriptionOptions.match(e)||n.internalActions.unsubscribeQueryResult.match(e))&&l(e.payload.queryCacheKey,r),(t.pending.match(e)||t.rejected.match(e)&&e.meta.condition)&&l(e.meta.arg.queryCacheKey,r),(t.fulfilled.match(e)||t.rejected.match(e)&&!e.meta.condition)&&d(e.meta.arg,r),n.util.resetApiState.match(e)&&(!function(){for(const e of o.keys())h(e)}(),c&&(clearTimeout(c),c=null),s.clear())}},Zr=({api:e,context:t,queryThunk:n,mutationThunk:r})=>{const a=g(n,r),o=y(n,r),i=d(n,r),s={};return(n,r)=>{if(a(n)){const{requestId:a,arg:{endpointName:o,originalArgs:i}}=n.meta,c=kr(t,o),l=c?.onQueryStarted;if(l){const t={},n=new Promise((e,n)=>{t.resolve=e,t.reject=n});n.catch(()=>{}),s[a]=t;const d=e.endpoints[o].select(wr(c)?i:a),u=r.dispatch((e,t,n)=>n),h={...r,getCacheEntry:()=>d(r.getState()),requestId:a,extra:u,updateCachedData:wr(c)?t=>r.dispatch(e.util.updateQueryData(o,i,t)):void 0,queryFulfilled:n};l(i,h)}}else if(i(n)){const{requestId:e,baseQueryMeta:t}=n.meta;s[e]?.resolve({data:n.payload,meta:t}),delete s[e]}else if(o(n)){const{requestId:e,rejectedWithValue:t,baseQueryMeta:r}=n.meta;s[e]?.reject({error:n.payload??n.error,isUnhandledError:!t,meta:r}),delete s[e]}}};function ea(e){const{reducerPath:t,queryThunk:n,api:r,context:a,getInternalState:o}=e,{apiUid:s}=a,c={invalidateTags:i(`${t}/invalidateTags`)},l=e=>e.type.startsWith(`${t}/`),d=[Gr,Qr,Jr,Yr,Xr,Zr];return{middleware:n=>{let i=!1;const c=o(n.dispatch),h={...e,internalState:c,refetchQuery:u,isThisApiSliceAction:l,mwApi:n},f=d.map(e=>e(h)),p=Vr(h),m=(({reducerPath:e,context:t,api:n,refetchQuery:r,internalState:a})=>{const{removeQueryResult:o}=n.internalActions;function i(n,i){const s=n.getState()[e],c=s.queries,l=a.currentSubscriptions;t.batch(()=>{for(const e of l.keys()){const t=c[e],a=l.get(e);if(!a||!t)continue;const d=[...a.values()];(d.some(e=>!0===e[i])||d.every(e=>void 0===e[i])&&s.config[i])&&(0===a.size?n.dispatch(o({queryCacheKey:e})):t.status!==Wn&&n.dispatch(r(t)))}})}return(e,t)=>{lr.match(e)&&i(t,"refetchOnFocus"),ur.match(e)&&i(t,"refetchOnReconnect")}})(h);return e=>o=>{if(!w(o))return e(o);i||(i=!0,n.dispatch(r.internalActions.middlewareRegistered(s)));const c={...n,next:e},d=n.getState(),[u,h]=p(o,c,d);let y;if(y=u?e(o):h,n.getState()[t]&&(m(o,c,d),l(o)||a.hasRehydrationInfo(o)))for(const e of f)e(o,c,d);return y}},actions:c};function u(t){return e.api.endpoints[t.endpointName].initiate(t.originalArgs,{subscribe:!1,forceRefetch:!0})}}var ta=Symbol(),na=Hr((({createSelector:e=o}={})=>({name:ta,init(t,{baseQuery:n,tagTypes:r,reducerPath:a,serializeQueryArgs:o,keepUnusedDataFor:i,refetchOnMountOrArgChange:c,refetchOnFocus:l,refetchOnReconnect:u,invalidationBehavior:h,onSchemaFailure:f,catchSchemaFailure:p,skipSchemaValidation:w},b){Tn();const v=e=>e;Object.assign(t,{reducerPath:a,endpoints:{},internalActions:{onOnline:ur,onOffline:hr,onFocus:lr,onFocusLost:dr},util:{}});const k=function({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=e=>Lr,a=e=>Fr;return{buildQuerySelector:function(e,t){return l(e,t,o)},buildInfiniteQuerySelector:function(e,t){const{infiniteQueryOptions:n}=t;return l(e,t,function(e){const t={...e,...Yn(e.status)},{isLoading:r,isError:a,direction:o}=t,i="forward"===o,s="backward"===o;return{...t,hasNextPage:d(n,t.data,t.originalArgs),hasPreviousPage:u(n,t.data,t.originalArgs),isFetchingNextPage:r&&i,isFetchingPreviousPage:r&&s,isFetchNextPageError:a&&i,isFetchPreviousPageError:a&&s}})},buildMutationSelector:function(){return e=>{let t;return t="object"==typeof e?Dr(e)??Or:e,n(t===Or?a:e=>i(e)?.mutations?.[t]??Fr,o)}},selectInvalidatedBy:function(e,n){const r=e[t],a=new Set,o=tr(n,nr,vr);for(const e of o){const t=r.provided.tags[e.type];if(!t)continue;let n=(void 0!==e.id?t[e.id]:Object.values(t).flat())??[];for(const e of n)a.add(e)}return Array.from(a.values()).flatMap(e=>{const t=r.queries[e];return t?{queryCacheKey:e,endpointName:t.endpointName,originalArgs:t.originalArgs}:[]})},selectCachedArgsForQuery:function(e,t){return tr(Object.values(s(e)),e=>e?.endpointName===t&&e.status!==Wn,e=>e.originalArgs)},selectApiState:i,selectQueries:s,selectMutations:function(e){return i(e)?.mutations},selectQueryEntry:c,selectConfig:function(e){return i(e)?.config}};function o(e){return{...e,...Yn(e.status)}}function i(e){return e[t]}function s(e){return i(e)?.queries}function c(e,t){return s(e)?.[t]}function l(t,a,o){return i=>{if(i===Or)return n(r,o);const s=e({queryArgs:i,endpointDefinition:a,endpointName:t});return n(e=>c(e,s)??Lr,o)}}function d(e,t,n){return!!t&&null!=Kr(e,t,n)}function u(e,t,n){return!(!t||!e.getPreviousPageParam)&&null!=Rr(e,t,n)}}({serializeQueryArgs:o,reducerPath:a,createSelector:e}),{selectInvalidatedBy:I,selectCachedArgsForQuery:S,buildQuerySelector:C,buildInfiniteQuerySelector:A,buildMutationSelector:E}=k;$r(t.util,{selectInvalidatedBy:I,selectCachedArgsForQuery:S});const{queryThunk:P,infiniteQueryThunk:x,mutationThunk:K,patchQueryData:R,updateQueryData:M,upsertQueryData:_,prefetch:U,buildMatchThunkActions:D}=function({reducerPath:e,baseQuery:t,context:{endpointDefinitions:n},serializeQueryArgs:r,api:a,assertTagType:o,selectors:i,onSchemaFailure:c,catchSchemaFailure:l,skipSchemaValidation:u}){function h(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}function f(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}const p=(e,t)=>e.query&&e[t]?e[t]:Pr,w=async(e,{signal:r,abort:a,rejectWithValue:o,fulfillWithValue:s,dispatch:d,getState:m,extra:y})=>{const g=n[e.endpointName],{metaSchema:w,skipSchemaValidation:v=u}=g,k=e.type===fr;try{let I=Pr;const S={signal:r,abort:a,dispatch:d,getState:m,extra:y,endpoint:e.endpointName,type:e.type,forced:k?b(e,m()):void 0,queryCacheKey:k?e.queryCacheKey:void 0},C=k?e[Ir]:void 0;let A;const E=async(t,n,r,a)=>{if(null==n&&t.pages.length)return Promise.resolve({data:t});const o={queryArg:e.originalArgs,pageParam:n},i=await P(o),s=a?h:f;return{data:{pages:s(t.pages,i.data,r),pageParams:s(t.pageParams,n,r)},meta:i.meta}};async function P(e){let n;const{extraOptions:r,argSchema:a,rawResponseSchema:o,responseSchema:i}=g;if(a&&!Ar(v,"arg")&&(e=await Er(a,e,"argSchema",{})),C?n=C():g.query?(I=p(g,"transformResponse"),n=await t(g.query(e),S,r)):n=await g.queryFn(e,S,r,e=>t(e,S,r)),n.error)throw new ir(n.error,n.meta);let{data:s}=n;o&&!Ar(v,"rawResponse")&&(s=await Er(o,n.data,"rawResponseSchema",n.meta));let c=await I(s,n.meta,e);return i&&!Ar(v,"response")&&(c=await Er(i,c,"responseSchema",n.meta)),{...n,data:c}}if(k&&"infiniteQueryOptions"in g){const{infiniteQueryOptions:x}=g,{maxPages:K=1/0}=x,R=e.refetchCachedPages??x.refetchCachedPages??!0;let M;const _={pages:[],pageParams:[]},U=i.selectQueryEntry(m(),e.queryCacheKey)?.data,D=b(e,m())&&!e.direction||!U?_:U;if("direction"in e&&e.direction&&D.pages.length){const T="backward"===e.direction,N=(T?Rr:Kr)(x,D,e.originalArgs);M=await E(D,N,K,T)}else{const{initialPageParam:q=x.initialPageParam}=e,O=U?.pageParams??[],B=O[0]??q,L=O.length;if(M=await E(D,B,K),C&&(M={data:M.data.pages[0]}),R)for(let F=1;F<L;F++){const z=Kr(x,M.data,e.originalArgs);M=await E(M.data,z,K)}}A=M}else A=await P(e.originalArgs);return w&&!Ar(v,"meta")&&A.meta&&(A.meta=await Er(w,A.meta,"metaSchema",A.meta)),s(A.data,xr({fulfilledTimeStamp:Date.now(),baseQueryMeta:A.meta}))}catch(j){let H=j;if(H instanceof ir){let $=p(g,"transformErrorResponse");const{rawErrorResponseSchema:V,errorResponseSchema:Q}=g;let{value:W,meta:X}=H;try{V&&!Ar(v,"rawErrorResponse")&&(W=await Er(V,W,"rawErrorResponseSchema",X)),w&&!Ar(v,"meta")&&(X=await Er(w,X,"metaSchema",X));let G=await $(W,X,e.originalArgs);return Q&&!Ar(v,"errorResponse")&&(G=await Er(Q,G,"errorResponseSchema",X)),o(G,xr({baseQueryMeta:X}))}catch(J){H=J}}try{if(H instanceof Cr){const Y={endpoint:e.endpointName,arg:e.originalArgs,type:e.type,queryCacheKey:k?e.queryCacheKey:void 0};g.onSchemaFailure?.(H,Y),c?.(H,Y);const{catchSchemaFailure:Z=l}=g;if(Z)return o(Z(H,Y),xr({baseQueryMeta:H._bqMeta}))}}catch(ee){H=ee}throw console.error(H),H}};function b(e,t){const n=i.selectQueryEntry(t,e.queryCacheKey),r=i.selectConfig(t).refetchOnMountOrArgChange,a=n?.fulfilledTimeStamp,o=e.forceRefetch??(e.subscribe&&r);return!!o&&(!0===o||(Number(new Date)-Number(a))/1e3>=o)}const v=()=>s(`${e}/executeQuery`,w,{getPendingMeta({arg:e}){const t=n[e.endpointName];return xr({startedTimeStamp:Date.now(),...gr(t)?{direction:e.direction}:{}})},condition(e,{getState:t}){const r=t(),a=i.selectQueryEntry(r,e.queryCacheKey),o=a?.fulfilledTimeStamp,s=e.originalArgs,c=a?.originalArgs,l=n[e.endpointName],d=e.direction;return!(!Sr(e)&&("pending"===a?.status||!b(e,r)&&(!yr(l)||!l?.forceRefetch?.({currentArg:s,previousArg:c,endpointState:a,state:r}))&&o&&!d))},dispatchConditionRejection:!0}),k=v(),I=v(),S=s(`${e}/executeMutation`,w,{getPendingMeta:()=>xr({startedTimeStamp:Date.now()})});function C(e){return t=>t?.meta?.arg?.endpointName===e}return{queryThunk:k,mutationThunk:S,infiniteQueryThunk:I,prefetch:(e,t,n={})=>(r,o)=>{const i=(e=>"force"in e)(n)&&n.force,s=(e=>"ifOlderThan"in e)(n)&&n.ifOlderThan,c=(n=!0)=>{const r={forceRefetch:n,subscribe:!1};return a.endpoints[e].initiate(t,r)},l=a.endpoints[e].select(t)(o());if(i)r(c());else if(s){const e=l?.fulfilledTimeStamp;if(!e)return void r(c());(Number(new Date)-Number(new Date(e)))/1e3>=s&&r(c())}else r(c(!1))},updateQueryData:(e,t,n,r=!0)=>(o,i)=>{const s=a.endpoints[e].select(t)(i()),c={patches:[],inversePatches:[],undo:()=>o(a.util.patchQueryData(e,t,c.inversePatches,r))};if(s.status===Wn)return c;let l;if("data"in s)if(qt(s.data)){const[e,t,r]=qn(s.data,n);c.patches.push(...t),c.inversePatches.push(...r),l=e}else l=n(s.data),c.patches.push({op:"replace",path:[],value:l}),c.inversePatches.push({op:"replace",path:[],value:s.data});return 0===c.patches.length||o(a.util.patchQueryData(e,t,c.patches,r)),c},upsertQueryData:(e,t,n)=>r=>r(a.endpoints[e].initiate(t,{subscribe:!1,forceRefetch:!0,[Ir]:()=>({data:n})})),patchQueryData:(e,t,i,s)=>(c,l)=>{const d=n[e],u=r({queryArgs:t,endpointDefinition:d,endpointName:e});if(c(a.internalActions.queryResultPatched({queryCacheKey:u,patches:i})),!s)return;const h=a.endpoints[e].select(t)(l()),f=br(d.providesTags,h.data,void 0,t,{},o);c(a.internalActions.updateProvidedBy([{queryCacheKey:u,providedTags:f}]))},buildMatchThunkActions:function(e,t){return{matchPending:m(g(e),C(t)),matchFulfilled:m(d(e),C(t)),matchRejected:m(y(e),C(t))}}}}({baseQuery:n,reducerPath:a,context:b,api:t,serializeQueryArgs:o,assertTagType:v,selectors:k,onSchemaFailure:f,catchSchemaFailure:p,skipSchemaValidation:w}),{reducer:T,actions:N}=qr({context:b,queryThunk:P,mutationThunk:K,serializeQueryArgs:o,reducerPath:a,assertTagType:v,config:{refetchOnFocus:l,refetchOnReconnect:u,refetchOnMountOrArgChange:c,keepUnusedDataFor:i,reducerPath:a,invalidationBehavior:h}});$r(t.util,{patchQueryData:R,updateQueryData:M,upsertQueryData:_,prefetch:U,resetApiState:N.resetApiState,upsertQueryEntries:N.cacheEntriesUpserted}),$r(t.internalActions,N);const q=new WeakMap,O=e=>ar(q,e,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:B,buildInitiateInfiniteQuery:L,buildInitiateMutation:F,getRunningMutationThunk:z,getRunningMutationsThunk:j,getRunningQueriesThunk:H,getRunningQueryThunk:$}=function({serializeQueryArgs:e,queryThunk:t,infiniteQueryThunk:n,mutationThunk:r,api:a,context:o,getInternalState:i}){const s=e=>i(e)?.runningQueries,c=e=>i(e)?.runningMutations,{unsubscribeQueryResult:l,removeMutationResult:d,updateSubscriptionOptions:u}=a.internalActions;return{buildInitiateQuery:function(e,t){return h(e,t)},buildInitiateInfiniteQuery:function(e,t){return h(e,t)},buildInitiateMutation:function(e){return(t,{track:n=!0,fixedCacheKey:a}={})=>(o,i)=>{const s=r({type:"mutation",endpointName:e,originalArgs:t,track:n,fixedCacheKey:a}),l=o(s),{requestId:u,abort:h,unwrap:f}=l,p=(m=e=>({error:e}),l.unwrap().then(e=>({data:e})).catch(m));var m;const y=Object.assign(p,{arg:l.arg,requestId:u,abort:h,unwrap:f,reset:()=>{o(d({requestId:u,fixedCacheKey:a}))}}),g=c(o);return g.set(u,y),y.then(()=>{g.delete(u)}),a&&(g.set(a,y),y.then(()=>{g.get(a)===y&&g.delete(a)})),y}},getRunningQueryThunk:function(t,n){return r=>{const a=kr(o,t),i=e({queryArgs:n,endpointDefinition:a,endpointName:t});return s(r)?.get(i)}},getRunningMutationThunk:function(e,t){return e=>c(e)?.get(t)},getRunningQueriesThunk:function(){return e=>rr(s(e))},getRunningMutationsThunk:function(){return e=>rr(c(e))}};function h(r,o){const i=(c,{subscribe:d=!0,forceRefetch:h,subscriptionOptions:f,[Ir]:p,...m}={})=>(y,g)=>{const w=e({queryArgs:c,endpointDefinition:o,endpointName:r});let b;const v={...m,type:fr,subscribe:d,forceRefetch:h,subscriptionOptions:f,endpointName:r,originalArgs:c,queryCacheKey:w,[Ir]:p};if(yr(o))b=t(v);else{const{direction:e,initialPageParam:t,refetchCachedPages:r}=m;b=n({...v,direction:e,initialPageParam:t,refetchCachedPages:r})}const k=a.endpoints[r].select(c),I=y(b),S=k(g()),{requestId:C,abort:A}=I,E=S.requestId!==C,P=s(y)?.get(w),x=()=>k(g()),K=Object.assign(p?I.then(x):E&&!P?Promise.resolve(S):Promise.all([P,I]).then(x),{arg:c,requestId:C,subscriptionOptions:f,queryCacheKey:w,abort:A,async unwrap(){const e=await K;if(e.isError)throw e.error;return e.data},refetch:e=>y(i(c,{subscribe:!1,forceRefetch:!0,...e})),unsubscribe(){d&&y(l({queryCacheKey:w,requestId:C}))},updateSubscriptionOptions(e){K.subscriptionOptions=e,y(u({endpointName:r,requestId:C,queryCacheKey:w,options:e}))}});if(!P&&!E&&!p){const e=s(y);e.set(w,K),K.then(()=>{e.delete(w)})}return K};return i}}({queryThunk:P,mutationThunk:K,infiniteQueryThunk:x,api:t,serializeQueryArgs:o,context:b,getInternalState:O});$r(t.util,{getRunningMutationThunk:z,getRunningMutationsThunk:j,getRunningQueryThunk:$,getRunningQueriesThunk:H});const{middleware:V,actions:Q}=ea({reducerPath:a,context:b,queryThunk:P,mutationThunk:K,infiniteQueryThunk:x,api:t,assertTagType:v,selectors:k,getRunningQueryThunk:$,getInternalState:O});return $r(t.util,Q),$r(t,{reducer:T,middleware:V}),{name:ta,injectEndpoint(e,n){const r=t,a=r.endpoints[e]??={};yr(n)&&$r(a,{name:e,select:C(e,n),initiate:B(e,n)},D(P,e)),n.type===pr&&$r(a,{name:e,select:E(),initiate:F(e)},D(K,e)),gr(n)&&$r(a,{name:e,select:A(e,n),initiate:L(e,n)},D(P,e))}}}}))());const ra="0123456789abcdef",aa=new Array(64),oa=new Array(128),ia=e=>new Promise(t=>{let n=0;const r=e.length;for(let t=0;t<r;t++)n+=e[t].length;const a=new Uint8Array(n);let o=0;for(const t of e)a.set(t,o),o+=t.length;t(a)}),sa=(e,t)=>new Promise(n=>{const r=e.length;if(r!==t.length)return void n(!1);let a=0;for(let n=0;n<r;n++)a|=e[n]^t[n];n(0===a)}),ca=e=>{const t=e.length,n=t===N?oa:32===t?aa:new Array(2*t);let r=0;for(let a=0;a<t;a++){const t=e[a];n[r++]=ra[t>>4],n[r++]=ra[15&t]}return n.join("")},la=e=>{if(0===(e=e.replace(/^0x/,"")).length)throw new Error("No hex characters in string");const t=/[^0-9a-f]/i.exec(e);if(t)throw new Error(`Found non-hex characters ${t[0]}`);e.length%2!=0&&(e="0"+e);const n=e.match(/[\dA-F]{2}/gi);if(!n)throw new Error("No hex characters in string");const r=n.length,a=new Uint8Array(r);for(let e=0;e<r;e++)a[e]=parseInt(n[e],16);return a},da=(e,t,n)=>{t=t??32,n=n??16384;const r=65536,a=Math.ceil((e+1048576)/r);if(a>n)throw new Error(`Memory required is ${String(a*r)} bytes while declared maximum is ${String(n*r)} bytes`);return a<t?t:a};var ua=()=>{const e=(L+F)*Uint8Array.BYTES_PER_ELEMENT,t=da(e);return new WebAssembly.Memory({initial:t,maximum:t})},ha=()=>{const e=(X+G)*Uint8Array.BYTES_PER_ELEMENT,t=da(e);return new WebAssembly.Memory({initial:t,maximum:t})},fa=()=>{const e=(L+F+B)*Uint8Array.BYTES_PER_ELEMENT,t=da(e);return new WebAssembly.Memory({initial:t,maximum:t})},pa=e=>{const t=(e+O+F+N)*Uint8Array.BYTES_PER_ELEMENT,n=da(t);return new WebAssembly.Memory({initial:n,maximum:n})},ma=e=>{const t=(e+O+L)*Uint8Array.BYTES_PER_ELEMENT,n=da(t);return new WebAssembly.Memory({initial:n,maximum:n})},ya=()=>{const e=da(0);return new WebAssembly.Memory({initial:e,maximum:e})},ga=e=>{const t=da((2*e+3)*N);return new WebAssembly.Memory({initial:t,maximum:t})},wa=e=>{const t=da(e*N+e*(N+1)+3*N);return new WebAssembly.Memory({initial:t,maximum:t})},ba=e=>{const t=(78643200+e+B+$)*Uint8Array.BYTES_PER_ELEMENT,n=da(t);return new WebAssembly.Memory({initial:n,maximum:n})};function va(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ka,Ia={exports:{}};var Sa=(ka||(ka=1,function(e){var t,n=(t=globalThis.document?.currentScript?.src,async function(e={}){var n=e,r=!!globalThis.window,a=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process,a&&(t=self.location.href);var o,i,s="";if(r||a){try{s=new URL(".",t).href}catch{}a&&(i=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),o=async e=>{var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)}}console.log.bind(console);var c,l=console.error.bind(console),d=!1;function u(e,t,n){const r=e.BYTES_PER_ELEMENT,a=t*r;if(t<=0&&I(`segmentation fault ${n} ${r} bytes at address ${a}`),v){var o=U(0);a+r>o&&I(`segmentation fault, exceeded the top of the available dynamic heap when ${n} ${r} bytes at address ${a}. DYNAMICTOP=${o}`),o<D()&&I(`brk >= _emscripten_stack_get_base() (brk=${o}, _emscripten_stack_get_base()=${D()})`),o>b.buffer.byteLength&&I(`brk <= wasmMemory.buffer.byteLength (brk=${o}, wasmMemory.buffer.byteLength=${b.buffer.byteLength})`)}return t}var h,f,p,m,y,g,w,b,v=!1;function k(){if(!m?.buffer?.resizable){var e=b.buffer;m=new Int8Array(e),w=new Uint8Array(e),f=new Int32Array(e),g=new Uint32Array(e),y=new Float64Array(e),p=new BigInt64Array(e),new BigUint64Array(e)}}function I(e){throw l(e=`Aborted(${e})`),d=!0,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}function S(){return s+"libcrypto.wasm"}async function C(e){if(!c)try{var t=await o(e);return new Uint8Array(t)}catch{}return function(e){if(e==h&&c)return new Uint8Array(c);if(i)return i(e);throw"both async and sync fetching of the wasm failed"}(e)}async function A(e,t,n){if(!e)try{var r=fetch(t,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(r,n)}catch(e){l(`wasm streaming compile failed: ${e}`),l("falling back to ArrayBuffer instantiation")}return async function(e,t){try{var n=await C(e);return await WebAssembly.instantiate(n,t)}catch(e){l(`failed to asynchronously prepare wasm: ${e}`),I(e)}}(t,n)}var E=globalThis.TextDecoder&&new TextDecoder,P=(e,t,n)=>e?((e,t=0,n)=>{var r=((e,t,n)=>{for(var r=t+n;e[t]&&!(t>=r);)++t;return t})(e,t,n);if(r-t>16&&e.buffer&&E)return E.decode(e.subarray(t,r));for(var a="";t<r;){var o=e[t++];if(128&o){var i=63&e[t++];if(192!=(224&o)){var s=63&e[t++];if((o=224==(240&o)?(15&o)<<12|i<<6|s:(7&o)<<18|i<<12|s<<6|63&e[t++])<65536)a+=String.fromCharCode(o);else{var c=o-65536;a+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else a+=String.fromCharCode((31&o)<<6|i)}else a+=String.fromCharCode(o)}return a})(w,e,t):"",x=[],K=(e,t,n)=>{var r=((e,t)=>{var n;for(x.length=0;n=w[u(w,e++,"loading")];){var r=105!=n;t+=(r&=112!=n)&&t%8?4:0,x.push(112==n?g[u(g,t>>2,"loading")]:106==n?p[u(p,t>>3,"loading")]:105==n?f[u(f,t>>2,"loading")]:y[u(y,t>>3,"loading")]),t+=r?8:4}return x})(t,n);return N[e](...r)},R=e=>{I("OOM")},M=(e,t)=>Math.ceil(e/t)*t,_=e=>{var t=(e-b.buffer.byteLength+65535)/65536|0;try{return b.grow(t),k(),1}catch(e){}};!function(){if(n.wasmMemory)b=n.wasmMemory;else{var e=n.INITIAL_MEMORY||2097152;b=new WebAssembly.Memory({initial:e/65536,maximum:16384})}k()}(),n.wasmBinary&&(c=n.wasmBinary);var U,D,T,N={38164:()=>n.getRandomValue(),38200:()=>{if(void 0===n.getRandomValue)try{var e="object"==typeof window?window:self,t=void 0!==e.crypto?e.crypto:e.msCrypto;t=void 0===t?a:t;var r=function(){var e=new Uint32Array(1);return t.getRandomValues(e),e[0]>>>0};r(),n.getRandomValue=r}catch(e){try{var a=require("crypto"),o=function(){var e=a.randomBytes(4);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0};o(),n.getRandomValue=o}catch(e){throw"No secure random number generator found"}}}},q={e:(e,t,n,r)=>I(`Assertion failed: ${P(e)}, at: `+[t?P(t):"unknown filename",n,r?P(r):"unknown function"]),g:()=>I(""),c:function(){I("alignment fault")},d:(e,t,n)=>K(e,t,n),f:e=>{var t=w.length,n=1073741824;(e>>>=0)>n&&R();for(var r=1;r<=4;r*=2){var a=t*(1+.2/r);a=Math.min(a,e+100663296);var o=Math.min(n,M(Math.max(e,a),65536));if(_(o))return!0}R()},a:b,b:function(){I("segmentation fault")}};return T=await async function(){function e(e){return function(e){n._crypto_init=e.i,n._argon2=e.j,n._keypair_from_seed=e.k,n._keypair_from_secret_key=e.l,n._sign=e.m,n._verify=e.n,n._get_merkle_root=e.o,n._get_merkle_proof=e.p,n._get_merkle_root_from_proof=e.q,n._verify_merkle_proof=e.r,n._cpace_ristretto255_from_hash=e.s,n._cpace_ristretto255_scalarmult=e.t,n._cpace_ristretto255_scalar_random=e.u,n._x25519_keypair=e.v,n._x25519_dh=e.w,n._hkdf_sha512_extract=e.x,n._hkdf_sha512_expand=e.y,n._encrypt_chachapoly_symmetric=e.z,n._decrypt_chachapoly_symmetric=e.A,n._receive_message_with_key=e.B,n._sha512_init=e.C,n._sha512_update=e.D,n._sha512_final=e.E,n._mlkem512_keypair=e.F,n._mlkem512_encaps=e.G,n._mlkem512_decaps=e.H,n._mlkem768_keypair=e.I,n._mlkem768_encaps=e.J,n._mlkem768_decaps=e.K,n._mlkem1024_keypair=e.L,n._mlkem1024_encaps=e.M,n._mlkem1024_decaps=e.N,n._free=e.O,n._malloc=e.P,U=e.Q,D=e.R,e.__indirect_function_table}(T=e.exports),T}var t={a:q};h??=S();var r=function(t){return e(t.instance)}(await A(c,h,t));return r}(),await async function(){d||(v=!0,T.h())}(),n});e.exports=n,e.exports.default=n}(Ia)),Ia.exports),Ca=va(Sa);const Aa=new Uint32Array(1),Ea=()=>{const e=globalThis.crypto;if("function"!=typeof e?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");try{return e.getRandomValues(Aa),Aa[0]>>>0}finally{Aa[0]=0}},Pa=(e,t=e=>{const t=globalThis.crypto;if("function"!=typeof t?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");t.getRandomValues(e)})=>{if(!(e instanceof Uint8Array))throw new TypeError("random: destination must be a Uint8Array");const n=new Uint8Array(e.byteLength);try{t(n),e.set(n)}finally{n.fill(0)}};if("object"!=typeof WebAssembly)throw new Error("no native wasm support detected");const xa="0.14.3";let Ka=new URL(`https://cdn.p2party.com/@${xa}/libcrypto.wasm`),Ra=!1;const Ma={integrity:"sha384-pBMyUqQ3KBztxgeJMgDFZeohfj9QlAFNwt4/gRlqT0vlZ2kbkKxv+q5DwbZOBuUP"},_a=e=>{if(Ra)throw new Error("WASM source cannot change after cryptography has loaded");const t=e instanceof URL?new URL(e.href):new URL(e);if("https:"!==t.protocol&&"http:"!==t.protocol)throw new TypeError("WASM source must use http: or https:");Ka=t},Ua=async e=>{Ra=!0;const t=await(async()=>{const e=await fetch(Ka,Ma);if(!e.ok)throw new Error(`Unable to load p2party ${xa} WASM: HTTP ${String(e.status)}`);return await e.arrayBuffer()})();return await Ca({wasmBinary:t,wasmMemory:e,getRandomValue:Ea})},Da=(e,t)=>{t.fill(0),e._free(t.byteOffset)},Ta=async e=>{const t=e?.wasmMemory??ua(),n=e??await Ua(t),r=n._malloc(L),a=new Uint8Array(t.buffer,r,L),o=n._malloc(F),i=new Uint8Array(t.buffer,o,F),s=n._malloc(B),c=new Uint8Array(t.buffer,s,B);try{Pa(c);if(0!==n._keypair_from_seed(a.byteOffset,i.byteOffset,c.byteOffset))throw new Error("An unexpected error occured.");return{publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(i)}}finally{n._free(r),Da(n,i),Da(n,c)}},Na=async(e,t,n)=>{if(t.length!==F)throw new Error(`Ed25519 secret key must be ${String(F)} bytes`);const r=e.length,a=n?n.wasmMemory:pa(r),o=n??await Ua(a),i=o._malloc(Math.max(r*Uint8Array.BYTES_PER_ELEMENT,1)),s=new Uint8Array(a.buffer,i,r*Uint8Array.BYTES_PER_ELEMENT);s.set(e);const c=o._malloc(O),l=new Uint8Array(a.buffer,c,O),d=o._malloc(F),u=new Uint8Array(a.buffer,d,F);u.set(t);try{if(0!==o._sign(r,s.byteOffset,u.byteOffset,l.byteOffset))throw new Error("Could not sign with Ed25519");return Uint8Array.from(l)}finally{o._free(i),o._free(c),Da(o,u)}},qa=async(e,t,n,r)=>{const a=e.length,o=r?r.wasmMemory:ma(a),i=r??await Ua(o),s=i._malloc(a*Uint8Array.BYTES_PER_ELEMENT),c=new Uint8Array(o.buffer,s,a*Uint8Array.BYTES_PER_ELEMENT);c.set(e);const l=i._malloc(O),d=new Uint8Array(o.buffer,l,O);d.set(t);const u=i._malloc(L),h=new Uint8Array(o.buffer,u,L);h.set(n);const f=i._verify(a,c.byteOffset,h.byteOffset,d.byteOffset);return i._free(s),i._free(l),i._free(u),0===f},Oa=/^[0-9a-f]{64}$/,Ba=e=>"string"==typeof e&&Oa.test(e),La=(e,t="Ed25519 identity")=>{if(!Ba(e))throw new Error(`${t} must be 32-byte lowercase hexadecimal`)},Fa=(e,t)=>{if(La(e,"Self Ed25519 identity"),La(t,"Peer Ed25519 identity"),e===t)throw new Error("Cannot assign a protocol role to the same Ed25519 identity");return e<t},za='const e=(e,t)=>t.some(t=>e instanceof t);let t,a;const n=new WeakMap,r=new WeakMap,o=new WeakMap;let i={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return n.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return d(e[t])},set:(e,t,a)=>(e[t]=a,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function s(e){i=e(i)}function c(e){return(a||(a=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(u(this),t),d(this.request)}:function(...t){return d(e.apply(u(this),t))}}function l(a){return"function"==typeof a?c(a):(a instanceof IDBTransaction&&function(e){if(n.has(e))return;const t=new Promise((t,a)=>{const n=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",o),e.removeEventListener("abort",o)},r=()=>{t(),n()},o=()=>{a(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",r),e.addEventListener("error",o),e.addEventListener("abort",o)});n.set(e,t)}(a),e(a,t||(t=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(a,i):a)}function d(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,a)=>{const n=()=>{e.removeEventListener("success",r),e.removeEventListener("error",o)},r=()=>{t(d(e.result)),n()},o=()=>{a(e.error),n()};e.addEventListener("success",r),e.addEventListener("error",o)});return o.set(t,e),t}(e);if(r.has(e))return r.get(e);const t=l(e);return t!==e&&(r.set(e,t),o.set(t,e)),t}const u=e=>o.get(e);const h=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],w=new Map;function g(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,r=y.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!r&&!h.includes(a))return;const o=async function(e,...t){const o=this.transaction(e,r?"readwrite":"readonly");let i=o.store;return n&&(i=i.index(t.shift())),(await Promise.all([i[a](...t),r&&o.done]))[0]};return w.set(t,o),o}s(e=>({...e,get:(t,a,n)=>g(t,a)||e.get(t,a,n),has:(t,a)=>!!g(t,a)||e.has(t,a)}));const f=["continue","continuePrimaryKey","advance"],m={},p=new WeakMap,b=new WeakMap,k={get(e,t){if(!f.includes(t))return e[t];let a=m[t];return a||(a=m[t]=function(...e){p.set(this,b.get(this)[t](...e))}),a}};async function*S(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const a=new Proxy(t,k);for(b.set(a,t),o.set(a,u(t));t;)yield a,t=await(p.get(a)||t.continue()),p.delete(a)}function I(t,a){return a===Symbol.asyncIterator&&e(t,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===a&&e(t,[IDBIndex,IDBObjectStore])}s(e=>({...e,get:(t,a,n)=>I(t,a)?S:e.get(t,a,n),has:(t,a)=>I(t,a)||e.has(t,a)}));const x=64*Uint8Array.BYTES_PER_ELEMENT,K=65405-(9+x+8+8+256+8+8+8+(4+48*(x+1)));(new TextEncoder).encode("p2party-x25519-idsig-v1");const v=["hybrid-3dh-mlkem512-cpace21-v4","hybrid-3dh-mlkem768-cpace21-v4","hybrid-3dh-mlkem1024-cpace21-v4"],C="p2party-reassembled",R="p2party";async function A(){return function(e,t,{blocked:a,upgrade:n,blocking:r,terminated:o}={}){const i=indexedDB.open(e,t),s=d(i);return n&&i.addEventListener("upgradeneeded",e=>{n(d(i.result),e.oldVersion,e.newVersion,d(i.transaction),e)}),a&&i.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),s.then(e=>{o&&e.addEventListener("close",()=>o()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}(R,19,{upgrade(e,t,a,n){if(e.objectStoreNames.contains("addressBook")){const e=n.objectStore("addressBook");e.indexNames.contains("username")||e.createIndex("username","username",{unique:!1}),e.indexNames.contains("peerId")||e.createIndex("peerId","peerId",{unique:!0}),e.indexNames.contains("peerPublicKey")||e.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}else{const t=e.createObjectStore("addressBook",{keyPath:["peerId"]});t.createIndex("username","username",{unique:!1}),t.createIndex("peerId","peerId",{unique:!0}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}if(e.objectStoreNames.contains("blacklist")){const e=n.objectStore("blacklist");e.indexNames.contains("username")||e.createIndex("username","username",{unique:!1}),e.indexNames.contains("peerId")||e.createIndex("peerId","peerId",{unique:!0}),e.indexNames.contains("peerPublicKey")||e.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}else{const t=e.createObjectStore("blacklist",{keyPath:["peerId"]});t.createIndex("username","username",{unique:!1}),t.createIndex("peerId","peerId",{unique:!0}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}if(e.objectStoreNames.contains("uniqueRoom")){const e=n.objectStore("uniqueRoom");e.indexNames.contains("roomUrl")||e.createIndex("roomUrl","roomUrl",{unique:!0}),e.indexNames.contains("roomId")||e.createIndex("roomId","roomId",{unique:!0})}else{const t=e.createObjectStore("uniqueRoom",{keyPath:["roomId"]});t.createIndex("roomUrl","roomUrl",{unique:!0}),t.createIndex("roomId","roomId",{unique:!0})}if(e.objectStoreNames.contains("messageData")){const e=n.objectStore("messageData");e.indexNames.contains("roomId")||e.createIndex("roomId","roomId",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1}),e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!0}),e.indexNames.contains("fromPeerId")||e.createIndex("fromPeerId","fromPeerId",{unique:!1})}else{const t=e.createObjectStore("messageData",{keyPath:["timestamp","roomId","merkleRoot"]});t.createIndex("roomId","roomId",{unique:!1}),t.createIndex("hash","hash",{unique:!1}),t.createIndex("merkleRoot","merkleRoot",{unique:!0}),t.createIndex("fromPeerId","fromPeerId",{unique:!1})}if(e.objectStoreNames.contains("chunks")){const e=n.objectStore("chunks");e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1})}else{const t=e.createObjectStore("chunks",{keyPath:["merkleRoot","chunkIndex"]});t.createIndex("merkleRoot","merkleRoot",{unique:!1}),t.createIndex("hash","hash",{unique:!1})}if(t<18&&e.objectStoreNames.contains("newChunks")&&e.deleteObjectStore("newChunks"),e.objectStoreNames.contains("newChunks")){const e=n.objectStore("newChunks");e.indexNames.contains("transferId")||e.createIndex("transferId","transferId",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1}),e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!1}),e.indexNames.contains("receiptScope")||e.createIndex("receiptScope",["merkleRoot","receiptToken"],{unique:!1})}else{const t=e.createObjectStore("newChunks",{keyPath:["transferId","chunkIndex"]});t.createIndex("transferId","transferId",{unique:!1}),t.createIndex("hash","hash",{unique:!1}),t.createIndex("merkleRoot","merkleRoot",{unique:!1}),t.createIndex("receiptScope",["merkleRoot","receiptToken"],{unique:!1})}if(e.objectStoreNames.contains("sendQueue")){const e=n.objectStore("sendQueue");e.indexNames.contains("labelPeer")||e.createIndex("labelPeer",["label","toPeerId"],{unique:!1})}else{e.createObjectStore("sendQueue",{keyPath:["position","label","toPeerId"]}).createIndex("labelPeer",["label","toPeerId"],{unique:!1})}if(!e.objectStoreNames.contains("ratchetSessions")){const t=e.createObjectStore("ratchetSessions",{keyPath:["roomId","peerPublicKey"]});t.createIndex("peerId","peerId",{unique:!1}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!1}),t.createIndex("roomId","roomId",{unique:!1})}t>0&&t<19&&(n.objectStore("ratchetSessions").clear(),n.objectStore("sendQueue").clear()),e.objectStoreNames.contains("meta")||e.createObjectStore("meta")}})}const D="ratchetWrapKey",P=12,E=16,L=16,B=Uint8Array.of(80,50,82,87),j=B.byteLength+1+L+P,M=262144,N=(new TextEncoder).encode("p2party-edge-crypto-at-rest-aad-v2");var U;!function(e){e[e.RootKey=1]="RootKey",e[e.SendingChainKey=2]="SendingChainKey",e[e.ReceivingChainKey=3]="ReceivingChainKey",e[e.DhSelfSecret=4]="DhSelfSecret",e[e.SkippedMessageKey=5]="SkippedMessageKey",e[e.EdgeCryptoState=6]="EdgeCryptoState"}(U||(U={}));const q=e=>e.slice(0),$=(e,t,a)=>{if(!(e instanceof ArrayBuffer))throw new Error(`${t} must be an ArrayBuffer`);if(void 0!==a&&e.byteLength!==a)throw new Error(`${t} must be ${String(a)} bytes`);return e},T=(e,t)=>{if("number"!=typeof e||!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a safe unsigned integer`);return e},z=(e,t)=>{if("string"!=typeof e||0===e.length)throw new Error(`${t} must be a non-empty string`);const a=(new TextEncoder).encode(e);if(a.byteLength>1048576)throw new Error(`${t} is too long`);if((new TextDecoder).decode(a)!==e)throw new Error(`${t} is not canonical Unicode`);return e},F=e=>{if(!Number.isInteger(e)||e<0||e>4294967295)throw new Error("ratchet wrap: value exceeds uint32");const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t},H=e=>{T(e,"ratchet wrap counter");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t},O=e=>{const t=e.reduce((e,t)=>e+t.byteLength,0),a=new Uint8Array(t);let n=0;for(const t of e)a.set(t,n),n+=t.byteLength;return a},Q=e=>O([F(e.byteLength),e]),V=e=>Q((new TextEncoder).encode(e)),W=e=>{const t=e.rootSuite;if("string"!=typeof(a=t)||!v.includes(a))throw new Error("Unsupported ratchet root suite");var a;if(z(e.roomId,"ratchet roomId"),z(e.peerPublicKey,"ratchet peerPublicKey"),!/^[0-9a-f]{64}$/.test(e.peerPublicKey))throw new Error("ratchet peerPublicKey must be 32-byte lowercase hex");if(z(e.peerId,"ratchet peerId"),$(e.dhSelfPub,"ratchet dhSelfPub",32),null!==e.dhRemotePub&&$(e.dhRemotePub,"ratchet dhRemotePub",32),T(e.Ns,"ratchet Ns"),T(e.Nr,"ratchet Nr"),T(e.PN,"ratchet PN"),T(e.updatedAt,"ratchet updatedAt"),!Array.isArray(e.skippedMessageKeys)||e.skippedMessageKeys.length>2e3)throw new Error("ratchet skipped-message-key count is invalid");if(e.skippedMessageKeys.forEach((e,t)=>{$(e.dhPub,`ratchet skipped[${String(t)}].dhPub`,32),T(e.n,`ratchet skipped[${String(t)}].n`)}),null!==e.edgeCryptoState){const t=$(e.edgeCryptoState,"ratchet edge crypto state");if(t.byteLength<1||t.byteLength>M+j+E)throw new Error("ratchet edge crypto state length is invalid")}},X=e=>({rootSuite:e.rootSuite,roomId:e.roomId,peerPublicKey:e.peerPublicKey,peerId:e.peerId,rootKey:q($(e.rootKey,"ratchet rootKey")),sendingChainKey:null===e.sendingChainKey?null:q($(e.sendingChainKey,"ratchet sendingChainKey")),receivingChainKey:null===e.receivingChainKey?null:q($(e.receivingChainKey,"ratchet receivingChainKey")),dhSelfPub:q($(e.dhSelfPub,"ratchet dhSelfPub")),dhSelfSec:q($(e.dhSelfSec,"ratchet dhSelfSec")),dhRemotePub:null===e.dhRemotePub?null:q($(e.dhRemotePub,"ratchet dhRemotePub")),Ns:e.Ns,Nr:e.Nr,PN:e.PN,skippedMessageKeys:(()=>{if(!Array.isArray(e.skippedMessageKeys))throw new Error("ratchet skippedMessageKeys must be an array");return e.skippedMessageKeys.map((e,t)=>({dhPub:q($(e.dhPub,`ratchet skipped[${String(t)}].dhPub`)),n:e.n,messageKey:q($(e.messageKey,`ratchet skipped[${String(t)}].messageKey`))}))})(),edgeCryptoState:null===e.edgeCryptoState?null:q($(e.edgeCryptoState,"ratchet edge crypto state")),updatedAt:e.updatedAt}),G=e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)},_=(e,t,a,n=0)=>{if(W(e),a.byteLength!==L)throw new Error("ratchet wrap: invalid record ID");const r=(null===e.sendingChainKey?0:1)|(null===e.receivingChainKey?0:2)|(null===e.dhRemotePub?0:4)|(null===e.edgeCryptoState?0:8),o=[Q(N),Uint8Array.of(2,t),Q(a),F(n),V(e.rootSuite),V(e.roomId),V(e.peerPublicKey),V(e.peerId),Q(new Uint8Array(e.dhSelfPub)),Uint8Array.of(r)];null!==e.dhRemotePub&&o.push(Q(new Uint8Array(e.dhRemotePub))),o.push(H(e.Ns),H(e.Nr),H(e.PN),H(e.updatedAt),F(e.skippedMessageKeys.length));for(const t of e.skippedMessageKeys)o.push(Q(new Uint8Array(t.dhPub)),H(t.n));return O(o)},Y=(e,t=32)=>{const a=new Uint8Array(e),n=j+1+E,r=j+M+E;if(null===t&&(a.byteLength<n||a.byteLength>r)||null!==t&&a.byteLength!==j+t+E)throw new Error("Unsupported or malformed ratchet wrap envelope");for(let e=0;e<B.byteLength;e++)if(a[e]!==B[e])throw new Error("Unsupported or malformed ratchet wrap envelope");if(2!==a[B.byteLength])throw new Error("Unsupported or malformed ratchet wrap envelope");return Uint8Array.from(a.subarray(B.byteLength+1,B.byteLength+1+L))},J=async(e,t,a,n,r=32)=>{if($(t,"ratchet secret",null===r?void 0:r),null===r&&(t.byteLength<1||t.byteLength>M))throw new Error("ratchet variable secret length is invalid");if(n.byteLength!==L)throw new Error("ratchet wrap: invalid record ID");const o=crypto.getRandomValues(new Uint8Array(P)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:a,tagLength:128},e,t),s=new Uint8Array(j+i.byteLength);return s.set(B,0),s[B.byteLength]=2,s.set(n,B.byteLength+1),s.set(o,B.byteLength+1+L),s.set(new Uint8Array(i),j),s.buffer},Z=async(e,t,a,n,r=32)=>{$(t,"ratchet wrapped secret");const o=Y(t,r);if(!te(o,n))throw new Error("Ratchet wrap record ID mismatch");const i=new Uint8Array(t),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:i.subarray(B.byteLength+1+L,j),additionalData:a,tagLength:128},e,i.subarray(j));if(null!==r&&s.byteLength!==r||null===r&&(s.byteLength<1||s.byteLength>M))throw new Uint8Array(s).fill(0),new Error("Ratchet wrapped secret has an invalid plaintext length");return s},ee=async e=>{W(e);const t=Y(e.rootKey),a=[e.sendingChainKey,e.receivingChainKey,e.dhSelfSec,...e.skippedMessageKeys.map(e=>e.messageKey)];for(const e of a)if(null!==e&&!te(Y(e),t))throw new Error("Ratchet wrap record ID mismatch");if(null!==e.edgeCryptoState&&!te(Y(e.edgeCryptoState,null),t))throw new Error("Ratchet wrap record ID mismatch");const n=[_(e,U.RootKey,t),Q(new Uint8Array(e.rootKey)),Q(e.sendingChainKey?new Uint8Array(e.sendingChainKey):new Uint8Array),Q(e.receivingChainKey?new Uint8Array(e.receivingChainKey):new Uint8Array),Q(new Uint8Array(e.dhSelfSec))];for(const t of e.skippedMessageKeys)n.push(Q(new Uint8Array(t.messageKey)));n.push(Q(e.edgeCryptoState?new Uint8Array(e.edgeCryptoState):new Uint8Array));const r=O(n);try{return new Uint8Array(await crypto.subtle.digest("SHA-256",r))}finally{r.fill(0)}},te=(e,t)=>{if(e.byteLength!==t.byteLength)return!1;let a=0;for(let n=0;n<e.byteLength;n++)a|=e[n]^t[n];return 0===a};async function ae(){const e=await A();try{const t=await e.get("meta",D);if(t)return t;const a=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),n=e.transaction("meta","readwrite"),r=n.objectStore("meta"),o=await r.get(D);return o?(await n.done,o):(await r.put(a,D),await n.done,a)}finally{e.close()}}async function ne(e,t){const a=crypto.getRandomValues(new Uint8Array(P)),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:a},e,t),r=new Uint8Array(P+n.byteLength);return r.set(a,0),r.set(new Uint8Array(n),P),r.buffer}async function re(e,t){const a=new Uint8Array(t);if(a.byteLength<28)throw new Error("Malformed wrapped secret");return crypto.subtle.decrypt({name:"AES-GCM",iv:a.subarray(0,P)},e,a.subarray(P))}const oe=()=>globalThis.navigator?.storage,ie=new Map,se=e=>e.createSyncAccessHandle,ce=(e,t,a,n)=>new File([e],t.length>0?t:a,{type:n});async function le(e,t,a,n){if(e.length!==2*x)return null;const r=ie.get(e);if(r)return r;const o=async function(e,t,a,n){try{const r=oe();if(!r||"function"!=typeof r.getDirectory)return console.warn("OPFS unavailable — reassembling file in memory"),null;const o=await r.getDirectory(),i=await o.getDirectoryHandle(C,{create:!0}),s=await i.getFileHandle(e,{create:!0}),c=await s.getFile();if(t>0&&c.size===t)return ce(c,a,e,n);const l=s.createSyncAccessHandle;if("function"!=typeof l)return console.warn("OPFS sync access handle unavailable — reassembling in memory"),null;const d=await l.call(s);let u;try{u=await A(),d.truncate(0);let t=0;const a=u.transaction("chunks","readonly"),n=a.objectStore("chunks").index("merkleRoot");let r=await n.openCursor(e);for(;r;){const e=new Uint8Array(r.value.data??new ArrayBuffer(0));let a=0;for(;a<e.length;){const n=d.write(e.subarray(a),{at:t+a});if(n<=0)throw new Error("OPFS short write");a+=n}t+=e.length,r=await r.continue()}await a.done,d.flush()}catch(t){try{d.close()}catch{}if(u)try{u.close()}catch{}throw await i.removeEntry(e).catch(()=>{}),t}return d.close(),u.close(),ce(await s.getFile(),a,e,n)}catch(e){return console.error(e),null}}(e,t,a,n);ie.set(e,o);try{return await o}finally{ie.delete(e)}}async function de(e){try{const t=oe();if(!t||"function"!=typeof t.getDirectory)return;const a=await t.getDirectory(),n=await a.getDirectoryHandle(C).catch(()=>null);n&&await n.removeEntry(e).catch(()=>{})}catch{}}const ue=new Map,he=new Map,ye=new Map,we=new Map;async function ge(e,t){const a=we.get(e)??Promise.resolve();let n;const r=new Promise(e=>{n=e}),o=a.then(()=>r);we.set(e,o),await a;try{return await t()}finally{n(),we.get(e)===o&&we.delete(e)}}async function fe(e,t){const a=ue.get(e);if(a)return a;const n=he.get(e);if(n)return n;if(ue.size>=8)for(const t of ue.keys())if(t!==e){await be(t);break}const r=async function(e,t){const a=oe();if(!a||"function"!=typeof a.getDirectory)return null;const n=await a.getDirectory(),r=await n.getDirectoryHandle(C,{create:!0}),o=await r.getFileHandle(e,{create:!0}),i=se(o);if("function"!=typeof i)return null;const s=await i.call(o);try{return t>0&&s.getSize()!==t&&s.truncate(t),{access:s,uniformSize:0,uniformKnown:!1,maxRealLen:0,seenCount:0}}catch(e){try{s.close()}catch{}throw e}}(e,t).catch(e=>(console.error(e),null));he.set(e,r);try{const t=await r;return t&&ue.set(e,t),t}finally{he.delete(e)}}function me(e,t,a){const n=new Uint8Array(a);let r=0;for(;r<n.length;){const a=e.write(n.subarray(r),{at:t+r});if(a<=0)throw new Error("OPFS short write");r+=a}}async function pe(e){const{schemaVersion:t,roomId:a,fromPeerId:n,channelLabel:r,timestamp:o,merkleRoot:i,hash:s,filename:c,messageType:l,chunkIndex:d,mimeType:u,leafHash:h,realLen:y,totalSize:w,data:g,storage:f}=e;if(1!==t||!Number.isSafeInteger(l)||l<1||l>64||!Number.isSafeInteger(d)||d<0||!Number.isSafeInteger(y)||y<=0||y>K||!Number.isSafeInteger(w)||w<=0||w>10737418240||y>w||d>=w||g.byteLength!==y||!Number.isSafeInteger(o))throw new Error("invalid receive chunk bounds");const m=e=>{if(e&&(e.roomId!==a||e.fromPeerId!==n||e.hash!==s||e.totalSize!==w||e.messageType!==l||e.filename!==c||e.channelLabel!==r||e.timestamp!==o))throw new Error("receive chunk metadata conflicts with message")},p=e=>{const t=e.map(e=>({chunkIndex:e.chunkIndex,realLen:e.realLen??0})).sort((e,t)=>e.chunkIndex-t.chunkIndex);let a=0;for(let e=0;e<t.length;e++){const n=t[e];if(!Number.isSafeInteger(n.chunkIndex)||n.chunkIndex<0||!Number.isSafeInteger(n.realLen)||n.realLen<=0||n.realLen>K||n.realLen>w||n.chunkIndex>=w||e>0&&t[e-1].chunkIndex===n.chunkIndex)throw new Error("invalid receive chunk layout");if(a+=n.realLen,!Number.isSafeInteger(a)||a>w)throw new Error("receive chunks exceed declared total")}const n=t.find(e=>0===e.chunkIndex);let r;if(n)r=n.realLen;else if(t.length>=2){r=0;for(const e of t)r=Math.max(r,e.realLen)}if(void 0!==r){const e=Math.ceil(w/r),n=e-1,o=w-r*n;for(const a of t){if(a.chunkIndex>=e)throw new Error("receive chunk index exceeds canonical manifest");const t=a.chunkIndex===n?o:r;if(a.realLen!==t)throw new Error("receive chunk length conflicts with manifest")}const i=a===w&&t.length===e&&t.every((e,t)=>e.chunkIndex===t);if(a===w&&!i)throw new Error("receive completion has a chunk-index gap");return{savedSize:a,complete:i}}if(a===w)throw new Error("receive completion is missing chunk zero");return{savedSize:a,complete:!1}},b=await A();let k;try{const e=b.transaction(["chunks","messageData"],"readonly");k=await e.objectStore("chunks").count([i,d]);m(await e.objectStore("messageData").index("merkleRoot").get(i)),await e.done}finally{b.close()}if(k>0){const e=await A();try{const t=e.transaction(["chunks","messageData"],"readonly"),a=t.objectStore("chunks").index("merkleRoot"),n=[];let r=await a.openCursor(i);for(;r;)n.push(r.value),r=await r.continue();m(await t.objectStore("messageData").index("merkleRoot").get(i));const o=p(n);return await t.done,{stored:!1,...o}}finally{e.close()}}const S=await A();try{const e=S.transaction(["chunks","messageData"],"readonly"),t=[];let a=await e.objectStore("chunks").index("merkleRoot").openCursor(i);for(;a;)t.push(a.value),a=await a.continue();m(await e.objectStore("messageData").index("merkleRoot").get(i)),p([...t,{chunkIndex:d,realLen:y}]),await e.done}finally{S.close()}let I=!1;if("opfs"===f)try{I=await async function(e,t,a,n,r){const o=await fe(e,n);if(!o)return!1;if(o.maxRealLen=Math.max(o.maxRealLen,a),o.seenCount+=1,o.uniformKnown||(0===t?(a<n&&(o.uniformSize=a),o.uniformKnown=!0):o.seenCount>=2&&(o.uniformSize=o.maxRealLen,o.uniformKnown=!0)),!o.uniformKnown)return!1;const i=0===t?0:t*o.uniformSize;return me(o.access,i,r),o.access.flush(),!0}(i,d,y,w,g)}catch(e){console.error(e),I=!1}const x="opfs"===f&&I?{merkleRoot:i,hash:s,chunkIndex:d,mimeType:u,realLen:y,leafHash:h}:{merkleRoot:i,hash:s,chunkIndex:d,mimeType:u,realLen:y,leafHash:h,data:g},v=await A();try{const e=v.transaction(["chunks","messageData","uniqueRoom"],"readwrite"),t=e.objectStore("chunks"),u=await t.getKey([i,d]);let h=!1;const g=[];let f=await t.index("merkleRoot").openCursor(i);for(;f;)g.push(f.value),f=await f.continue();void 0===u&&(p([...g,{chunkIndex:d,realLen:y}]),await t.add(x),g.push(x),h=!0);const b=p(g);if(h){const t=e.objectStore("messageData"),d=await t.index("merkleRoot").get(i);m(d),await t.put({roomId:a,timestamp:d?.timestamp??o,merkleRoot:i,hash:s,fromPeerId:n,filename:c,messageType:l,savedSize:b.savedSize,totalSize:w,channelLabel:r});const u=e.objectStore("uniqueRoom"),h=await u.index("roomId").get(a);h&&h.lastMessageMerkleRoot!==i&&await u.put({...h,lastMessageMerkleRoot:i,messageCount:h.messageCount+1,updatedAt:o})}return await e.done,{stored:h,...b}}finally{v.close()}}async function be(e){const t=he.get(e);if(t)try{await t}catch{}const a=ue.get(e);if(a){ue.delete(e);try{a.access.flush(),a.access.close()}catch{}}}async function ke(e,t,a,n){if(e.length!==2*x)return null;await be(e);const r=ye.get(e);if(r)return r;const o=async function(e,t,a,n){try{const r=oe();if(!r||"function"!=typeof r.getDirectory)return null;const o=await r.getDirectory(),i=await o.getDirectoryHandle(C,{create:!0}),s=await i.getFileHandle(e,{create:!0}),c=await A(),l=[];let d=0;try{const t=c.transaction("chunks","readonly"),a=t.objectStore("chunks").index("merkleRoot");let n=await a.openCursor(e);for(;n;){const e=n.value;e.realLen&&e.realLen>d&&(d=e.realLen),e.data&&e.data.byteLength>0&&l.push(e),n=await n.continue()}await t.done}catch(e){return console.error(e),c.close(),null}const u=await s.getFile();if(t>0&&u.size===t&&0===l.length)return c.close(),ce(u,a,e,n);if(l.length>0&&(0===d||l.some(e=>null==e.realLen)))return c.close(),null;const h=se(s);if("function"!=typeof h)return c.close(),null;const y=await h.call(s);try{t>0&&y.getSize()!==t&&y.truncate(t);for(let e=0;e<l.length;e++){const t=l[e];me(y,0===t.chunkIndex?0:t.chunkIndex*d,t.data)}y.flush()}finally{y.close()}if(l.length>0)try{const e=c.transaction("chunks","readwrite"),t=e.objectStore("chunks");for(let e=0;e<l.length;e++){const a=l[e];await t.put({merkleRoot:a.merkleRoot,hash:a.hash,chunkIndex:a.chunkIndex,mimeType:a.mimeType,realLen:a.realLen,leafHash:a.leafHash})}await e.done}catch(e){console.error(e)}c.close();const w=await s.getFile();return t>0&&w.size!==t?null:ce(w,a,e,n)}catch(e){return console.error(e),null}}(e,t,a,n);ye.set(e,o);try{return await o}finally{ye.delete(e)}}const Se=new class{#e=new Map;#t(e,t){const a=(e=>`${String(e.roomId.length)}:${e.roomId}${String(e.peerPublicKey.length)}:${e.peerPublicKey}`)(e),n=this.#e.get(a);if(n&&e.updatedAt<n.updatedAt)throw t.fill(0),new Error("Ratchet persistence rollback detected");if(e.updatedAt===n?.updatedAt&&!te(t,n.fingerprint))throw t.fill(0),new Error("Ratchet persistence equivocation detected");!n||e.updatedAt>n.updatedAt?(n?.fingerprint.fill(0),this.#e.set(a,{updatedAt:e.updatedAt,fingerprint:t})):t.fill(0)}async acceptAuthenticated(e){const t=await ee(e);this.#t(e,t)}async rememberTrustedWrite(e){const t=await ee(e);this.#t(e,t)}forget(e,t){const a=`${String(e.length)}:${e}${String(t.length)}:${t}`;this.#e.get(a)?.fingerprint.fill(0),this.#e.delete(a)}clear(){for(const e of this.#e.values())e.fingerprint.fill(0);this.#e.clear()}},Ie=new Map,xe=new Map,Ke=(e,t)=>`${String(e.length)}:${e}${String(t.length)}:${t}`,ve=async(e,t,a)=>{const n=Ke(e,t),r=xe.get(n)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=r.catch(()=>{}).then(()=>i);xe.set(n,s),await r.catch(()=>{});try{return await a()}finally{o(),xe.get(n)===s&&xe.delete(n)}};async function Ce(e,t){return ve(e,t,async()=>{try{const a=await A();let n;try{n=await a.get("ratchetSessions",[e,t])}finally{a.close()}if(!n)return;const r=await ae(),o=await async function(e,t,a){const n=X(e);W(n);const r=[];try{const e=Y(n.rootKey),o=await Z(t,n.rootKey,_(n,U.RootKey,e),e);r.push(o);const i=n.sendingChainKey?await Z(t,n.sendingChainKey,_(n,U.SendingChainKey,e),e):null;i&&r.push(i);const s=n.receivingChainKey?await Z(t,n.receivingChainKey,_(n,U.ReceivingChainKey,e),e):null;s&&r.push(s);const c=await Z(t,n.dhSelfSec,_(n,U.DhSelfSecret,e),e);r.push(c);const l=[];for(let a=0;a<n.skippedMessageKeys.length;a++){const o=n.skippedMessageKeys[a],i=await Z(t,o.messageKey,_(n,U.SkippedMessageKey,e,a),e);r.push(i),l.push({dhPub:o.dhPub,n:o.n,messageKey:i})}const d=n.edgeCryptoState?await Z(t,n.edgeCryptoState,_(n,U.EdgeCryptoState,e),e,null):null;return d&&r.push(d),a&&await a.acceptAuthenticated(n),{...n,rootKey:o,sendingChainKey:i,receivingChainKey:s,dhSelfSec:c,skippedMessageKeys:l,edgeCryptoState:d}}catch(e){for(const e of r)new Uint8Array(e).fill(0);throw e}finally{G(n)}}(n,r,Se),i=Ke(e,t);return Ie.set(i,Math.max(Ie.get(i)??0,o.updatedAt)),o}catch(e){return void console.error(e)}})}async function Re(e){await ve(e.roomId,e.peerPublicKey,async()=>{const t=Ke(e.roomId,e.peerPublicKey),a=Ie.get(t)??0,n=Math.max(Date.now(),e.updatedAt),r=n>a?n:a+1;if(!Number.isSafeInteger(r))throw new Error("Ratchet persistence timestamp exhausted");const o={...e,updatedAt:r};try{const e=await ae(),a=await async function(e,t){const a=X(e);if(W(a),$(a.rootKey,"ratchet rootKey",32),a.sendingChainKey&&$(a.sendingChainKey,"ratchet sendingChainKey",32),a.receivingChainKey&&$(a.receivingChainKey,"ratchet receivingChainKey",32),$(a.dhSelfSec,"ratchet dhSelfSec",32),a.skippedMessageKeys.forEach((e,t)=>$(e.messageKey,`ratchet skipped[${String(t)}].messageKey`,32)),a.edgeCryptoState&&($(a.edgeCryptoState,"ratchet edge crypto state"),a.edgeCryptoState.byteLength<1||a.edgeCryptoState.byteLength>M))throw new Error("ratchet edge crypto state length is invalid");try{const e=crypto.getRandomValues(new Uint8Array(L)),n=await J(t,a.rootKey,_(a,U.RootKey,e),e),r=a.sendingChainKey?await J(t,a.sendingChainKey,_(a,U.SendingChainKey,e),e):null,o=a.receivingChainKey?await J(t,a.receivingChainKey,_(a,U.ReceivingChainKey,e),e):null,i=await J(t,a.dhSelfSec,_(a,U.DhSelfSecret,e),e),s=[];for(let n=0;n<a.skippedMessageKeys.length;n++){const r=a.skippedMessageKeys[n];s.push({dhPub:r.dhPub,n:r.n,messageKey:await J(t,r.messageKey,_(a,U.SkippedMessageKey,e,n),e)})}const c=a.edgeCryptoState?await J(t,a.edgeCryptoState,_(a,U.EdgeCryptoState,e),e,null):null;return{...a,rootKey:n,sendingChainKey:r,receivingChainKey:o,dhSelfSec:i,skippedMessageKeys:s,edgeCryptoState:c}}finally{G(a)}}(o,e),n=await A();try{await n.put("ratchetSessions",a)}finally{n.close()}await Se.rememberTrustedWrite(a),Ie.set(t,r)}finally{(e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)})(o)}})}const Ae=/^[0-9a-f]{64}$/,De=(e,t)=>{if("string"!=typeof e||0===e.length)throw new Error("PIN attempt room ID must not be empty");if(void 0!==t&&!Ae.test(t))throw new Error("PIN attempt peer identity must be 32-byte lowercase hexadecimal")},Pe=e=>`pinAttempts:v2:${e.length}:${e}:`,Ee=(e,t)=>`${Pe(e)}${t}`;const Le="identityX25519";const Be="identityEd25519";async function je(){try{await async function(){const e=[...he.values()];for(let t=0;t<e.length;t++)try{await e[t]}catch{}const t=[...ue.keys()];for(let e=0;e<t.length;e++)await be(t[e])}();const e=oe();if(e&&"function"==typeof e.getDirectory){const t=await e.getDirectory();await t.removeEntry(C,{recursive:!0}).catch(()=>{})}}catch{}await function(e,{blocked:t}={}){const a=indexedDB.deleteDatabase(e);return t&&a.addEventListener("blocked",e=>t(e.oldVersion,e)),d(a).then(()=>{})}(R,{blocked(){console.error("DB deletion BLOCKED")}}),Se.clear(),Ie.clear()}onmessage=async e=>{const t=e.data,{id:a,method:n}=t;try{let e;switch(n){case"getDBAddressBookEntry":e=await async function(e,t){if(!e&&!t)return;if(e&&e.length<10&&!t)return;if(t&&64!==t.length&&!e)return;const a=await A();try{const n=a.transaction("addressBook","readonly"),r=e?n.objectStore("addressBook").index("peerId"):n.objectStore("addressBook").index("peerPublicKey"),o=e?await r.get(e):await r.get(t??"");return await n.done,a.close(),o?{username:o.username,peerId:o.peerId,peerPublicKey:o.peerPublicKey}:void 0}catch{return void a.close()}}(...t.args);break;case"getAllDBAddressBookEntries":e=await async function(){try{const e=await A(),t=await e.getAll("addressBook");return e.close(),t}catch{return[]}}(...t.args);break;case"setDBAddressBookEntry":await async function(e,t,a){try{const n=await A(),r=n.transaction(["addressBook"],"readwrite"),o=r.objectStore("addressBook"),i=o.index("peerId"),s=o.index("peerPublicKey"),c=await i.get(t),l=await s.get(a);(!c&&!l||c&&!l||!c&&l)&&await o.put({username:e,peerId:t,peerPublicKey:a,dateAdded:Date.now()}),await r.done,n.close()}catch(e){console.error(e)}}(...t.args),e=void 0;break;case"deleteDBAddressBookEntry":e=await async function(e,t,a){const n=!e||0===e.length,r=!t||t.length<10,o=64!==a?.length;if(n&&r&&o)throw new Error("Cannot delete address book with no data");let i=t??"";try{const n=await A(),s=n.transaction("addressBook","readwrite"),c=s.objectStore("addressBook");if(r)if(o){const t=c.index("username"),a=await t.getKey(e??"");if(a){const n=await t.get(e??"");i=n?.peerId??"",await c.delete(a)}}else{const e=c.index("peerPublicKey"),t=await e.getKey(a);if(t){const n=await e.get(a);i=n?.peerId??"",await c.delete(t)}}else{const e=c.index("peerId"),a=await e.getKey(t);a&&await c.delete(a)}await s.done,n.close()}catch{}return i}(...t.args);break;case"getDBPeerIsBlacklisted":e=await async function(e,t){if(!e&&!t)return!1;if(e&&e.length<10&&!t)return!1;if(t&&64!==t.length&&!e)return!1;const a=await A();try{const n=a.transaction("blacklist","readonly"),r=e?n.objectStore("blacklist").index("peerId"):n.objectStore("blacklist").index("peerPublicKey"),o=e?await r.get(e):await r.get(t??"");return await n.done,!!o}finally{a.close()}}(...t.args);break;case"getAllDBBlacklisted":e=await async function(){const e=await A();try{const t=await e.getAll("blacklist");return e.close(),t}catch{return e.close(),[]}}(...t.args);break;case"setDBPeerInBlacklist":await async function(e,t){try{const a=await A(),n=a.transaction(["blacklist"],"readwrite"),r=n.objectStore("blacklist"),o=r.index("peerId"),i=r.index("peerPublicKey"),s=await o.get(e),c=await i.get(t);(!s&&!c||s&&!c||!s&&c)&&await r.put({peerId:e,peerPublicKey:t,dateAdded:Date.now()}),await n.done,a.close()}catch(e){throw console.error(e),e}}(...t.args),e=void 0;break;case"deleteDBPeerFromBlacklist":await async function(e,t){const a=!e||e.length<10;if(a&&64!==t?.length)throw new Error("Cannot delete blacklisted with no data");try{const n=await A(),r=n.transaction("blacklist","readwrite"),o=r.objectStore("blacklist");if(a){const e=o.index("peerPublicKey"),a=await e.getKey(t??"");a&&await o.delete(a)}else{const t=o.index("peerId"),a=await t.getKey(e);a&&await o.delete(a)}await r.done,n.close()}catch(e){console.error(e)}}(...t.args),e=void 0;break;case"getAllDBUniqueRooms":e=await async function(){const e=await A();try{const t=await e.getAll("uniqueRoom");return e.close(),t}catch{return e.close(),[]}}(...t.args);break;case"setDBUniqueRoom":await async function(e,t,a){if(32!==a.byteLength)throw new Error("Room policy must be the canonical 32-byte descriptor");const n=await A();try{const r=n.transaction(["uniqueRoom"],"readwrite"),o=r.objectStore("uniqueRoom"),i=o.index("roomUrl"),s=o.index("roomId"),c=await i.get(e),l=await s.get(t),d=c??l;if(d)await o.put({...d,roomId:t,roomUrl:e,roomPolicy:a,updatedAt:Date.now()});else{const n=Date.now();await o.put({roomId:t,roomUrl:e,roomPolicy:a,messageCount:0,lastMessageMerkleRoot:"",createdAt:n,updatedAt:n})}await r.done}finally{n.close()}}(...t.args),e=void 0;break;case"getDBMessageData":e=await async function(e,t){try{const a=await A(),n=a.transaction(["messageData"],"readonly"),r=n.objectStore("messageData"),o=r.index("merkleRoot"),i=r.index("hash");if(e?.length===2*x){const r=await o.get(e);if(r)return await n.done,a.close(),r;if(t?.length===2*x){const e=await i.get(t);return await n.done,a.close(),e}return await n.done,void a.close()}if(t?.length===2*x){const e=await i.get(t);return await n.done,a.close(),e}return await n.done,void a.close()}catch(e){return void console.error(e)}}(...t.args);break;case"getDBRoomMessageData":e=await async function(e){const t=await A(),a=await t.getAllFromIndex("messageData","roomId",e);t.close();const n=a.length,r=[];for(let t=0;t<n;t++)r.push({transferId:a[t].transferId,roomId:e,merkleRoot:a[t].merkleRoot,hash:a[t].hash,fromPeerId:a[t].fromPeerId,filename:a[t].filename,messageType:a[t].messageType,savedSize:a[t].savedSize,totalSize:a[t].totalSize,channelLabel:a[t].channelLabel,timestamp:a[t].timestamp});return r}(...t.args);break;case"getDBRoomStats":e=await async function(e){const t=await A(),a=await t.getAllFromIndex("messageData","roomId",e);t.close();const n=new Set;let r=0,o=0,i=0,s=0;for(const e of a){const t=void 0!==e.transferId,a=t?e.totalSize:e.savedSize;t?(r+=a,i+=1):(o+=a,s+=1,e.fromPeerId.length>0&&n.add(e.fromPeerId))}return{messageCount:a.length,messagesSent:i,messagesReceived:s,bytesSent:r,bytesReceived:o,bytesTotal:r+o,peerIds:[...n]}}(...t.args);break;case"setDBRoomMessageData":await async function(e,t,a,n,r,o,i,s,c,l,d){try{const u=await A(),h=u.transaction(["messageData","uniqueRoom"],"readwrite"),y=h.objectStore("messageData"),w=await y.index("merkleRoot").get(t),g=w?.savedSize??0;try{await y.put({transferId:d,roomId:e,timestamp:l,merkleRoot:t,hash:a,fromPeerId:n,filename:s,messageType:i,savedSize:g+r<=o?g+r:o,totalSize:o,channelLabel:c})}catch(e){throw await h.done,u.close(),e}const f=h.objectStore("uniqueRoom"),m=await f.index("roomId").get(e);if(m&&m.lastMessageMerkleRoot!==t)try{await f.put({...m,lastMessageMerkleRoot:t,messageCount:m.messageCount+1,updatedAt:l})}catch(e){throw await h.done,u.close(),e}await h.done,u.close()}catch(e){throw console.error(e),e}}(...t.args),e=void 0;break;case"getDBChunk":e=await async function(e,t){const a=await A(),n=await a.get("chunks",[e,t]);return a.close(),n?.data}(...t.args);break;case"existsDBChunk":e=await async function(e,t){const a=await A(),n=await a.count("chunks",[e,t]);return a.close(),n>0}(...t.args);break;case"getDBNewChunk":e=await async function(e,t){const a=await A();try{return await a.get("newChunks",[e,t])}finally{a.close()}}(...t.args);break;case"getDBNewChunkByReceipt":e=await async function(e,t){if(e.length!==2*x||t.length!==2*x)return;const a=await A();try{return await a.getFromIndex("newChunks","receiptScope",[e,t])}finally{a.close()}}(...t.args);break;case"existsDBNewChunk":e=await async function(e,t){const a=await A(),n=await a.count("newChunks",[e,t]);return a.close(),n>0}(...t.args);break;case"getDBSendQueue":e=await async function(e,t,a){const n=await A();if(a){const r=await n.get("sendQueue",[a,e,t]);return n.close(),r?[r]:[]}const r=n.transaction("sendQueue","readonly").objectStore("sendQueue").index("labelPeer"),o=IDBKeyRange.only([e,t]),i=await r.getAll(o);return n.close(),i}(...t.args);break;case"getDBAllChunks":e=await async function(e,t){try{const a=await A(),n=a.transaction("chunks","readonly"),r=n.objectStore("chunks"),o=r.index("hash"),i=r.index("merkleRoot");if(e?.length===2*x){const t=await i.getAll(e);return 0===t.length?(await n.done,a.close(),[]):(await n.done,a.close(),t)}if(t?.length===2*x){const e=await o.getAll(t);return await n.done,a.close(),e.length>0?e.filter(t=>t.merkleRoot===e[0].merkleRoot):e}return await n.done,a.close(),[]}catch(e){return console.error(e),[]}}(...t.args);break;case"getDBAllChunkLeafHashes":e=await async function(e){if(e.length!==2*x)return[];try{const t=await A(),a=t.transaction("chunks","readonly"),n=a.objectStore("chunks").index("merkleRoot"),r=[];let o=await n.openCursor(e);for(;o;)r.push({chunkIndex:o.value.chunkIndex,leafHash:o.value.leafHash}),o=await o.continue();return await a.done,t.close(),r}catch(e){return console.error(e),[]}}(...t.args);break;case"assembleToOPFS":e=await le(...t.args);break;case"getDBAllChunksCount":e=await async function(e,t){try{const a=await A(),n=a.transaction(["chunks"],"readonly"),r=n.objectStore("chunks"),o=r.index("hash"),i=r.index("merkleRoot");if(t?.length===2*x){const r=await o.count(t);if(0===r){if(e?.length===2*x){const t=await i.count(e);return await n.done,a.close(),t}return await n.done,a.close(),0}return await n.done,a.close(),r}if(e?.length===2*x){const t=await i.count(e);return await n.done,a.close(),t}return await n.done,a.close(),0}catch{return 0}}(...t.args);break;case"setDBChunk":await async function(e){const t=await A();try{await t.add("chunks",e)}finally{t.close()}}(...t.args),e=void 0;break;case"storeReceiveChunk":{const a=t.args[0];e=await ge(a.merkleRoot,()=>async function(e){return pe(e)}(a));break}case"getReceiveFile":{const a=t.args;e=await ge(a[0],()=>ke(...a));break}case"closeReceiveFile":await ge(t.args[0],()=>be(...t.args)),e=void 0;break;case"deleteReceiveTransfer":await ge(t.args[0],()=>async function(e){if(e.length!==2*x||!/^[0-9a-f]+$/.test(e))throw new Error("invalid receive transfer Merkle root");await be(e);const t=await A();try{const a=t.transaction(["chunks","messageData","uniqueRoom"],"readwrite"),n=a.objectStore("chunks"),r=a.objectStore("messageData"),o=a.objectStore("uniqueRoom"),i=await n.index("merkleRoot").getAllKeys(e);for(const e of i)await n.delete(e);const s=await r.index("merkleRoot").getAllKeys(e);let c="";for(const e of s){const t=await r.get(e);!c&&t&&(c=t.roomId),await r.delete(e)}if(c){const e=await o.index("roomId").get(c);if(e){const t=r.index("roomId"),a=await t.count(c),n=await t.openCursor(IDBKeyRange.only(c),"prev");await o.put({...e,messageCount:a,updatedAt:n?.value.timestamp??Date.now(),lastMessageMerkleRoot:n?.value.merkleRoot??""})}}await a.done}finally{t.close()}await de(e)}(...t.args)),e=void 0;break;case"getDBAllNewChunks":e=await async function(e){const{transferId:t,merkleRootHex:a,hashHex:n}=e,r=t?"transferId":a?"merkleRoot":n?"hash":void 0,o=t??a??n;if(!r||!o)return[];const i=await A();try{return await i.getAllFromIndex("newChunks",r,o)}finally{i.close()}}(...t.args);break;case"getDBAllNewChunksCount":e=await async function(e){const t=await A();try{return await t.countFromIndex("newChunks","transferId",e)}finally{t.close()}}(...t.args);break;case"setDBNewChunk":await async function(e){const t=await A();try{await t.put("newChunks",e)}finally{t.close()}}(...t.args),e=void 0;break;case"setDBSendQueue":await async function(e){const t=await A();await t.put("sendQueue",e),t.close()}(...t.args),e=void 0;break;case"countDBSendQueue":e=await async function(e,t){const a=await A(),n=a.transaction("sendQueue","readonly").objectStore("sendQueue").index("labelPeer"),r=IDBKeyRange.only([e,t]),o=await n.count(r);return a.close(),o}(...t.args);break;case"deleteDBChunk":await async function(e,t){try{const a=await A(),n=a.transaction("chunks","readwrite"),r=n.objectStore("chunks");if(void 0!==t){const a=IDBKeyRange.only([e,t]);await r.delete(a)}else{const t=r.index("hash"),a=await t.getAllKeys(e),n=a.length;if(0===n){const t=r.index("merkleRoot"),a=await t.getAllKeys(e),n=a.length;for(let e=0;e<n;e++)await r.delete(a[e])}else for(let e=0;e<n;e++)await r.delete(a[e])}await n.done,a.close()}catch{}}(...t.args),e=void 0;break;case"deleteDBNewChunk":await async function(e){const{transferId:t,merkleRootHex:a,hashHex:n,chunkIndex:r}=e,o=await A();try{const e=o.transaction("newChunks","readwrite"),i=e.objectStore("newChunks");if(t&&void 0!==r)await i.delete([t,r]);else if(t){const e=await i.index("transferId").getAllKeys(t);for(const t of e)await i.delete(t)}else if(a){const e=await i.index("merkleRoot").getAllKeys(a);for(const t of e)await i.delete(t)}else if(n){const e=await i.index("hash").getAllKeys(n);for(const t of e)await i.delete(t)}await e.done}catch(e){throw console.error(e),e}finally{o.close()}}(...t.args),e=void 0;break;case"deleteDBMessageData":await async function(e){try{const t=await A(),a=t.transaction(["messageData","uniqueRoom"],"readwrite"),n=a.objectStore("messageData"),r=a.objectStore("uniqueRoom"),o=n.index("merkleRoot"),i=await o.getAllKeys(e),s=i.length;let c="";for(let e=0;e<s;e++){if(0===e||0===c.length){const t=await n.get(i[e]);c=t?.roomId??""}await n.delete(i[e])}if(c.length>0){const e=r.index("roomId"),t=await e.get(c);if(t){const e=n.index("roomId"),a=await e.getAllKeys(c),o=a.length,i=o>0?await n.get(a[o-1]):void 0;await r.put({...t,messageCount:t.messageCount>0?t.messageCount-1:0,updatedAt:i?.timestamp??Date.now(),lastMessageMerkleRoot:i?.merkleRoot??""})}}await a.done,t.close(),await ge(e,async()=>{await be(e),await de(e)})}catch{}}(...t.args),e=void 0;break;case"deleteDBUniqueRoom":await async function(e){try{const t=await A(),a=t.transaction(["uniqueRoom","ratchetSessions"],"readwrite"),n=a.objectStore("uniqueRoom"),r=n.index("roomId"),o=await r.getKey(e);void 0!==o&&await n.delete(o);const i=a.objectStore("ratchetSessions"),s=await i.index("roomId").getAllKeys(e);for(const t of s)await i.delete(t),Array.isArray(t)&&"string"==typeof t[1]&&(Se.forget(e,t[1]),Ie.delete(Ke(e,t[1])));await a.done,t.close()}catch{}}(...t.args),e=void 0;break;case"deleteDBSendQueue":await async function(e,t,a){try{const n=await A();if(void 0!==a)await n.delete("sendQueue",[a,e,t]);else{const a=IDBKeyRange.only([e,t]);await n.delete("sendQueue",a)}n.close()}catch{}}(...t.args),e=void 0;break;case"getRatchetSession":e=await Ce(...t.args);break;case"setRatchetSession":await Re(...t.args),e=void 0;break;case"deleteRatchetSession":await async function(e,t){await ve(e,t,async()=>{try{const a=await A();await a.delete("ratchetSessions",[e,t]),a.close(),Se.forget(e,t),Ie.delete(Ke(e,t))}catch(e){console.error(e)}})}(...t.args),e=void 0;break;case"getPinAttemptState":e=await async function(e,t){De(e,t);const a=await A();try{return await a.get("meta",Ee(e,t))}finally{a.close()}}(...t.args);break;case"incrementPinAttemptState":e=await async function(e,t,a,n,r,o){if(De(e,t),!Number.isSafeInteger(a)||!Number.isSafeInteger(n)||!Number.isSafeInteger(r)||!Number.isSafeInteger(o)||a<0||n<1||r<1||o<r)throw new Error("Invalid PIN backoff parameters");const i=await A();try{const s=i.transaction("meta","readwrite"),c=s.objectStore("meta"),l=Ee(e,t),d=await c.get(l),u=(d?.failures??0)+1,h={failures:u,retryAfter:a+(u<n?0:Math.min(r*2**(u-n),o))};return await c.put(h,l),await s.done,h}finally{i.close()}}(...t.args);break;case"deletePinAttemptState":await async function(e,t){De(e,t);const a=await A();try{if(void 0!==t)return void await a.delete("meta",Ee(e,t));const n=a.transaction("meta","readwrite"),r=n.objectStore("meta"),o=Pe(e),i=await r.getAllKeys();await Promise.all(i.filter(e=>"string"==typeof e&&e.startsWith(o)).map(e=>r.delete(e))),await r.delete(`pinAttempts:${e}`),await n.done}finally{a.close()}}(...t.args),e=void 0;break;case"getIdentityX25519":e=await async function(){const e=await A();let t;try{t=await e.get("meta",Le)}finally{e.close()}if(!t)return;if(32!==t.pub.byteLength||64!==t.crossSig.byteLength)throw new Error("Stored X25519 identity has invalid public fields");const a=await ae(),n=await re(a,t.wrappedSecret);if(32!==n.byteLength)throw new Error("Stored X25519 identity has an invalid secret length");return{pub:t.pub,secret:n,crossSig:t.crossSig}}();break;case"setIdentityX25519":await async function(e){if(32!==e.pub.byteLength||32!==e.secret.byteLength||64!==e.crossSig.byteLength)throw new Error("X25519 identity has invalid field lengths");const t=await ae(),a=await ne(t,e.secret),n={pub:e.pub,wrappedSecret:a,crossSig:e.crossSig},r=await A();try{await r.put("meta",n,Le)}finally{r.close()}}(...t.args),e=void 0;break;case"deleteIdentityX25519":await async function(){const e=await A();try{const t=e.transaction(["meta","ratchetSessions"],"readwrite");await t.objectStore("meta").delete(Le),await t.objectStore("ratchetSessions").clear(),await t.done}finally{e.close()}Se.clear(),Ie.clear()}(),e=void 0;break;case"getIdentityEd25519":e=await async function(){const e=await A();let t;try{t=await e.get("meta",Be)}finally{e.close()}if(!t)return;if(32!==t.pub.byteLength)throw new Error("Stored Ed25519 public key has an invalid length");const a=await ae(),n=await re(a,t.wrappedSecret);if(64!==n.byteLength)throw new Error("Stored Ed25519 secret key has an invalid length");return{pub:t.pub,secret:n}}();break;case"setIdentityEd25519":await async function(e){if(32!==e.pub.byteLength||64!==e.secret.byteLength)throw new Error("Ed25519 identity has invalid key lengths");const t=await ae(),a=await ne(t,e.secret),n={pub:e.pub,wrappedSecret:a},r=await A();try{await r.put("meta",n,Be)}finally{r.close()}}(...t.args),e=void 0;break;case"deleteIdentityEd25519":await async function(){const e=await A();try{const t=e.transaction(["meta","ratchetSessions"],"readwrite");await t.objectStore("meta").delete(Be),await t.objectStore("ratchetSessions").clear(),await t.done}finally{e.close()}Se.clear(),Ie.clear()}(),e=void 0;break;case"deleteDB":await je(),e=void 0;break;default:return void postMessage({id:a,error:"Method not found"})}postMessage({id:a,result:e})}catch(e){postMessage({id:a,error:String(e)})}};\n',ja=new Blob([za],{type:"application/javascript"}),Ha=new Worker(URL.createObjectURL(ja),{type:"module"});let $a=0;const Va=new Map;Ha.onmessage=e=>{const{id:t,result:n,error:r}=e.data,a=Va.get(t);a&&(Va.delete(t),r?a.reject(r):a.resolve(n))};const Qa=e=>{const t=[...Va.values()];Va.clear();for(const n of t)n.reject(e)};function Wa(e,...t){return new Promise((n,r)=>{const a=++$a;Va.set(a,{resolve:n,reject:r}),Ha.postMessage({id:a,method:e,args:t})})}Ha.onerror=e=>{Qa(new Error(`p2party: the database worker failed: ${e.message||"unknown error"}`))},Ha.onmessageerror=()=>{Qa(new Error("p2party: a database worker message could not be deserialized"))};const Xa=(e,t)=>Wa("getDBAddressBookEntry",e,t),Ga=async(e,t)=>{try{return await Wa("getDBPeerIsBlacklisted",e,t)}catch(e){return console.error("p2party: blacklist lookup failed; treating this peer as blocked",e),!0}},Ja=()=>Wa("getAllDBUniqueRooms"),Ya=(e,t)=>Wa("getDBMessageData",e,t),Za=e=>Wa("getDBRoomMessageData",e),eo=(e,t)=>Wa("getDBNewChunk",e,t),to=e=>Wa("setDBChunk",e),no=e=>Wa("storeReceiveChunk",e),ro=e=>Wa("deleteReceiveTransfer",e),ao=e=>Wa("setDBNewChunk",e),oo=e=>Wa("deleteDBNewChunk",e),io=(e,t,n)=>Wa("deleteDBSendQueue",e,t,n),so=(e,t)=>Wa("deleteRatchetSession",e,t),co=(e,t)=>Wa("getPinAttemptState",e,t),lo=()=>Wa("getIdentityX25519"),uo=()=>Wa("deleteIdentityX25519"),ho=e=>Wa("setIdentityEd25519",e),fo=()=>Wa("deleteIdentityEd25519"),po=(e,t)=>new Promise((n,r)=>{try{const r=(new TextEncoder).encode(e);if(r.length<=0||r.length>32)throw new Error("Channel label must be between 1 and 32 UTF-8 bytes");if("string"==typeof t&&!/^[0-9a-f]{128}$/.test(t))throw new Error("Merkle root hex should be 128 canonical lowercase characters");if("string"!=typeof t&&t.length!==N)throw new Error("Merkle root should be 64 bytes");let a="";const o=new Uint8Array(32);o.set(r.subarray(0,Math.min(32,r.length))),a+=ca(o),a+="~",a+="string"==typeof t?t:ca(t),n(a)}catch(e){r(e)}}),mo=e=>new Promise((t,n)=>{try{const n=e.split("~"),r=n.length;if(1===r)return void t({channelLabel:e,merkleRootHex:"",merkleRoot:new Uint8Array});if(2!==r||193!==e.length)throw new Error(`Channel message label needs exactly ${String(2)} bounded components.`);if(!/^[0-9a-f]{64}~[0-9a-f]{128}$/.test(e))throw new Error("Channel message label must use canonical lowercase hex");const a=la(n[0]);if(32!==a.length)throw new Error("Channel label is not 32 bytes long.");const o=(new TextDecoder).decode(a).replace(/\0+$/,""),i=la(n[1]);if(i.length!==N)throw new Error("Merkle root has invalid length");t({channelLabel:o,merkleRoot:i,merkleRootHex:n[1]})}catch(e){n(e)}}),yo=new Map,go=(e,t,n)=>`${e}\0${t}\0${n}`,wo=(e,t,n)=>{const r=go(e,t,n);let a=yo.get(r);return a||(a={acked:new Set,complete:!1},yo.set(r,a)),a},bo=(e,t,n)=>new Set(wo(e,t,n).acked),vo=(e,t,n)=>wo(e,t,n).acked.size,ko=(e,t,n)=>{const r=wo(e,t,n);return!r.complete&&(r.complete=!0,!0)},Io=(e,t,n)=>yo.get(go(e,t,n))?.complete??!1,So=(e,t,n)=>{yo.delete(go(e,t,n))},Co=async(e,t,n,r,a)=>{const o=Date.now()+r;for(;Date.now()<o&&!Io(e,t,n)&&!a?.aborted;)await new Promise(e=>setTimeout(e,200));return!a?.aborted&&Io(e,t,n)},Ao=async(e,t,n,r,a)=>{try{const o=ca(e),{merkleRootHex:i}=await mo(t),{rooms:s}=a.getState(),c=s.find(e=>e.id===r);if(!c)return{kind:"ignored",peerId:n};const l=c.messages.findLastIndex(e=>e.merkleRootHex===i);if(l<0)return{kind:"ignored",peerId:n};const d=c.messages[l].sha512Hex,u=c.messages[l].transferId;if(!u)return{kind:"ignored",peerId:n};if(o===d){return ko(c.id,n,u)?{kind:"peer-complete",peerId:n,transferId:u,newlyAccepted:!0}:{kind:"peer-complete",peerId:n,transferId:u,newlyAccepted:!1}}{const e=await((e,t)=>Wa("getDBNewChunkByReceipt",e,t))(i,o),t=e?.chunkIndex??-1;if(e&&e.transferId===u&&t>-1){const e=((e,t,n,r)=>{const a=wo(e,t,n).acked,o=a.size;return a.add(r),a.size!==o})(c.id,n,u,t);return{kind:"chunk-acked",peerId:n,transferId:u,chunkIndex:t,newlyAccepted:e}}}return{kind:"ignored",peerId:n}}catch(e){throw console.error(e),e}},Eo=e=>{const t=new Uint8Array(ee);let n=0;new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.schemaVersion),!1),n+=8,t[n]=e.messageType,n+=1,t.set(e.hash,n),n+=N;new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.totalSize),!1),n+=8;new DataView(t.buffer,n,8).setBigInt64(0,BigInt(e.date.getTime()),!1),n+=8;const r=(new TextEncoder).encode(e.name),a=new Uint8Array(256);a.set(r.subarray(0,Math.min(256,r.length))),t.set(a,n),n+=256;new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkStartIndex),!1),n+=8;new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkEndIndex),!1),n+=8;return new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkIndex),!1),t},Po=e=>{if(e.length!==ee)throw new Error("Invalid metadata buffer totalSize");let t=0;const n=new DataView(e.buffer,e.byteOffset+t,8),r=Number(n.getBigUint64(0,!1));t+=8;const a=e[t];t+=1;const o=e.slice(t,t+N);t+=N;const i=new DataView(e.buffer,e.byteOffset+t,8),s=Number(i.getBigUint64(0,!1));t+=8;const c=new DataView(e.buffer,e.byteOffset+t,8),l=Number(c.getBigUint64(0,!1)),d=new Date(l);t+=8;const u=e.slice(t,t+256);let h=(new TextDecoder).decode(u).replace(/\0+$/,"");h=h.replace(/[/\\]/g,"_").replace(/[<>:"'|?*]/g,"_").replace(/[\u0000-\u001f\u007f]/g,""),t+=256;const f=new DataView(e.buffer,e.byteOffset+t,8),p=Number(f.getBigUint64(0,!1));t+=8;const m=new DataView(e.buffer,e.byteOffset+t,8),y=Number(m.getBigUint64(0,!1));t+=8;const g=new DataView(e.buffer,e.byteOffset+t,8);return{schemaVersion:r,messageType:a,hash:o,totalSize:s,date:d,name:h,chunkStartIndex:p,chunkEndIndex:y,chunkIndex:Number(g.getBigUint64(0,!1))}},xo={Text:1,ImagePNG:2,ImageJPEG:3,ImageJPG:4,ImageGIF:5,ImageBMP:6,ImageTIFF:7,ImageSVG:8,ImageWEBP:9,ImageHEIC:10,DocumentPDF:11,DocumentDOC:12,DocumentDOCX:13,DocumentXLS:14,DocumentXLSX:15,DocumentPPT:16,DocumentPPTX:17,DocumentTXT:18,DocumentRTF:19,DocumentODT:20,AudioMP3:21,AudioWAV:22,AudioAAC:23,AudioFLAC:24,AudioOGG:25,AudioM4A:26,VideoMP4:27,VideoAVI:28,VideoMKV:29,VideoMOV:30,VideoWMV:31,VideoFLV:32,VideoWEBM:33,CompressedZIP:34,CompressedRAR:35,Compressed7Z:36,CompressedTAR:37,CompressedGZ:38,CodeHTML:39,CodeCSS:40,CodeJS:41,CodeJSX:42,CodeTS:43,CodeTSX:44,CodeJSON:45,CodeXML:46,CodePY:47,CodeJAVA:48,CodeC:49,CodeCPP:50,CodeCS:51,CodeRB:52,CodePHP:53,CodeSQL:54,EbookEPUB:55,EbookMOBI:56,EbookAZW:57,FontTTF:58,FontOTF:59,ImageICO:60,ExecutableEXE:61,ExecutableDMG:62,ExecutableAPK:63,Unknown:64},Ko={Text:"Text",Image:"Image",Document:"Document",Audio:"Audio",Video:"Video",Compressed:"Compressed",Code:"Code",Ebook:"Ebook",Font:"Font",Executable:"Executable",Unknown:"Unknown"},Ro=e=>{switch(e){case xo.Text:return"text/plain";case xo.ImagePNG:return"image/png";case xo.ImageJPEG:case xo.ImageJPG:return"image/jpeg";case xo.ImageGIF:return"image/gif";case xo.ImageBMP:return"image/bmp";case xo.ImageTIFF:return"image/tiff";case xo.ImageSVG:return"image/svg+xml";case xo.ImageWEBP:return"image/webp";case xo.ImageHEIC:return"image/heic";case xo.ImageICO:return"image/vnd.microsoft.icon";case xo.DocumentPDF:return"application/pdf";case xo.DocumentDOC:return"application/msword";case xo.DocumentDOCX:return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case xo.DocumentXLS:return"application/vnd.ms-excel";case xo.DocumentXLSX:return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case xo.DocumentPPT:return"application/vnd.ms-powerpoint";case xo.DocumentPPTX:return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case xo.DocumentTXT:return"text/plain";case xo.DocumentRTF:return"application/rtf";case xo.DocumentODT:return"application/vnd.oasis.opendocument.text";case xo.AudioMP3:return"audio/mpeg";case xo.AudioWAV:return"audio/wav";case xo.AudioAAC:return"audio/aac";case xo.AudioFLAC:return"audio/flac";case xo.AudioOGG:return"audio/ogg";case xo.AudioM4A:return"audio/mp4";case xo.VideoMP4:return"video/mp4";case xo.VideoAVI:return"video/x-msvideo";case xo.VideoMKV:return"video/x-matroska";case xo.VideoMOV:return"video/quicktime";case xo.VideoWMV:return"video/x-ms-wmv";case xo.VideoFLV:return"video/x-flv";case xo.VideoWEBM:return"video/webm";case xo.CompressedZIP:return"application/zip";case xo.CompressedRAR:return"application/vnd.rar";case xo.Compressed7Z:return"application/x-7z-compressed";case xo.CompressedTAR:return"application/x-tar";case xo.CompressedGZ:return"application/gzip";case xo.CodeHTML:return"text/html";case xo.CodeCSS:return"text/css";case xo.CodeJS:case xo.CodeJSX:return"application/javascript";case xo.CodeTS:case xo.CodeTSX:return"application/typescript";case xo.CodeJSON:return"application/json";case xo.CodeXML:return"application/xml";case xo.CodePY:return"text/x-python";case xo.CodeJAVA:return"text/x-java-source";case xo.CodeC:return"text/x-c";case xo.CodeCPP:return"text/x-c++";case xo.CodeCS:return"text/plain";case xo.CodeRB:return"text/x-ruby";case xo.CodePHP:return"application/x-httpd-php";case xo.CodeSQL:return"application/sql";case xo.EbookEPUB:return"application/epub+zip";case xo.EbookMOBI:return"application/x-mobipocket-ebook";case xo.EbookAZW:return"application/vnd.amazon.ebook";case xo.FontTTF:return"font/ttf";case xo.FontOTF:return"font/otf";case xo.ExecutableEXE:return"application/vnd.microsoft.portable-executable";case xo.ExecutableDMG:return"application/x-apple-diskimage";case xo.ExecutableAPK:return"application/vnd.android.package-archive";default:return"application/octet-stream"}},Mo=(new TextEncoder).encode("p2party/protocol-v3/chunk-receipt/v1\0"),_o=async(e,t,n)=>{if(e.length!==N)throw new Error("Chunk receipt Merkle root must be 64 bytes");if(n.length!==N)throw new Error("Chunk receipt leaf hash must be 64 bytes");if(!Number.isSafeInteger(t)||t<0)throw new Error("Chunk receipt index must be a safe unsigned integer");const r=new Uint8Array(Mo.length+e.length+8+n.length);let a=0;return r.set(Mo,a),a+=Mo.length,r.set(e,a),a+=e.length,new DataView(r.buffer).setBigUint64(a,BigInt(t),!1),a+=8,r.set(n,a),new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",r))},Uo=e=>{const t=e._malloc(X),n=e._malloc(G);if(0!==e._x25519_keypair(t,n))throw e._free(t),Da(e,new Uint8Array(e.wasmMemory.buffer,n,G)),new Error("x25519_keypair failed");const r=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,t,X)),a=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,n,G));return e._free(t),Da(e,new Uint8Array(e.wasmMemory.buffer,n,G)),{publicKey:r,secretKey:a}},Do=async e=>{const t=e?.wasmMemory??ha(),n=e??await Ua(t);return Uo(n)},To=(e,t,n)=>{const r=n._malloc(X),a=n._malloc(G),o=n._malloc(X);new Uint8Array(n.wasmMemory.buffer,a,G).set(e),new Uint8Array(n.wasmMemory.buffer,o,X).set(t);const i=0===n._x25519_dh(r,a,o)?Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,r,X)):null;if(Da(n,new Uint8Array(n.wasmMemory.buffer,r,X)),Da(n,new Uint8Array(n.wasmMemory.buffer,a,G)),n._free(o),!i)throw new Error("x25519_dh failed (identity point)");return i},No=(e,t,n)=>{const r=Math.max(e.length,1),a=Math.max(t.length,1),o=n._malloc(T),i=n._malloc(r),s=n._malloc(a);try{new Uint8Array(n.wasmMemory.buffer,i,e.length).set(e),new Uint8Array(n.wasmMemory.buffer,s,t.length).set(t);if(0!==n._hkdf_sha512_extract(o,i,e.length,s,t.length))throw new Error("hkdf_sha512_extract failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,o,T))}finally{Da(n,new Uint8Array(n.wasmMemory.buffer,o,T)),Da(n,new Uint8Array(n.wasmMemory.buffer,i,r)),Da(n,new Uint8Array(n.wasmMemory.buffer,s,a))}},qo=(e,t,n,r)=>{const a=r._malloc(n),o=r._malloc(T),i=r._malloc(Math.max(t.length,1));try{new Uint8Array(r.wasmMemory.buffer,o,T).set(e),new Uint8Array(r.wasmMemory.buffer,i,t.length).set(t);if(0!==r._hkdf_sha512_expand(a,n,o,i,t.length))throw new Error("hkdf_sha512_expand failed");return Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,a,n))}finally{Da(r,new Uint8Array(r.wasmMemory.buffer,a,n)),Da(r,new Uint8Array(r.wasmMemory.buffer,o,T)),r._free(i)}},Oo=(new TextEncoder).encode("p2party-rk-v1"),Bo=(new TextEncoder).encode("p2party-ck-v1"),Lo=(new TextEncoder).encode("p2party-mk-v1"),Fo=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),zo=e=>{const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(2*n,2*n+2),16);return t},jo=(e,t,n)=>{const r=No(e,t,n),a=qo(r,Oo,64,n);r.fill(0);const o=a.slice(0,32),i=a.slice(32,64);return a.fill(0),{rootKey:o,chainKey:i}},Ho=(e,t)=>{const n=No(e,Lo,t),r=No(e,Bo,t),a=n.slice(0,32),o=r.slice(0,32);return n.fill(0),r.fill(0),{chainKey:o,messageKey:a}},$o=(e,t,n,r,a=ye)=>{const o=Uo(r),i={rootSuite:a,rootKey:Uint8Array.from(e),sendingChainKey:null,receivingChainKey:null,dhSelfPub:o.publicKey,dhSelfSec:o.secretKey,dhRemotePub:null,Ns:0,Nr:0,PN:0,skipped:new Map};if(t){if(!n)throw new Error("ratchet: initiator requires remoteDhPub");i.dhRemotePub=Uint8Array.from(n);const e=To(i.dhSelfSec,i.dhRemotePub,r),t=jo(i.rootKey,e,r);e.fill(0),i.rootKey.fill(0),i.rootKey=t.rootKey,i.sendingChainKey=t.chainKey}return i},Vo=(e,t)=>{if(!e.sendingChainKey)throw new Error("ratchet: no sending chain");const{chainKey:n,messageKey:r}=Ho(e.sendingChainKey,t),a={dhPub:Uint8Array.from(e.dhSelfPub),N:e.Ns,PN:e.PN};return e.sendingChainKey.fill(0),e.sendingChainKey=n,e.Ns+=1,{messageKey:r,header:a}},Qo=(e,t,n)=>{if(e.Nr+512<t)throw new Error("ratchet: MAX_SKIP exceeded");if(e.receivingChainKey){for(;e.Nr<t;){const{chainKey:t,messageKey:r}=Ho(e.receivingChainKey,n);e.receivingChainKey.fill(0),e.receivingChainKey=t,e.skipped.set(`${Fo(e.dhRemotePub)}:${e.Nr}`,r),e.Nr+=1}if(e.skipped.size>ge)for(const t of e.skipped.keys()){if(e.skipped.size<=ge)break;e.skipped.get(t)?.fill(0),e.skipped.delete(t)}}},Wo=(e,t,n)=>{e.PN=e.Ns,e.Ns=0,e.Nr=0,e.dhRemotePub=Uint8Array.from(t.dhPub);let r=To(e.dhSelfSec,e.dhRemotePub,n),a=jo(e.rootKey,r,n);r.fill(0),e.rootKey.fill(0),e.rootKey=a.rootKey,e.receivingChainKey?.fill(0),e.receivingChainKey=a.chainKey;const o=e.dhSelfSec,i=Uo(n);e.dhSelfPub=i.publicKey,e.dhSelfSec=i.secretKey,o.fill(0),r=To(e.dhSelfSec,e.dhRemotePub,n),a=jo(e.rootKey,r,n),r.fill(0),e.rootKey.fill(0),e.rootKey=a.rootKey,e.sendingChainKey?.fill(0),e.sendingChainKey=a.chainKey},Xo=(e,t,n)=>{if(!Number.isInteger(t.N)||t.N<0||!Number.isInteger(t.PN)||t.PN<0)throw new Error("invalid ratchet header");const r=((e,t)=>{const n=`${Fo(t.dhPub)}:${t.N}`,r=e.skipped.get(n);return r?(e.skipped.delete(n),r):null})(e,t);if(r)return r;if((!e.dhRemotePub||!((e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n})(t.dhPub,e.dhRemotePub))&&(Qo(e,t.PN,n),Wo(e,t,n)),t.N<e.Nr)throw new Error("ratchet: message key already consumed");Qo(e,t.N,n);const{chainKey:a,messageKey:o}=Ho(e.receivingChainKey,n);return e.receivingChainKey.fill(0),e.receivingChainKey=a,e.Nr+=1,o},Go=e=>e.slice().buffer,Jo=e=>e?e.slice().buffer:null,Yo=e=>({rootSuite:e.rootSuite,rootKey:Go(e.rootKey),sendingChainKey:Jo(e.sendingChainKey),receivingChainKey:Jo(e.receivingChainKey),dhSelfPub:Go(e.dhSelfPub),dhSelfSec:Go(e.dhSelfSec),dhRemotePub:Jo(e.dhRemotePub),Ns:e.Ns,Nr:e.Nr,PN:e.PN,skippedMessageKeys:Array.from(e.skipped.entries()).map(([e,t])=>{const n=e.lastIndexOf(":");return{dhPub:zo(e.slice(0,n)).slice().buffer,n:Number(e.slice(n+1)),messageKey:t.slice().buffer}})}),Zo=e=>{const t=new Map;for(const n of e.skippedMessageKeys){const e=new Uint8Array(n.dhPub);t.set(`${Fo(e)}:${n.n}`,new Uint8Array(n.messageKey))}return{rootSuite:e.rootSuite,rootKey:new Uint8Array(e.rootKey),sendingChainKey:e.sendingChainKey?new Uint8Array(e.sendingChainKey):null,receivingChainKey:e.receivingChainKey?new Uint8Array(e.receivingChainKey):null,dhSelfPub:new Uint8Array(e.dhSelfPub),dhSelfSec:new Uint8Array(e.dhSelfSec),dhRemotePub:e.dhRemotePub?new Uint8Array(e.dhRemotePub):null,Ns:e.Ns,Nr:e.Nr,PN:e.PN,skipped:t}},ei=e=>Zo(Yo(e)),ti=e=>{e.rootKey.fill(0),e.sendingChainKey?.fill(0),e.receivingChainKey?.fill(0),e.dhSelfSec.fill(0);for(const t of e.skipped.values())t.fill(0)},ni=(e,t)=>{if(e.rootSuite!==t.rootSuite)throw new Error("ratchet: cannot adopt a different root suite");ti(e),e.rootSuite=t.rootSuite,e.rootKey=t.rootKey,e.sendingChainKey=t.sendingChainKey,e.receivingChainKey=t.receivingChainKey,e.dhSelfPub=t.dhSelfPub,e.dhSelfSec=t.dhSelfSec,e.dhRemotePub=t.dhRemotePub,e.Ns=t.Ns,e.Nr=t.Nr,e.PN=t.PN,e.skipped=t.skipped},ri=(1n<<64n)-1n,ai=(e,t,n)=>{if(!Number.isInteger(n)||n<0||n>Number.MAX_SAFE_INTEGER)throw new Error("chunkFrame: ratchet counter out of safe-integer range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(t,BigInt(n),!1)},oi=(e,t)=>{const n=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(t,!1);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("chunkFrame: ratchet counter exceeds safe-integer range");return Number(n)},ii=(e,t,n=0n)=>{if(e.dhPub.length!==ce)throw new Error("chunkFrame: dhPub must be 32 bytes");if(t.length!==le)throw new Error("chunkFrame: nonce must be 12 bytes");const r=new Uint8Array(69);return r[0]=2,r.set(e.dhPub,1),ai(r,33,e.N),ai(r,41,e.PN),((e,t,n)=>{if("bigint"!=typeof n||n<0n||n>ri)throw new Error("chunkFrame: PQ epoch out of u64 range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(t,n,!1)})(r,49,n),r.set(t,57),r},si=e=>{if(e.length<69)throw new Error("chunkFrame: frame shorter than the header");if(2!==e[0])throw new Error("chunkFrame: leading byte is not FRAME_TYPE_CHUNK");return{header:{dhPub:e.subarray(1,33),N:oi(e,33),PN:oi(e,41)},pqEpoch:(t=e,n=49,new DataView(t.buffer,t.byteOffset,t.byteLength).getBigUint64(n,!1)),nonce:e.subarray(57,69),ciphertext:e.subarray(69)};var t,n},ci=z,li=(1n<<64n)-1n,di=(new TextEncoder).encode("p2party/pq-message-key/v1\0"),ui=(e,t,n)=>{if(!(e instanceof Uint8Array)||e.length!==n)throw new Error(`pqMessageKey: ${t} must be ${String(n)} bytes`)},hi=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new Error(`pqMessageKey: ${t} is outside the safe u64 range`)},fi=(e,t)=>{if("string"!=typeof(n=e.rootSuite)||!me.includes(n))throw new Error("pqMessageKey: unsupported root suite");var n;ui(e.rootKey,"rootKey",32),ui(e.binding,"binding",32),(e=>{if("bigint"!=typeof e||e<0n||e>li)throw new Error("pqMessageKey: epoch is outside the u64 range")})(e.epoch),ui(t.dhPub,"header.dhPub",ce),hi(t.N,"header.N"),hi(t.PN,"header.PN");const r=(new TextEncoder).encode(e.rootSuite);if(r.length>65535)throw new Error("pqMessageKey: root suite identifier is too long");const a=di.length+2+r.length+32+8+1+ce+8+8,o=new Uint8Array(a);let i=0;o.set(di,i),i+=di.length;const s=new DataView(o.buffer);return s.setUint16(i,r.length,!1),i+=2,o.set(r,i),i+=r.length,o.set(e.binding,i),i+=32,s.setBigUint64(i,e.epoch,!1),i+=8,o[i++]=2,o.set(t.dhPub,i),i+=ce,s.setBigUint64(i,BigInt(t.N),!1),i+=8,s.setBigUint64(i,BigInt(t.PN),!1),o},pi=(e,t,n,r)=>{if(!(e instanceof Uint8Array))throw new Error("pqMessageKey: classicalMessageKey must be a Uint8Array");if(t?.rootKey instanceof Uint8Array&&(a=e,o=t.rootKey,a.buffer===o.buffer&&a.byteOffset<o.byteOffset+o.byteLength&&o.byteOffset<a.byteOffset+a.byteLength))throw new Error("pqMessageKey: classicalMessageKey must not alias context.rootKey");var a,o;let i=null,s=null;try{ui(e,"classicalMessageKey",ci);const a=fi(t,n);return i=Uint8Array.from(t.rootKey),s=No(i,e,r),qo(s,a,ci,r)}finally{e.fill(0),i?.fill(0),s?.fill(0)}},mi=z,yi=j,gi=H,wi=N+57,bi=(1n<<64n)-1n,vi=(e,t,n)=>{const r=`${a=e,Array.from(a,e=>e.toString(16).padStart(2,"0")).join("")}:${t}`;var a;if(void 0===n)return r;if("bigint"!=typeof n||n<0n||n>bi)throw new Error("messageChunkCrypto: PQ epoch out of u64 range");return`${r}:${n.toString(10)}`},ki=(e,t,n,r)=>{const a=e._malloc(J),o=e._malloc(ae),i=e._malloc(N),s=e._malloc(mi),c=new Uint8Array(e.wasmMemory.buffer,a,J),l=new Uint8Array(e.wasmMemory.buffer,o,ae);c.fill(0),l.fill(0),c.set(t.subarray(0,J),0),new Uint8Array(e.wasmMemory.buffer,i,N).set(n),new Uint8Array(e.wasmMemory.buffer,s,mi).set(r);const d=e._receive_message_with_key(o,a,i,s),u=0===d?Uint8Array.from(l):null;return e._free(a),e._free(i),Da(e,new Uint8Array(e.wasmMemory.buffer,s,mi)),Da(e,l),{code:d,decrypted:u}},Ii=(e,t,n,r,a,o)=>{if(r.length!==N)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const i=(()=>{const e=new Uint8Array(yi);return crypto.getRandomValues(e),e})(),s=ii(t,i,o?.epoch??0n),c=((e,t)=>{if(t.length<57)throw new Error("messageChunkCrypto: incomplete chunk frame header");const n=new Uint8Array(wi);return n.set(e,0),n.set(t.subarray(0,57),N),n})(r,s);let l=null;try{const r=((e,t,n,r,a)=>{const o=Math.max(r.length,1),i=Math.max(a.length,1),s=r.length+gi,c=e._malloc(mi),l=e._malloc(yi),d=e._malloc(o),u=e._malloc(i),h=e._malloc(s);new Uint8Array(e.wasmMemory.buffer,c,mi).set(t),new Uint8Array(e.wasmMemory.buffer,l,yi).set(n),r.length&&new Uint8Array(e.wasmMemory.buffer,d,r.length).set(r),a.length&&new Uint8Array(e.wasmMemory.buffer,u,a.length).set(a);const f=0===e._encrypt_chachapoly_symmetric(h,d,r.length,c,l,u,a.length)?Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,h,s)):null;if(Da(e,new Uint8Array(e.wasmMemory.buffer,c,mi)),e._free(l),Da(e,new Uint8Array(e.wasmMemory.buffer,d,o)),e._free(u),Da(e,new Uint8Array(e.wasmMemory.buffer,h,s)),!f)throw new Error("messageChunkCrypto: AEAD encrypt failed");return f})(a,o?l=pi(Uint8Array.from(e),o,t,a):e,i,n,c),d=new Uint8Array(s.length+r.length);return d.set(s,0),d.set(r,s.length),d}finally{l?.fill(0)}},Si=(e,t,n,r,a,o)=>{if(r.length!==N)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const{header:i,pqEpoch:s}=si(t);let c=null;if(o){try{c=o(s)}catch{return{decrypted:null,ok:!1,stateAdvanced:!1}}if(!(c&&(l=c,d=s,u=e.rootSuite,l.epoch===d&&l.rootSuite===u&&l.rootKey instanceof Uint8Array&&32===l.rootKey.length&&l.binding instanceof Uint8Array&&32===l.binding.length)))return{decrypted:null,ok:!1,stateAdvanced:!1}}else if(0n!==s)return{decrypted:null,ok:!1,stateAdvanced:!1};var l,d,u;const h=vi(i.dhPub,i.N,o?s:void 0),f=n.get(h);if(f){const{code:e,decrypted:n}=ki(a,t,r,f);return{decrypted:0===e?n:null,ok:0===e,stateAdvanced:!1}}const p=ei(e);let m;try{m=Ci(p,i,a),c&&(m=pi(m,c,i,a))}catch{return ti(p),{decrypted:null,ok:!1,stateAdvanced:!1}}const{code:y,decrypted:g}=ki(a,t,r,m);return-2===y?(m.fill(0),ti(p),{decrypted:null,ok:!1,stateAdvanced:!1}):(ni(e,p),n.set(h,m),{decrypted:0===y?g:null,ok:0===y,stateAdvanced:!0})},Ci=(e,t,n)=>{try{return Xo(e,t,n)}catch(t){throw ti(e),t}},Ai=(e,t)=>`${e.length}:${e}${t.length}:${t}`,Ei=new Map,Pi=new Map,xi=new WeakMap,Ki=async(e,t,n)=>{const r=Ai(e,t),a=Ei.get(r)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=a.catch(()=>{}).then(()=>i);Ei.set(r,s),await a.catch(()=>{});try{return await n()}finally{o(),Ei.get(r)===s&&Ei.delete(r)}},Ri=(e,t)=>{const n=Ai(t,e.withPeerPublicKey),r=xi.get(e);if(r){if(Pi.get(n)!==r)throw new Error("ratchet persistence: stale connection cannot reclaim edge");return}const a=Symbol(n);xi.set(e,a),Pi.set(n,a)},Mi=(e,t)=>{const n=Ai(t,e.withPeerPublicKey),r=xi.get(e);if(!r||Pi.get(n)!==r)throw new Error("ratchet persistence: stale connection owner")},_i=async(e,t,n,r,a=null)=>{const o=Yo(e),i={rootSuite:o.rootSuite,roomId:t,peerPublicKey:n,peerId:r,rootKey:o.rootKey,sendingChainKey:o.sendingChainKey,receivingChainKey:o.receivingChainKey,dhSelfPub:o.dhSelfPub,dhSelfSec:o.dhSelfSec,dhRemotePub:o.dhRemotePub,Ns:o.Ns,Nr:o.Nr,PN:o.PN,skippedMessageKeys:o.skippedMessageKeys,edgeCryptoState:null===a?null:a.slice().buffer,updatedAt:Date.now()};try{await(e=>Wa("setRatchetSession",e))(i)}finally{(e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)})(i)}},Ui=async(e,t,n,r,a=null)=>Ki(t,n,()=>_i(e,t,n,r,a)),Di=async(e,t,n,r,a=_i,o=so)=>Ki(n,e.withPeerPublicKey,async()=>{Mi(e,n);let i=!1;const s=e.serializeEdgeCryptoState?.()??null;try{i=!0,await a(t,n,e.withPeerPublicKey,e.withPeerId,s),Mi(e,n),r()}catch(t){if(i)try{await o(n,e.withPeerPublicKey)}catch(e){throw new AggregateError([t,e],"Ratchet establishment failed and persisted-seed rollback failed",{cause:e})}throw t}finally{s?.fill(0)}}),Ti=new WeakMap,Ni=async(e,t)=>{const n=Ti.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>a);Ti.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),Ti.get(e)===o&&Ti.delete(e)}},qi=async(e,t,n,r)=>Ni(e,async()=>{const a=e.ratchetState;if(!a)throw new Error("ratchet persistence: no live ratchet state");const o=ei(a);let i,s=!1;try{if(i=n(o),i.advanced){const n=i.stageEdgeCryptoState;if(r===Ui)await Ki(t,e.withPeerPublicKey,async()=>{if(Mi(e,t),e.ratchetState!==a)throw new Error("ratchet persistence: live state changed");const r=n?.()??e.serializeEdgeCryptoState?.()??null;try{await _i(o,t,e.withPeerPublicKey,e.withPeerId,r)}finally{r?.fill(0)}Mi(e,t)});else{const a=n?.()??e.serializeEdgeCryptoState?.()??null;try{await r(o,t,e.withPeerPublicKey,e.withPeerId,a)}finally{a?.fill(0)}}if(e.ratchetState!==a)throw new Error("ratchet persistence: live state changed");ni(a,o),s=!0}else ti(o);return i.commit?.(),i.value}catch(e){throw s||ti(o),i?.rollback?.(),e}}),Oi=async(e,t,n,r=Ui)=>qi(e,t,t=>{const r=Vo(t,n),a=e.pqHealingState;let o=null;if(a){const e=a.currentMessageContext();o={rootKey:Uint8Array.from(e.rootKey),binding:Uint8Array.from(e.binding),rootSuite:e.rootSuite,epoch:e.epoch}}return{value:{messageKey:r.messageKey,header:r.header,pqContext:o},advanced:!0,commit:()=>e.pqHealingState?.noteApplicationMessage(),rollback:()=>{r.messageKey.fill(0),o?.rootKey.fill(0)}}},r),Bi=async(e,t,n,r,a=Ui)=>qi(e,t,t=>{const a=e.pqHealingState;if(a){if(!n.has(r))return{value:void 0,advanced:!1};const e=new Map(n);return e.delete(r),{value:void 0,advanced:!0,stageEdgeCryptoState:()=>a.serialize(e),commit:()=>{n.get(r)?.fill(0),n.delete(r)}}}const o=t.skipped.get(r);return o&&(t.skipped.delete(r),o.fill(0)),{value:void 0,advanced:void 0!==o,commit:()=>{n.get(r)?.fill(0),n.delete(r)}}},a),Li=new WeakMap,Fi=async(e,t,n,r=Bi)=>{let a=Li.get(e);const o=a?.get(n);if(o)return o;const i=(async()=>{const a=e.messageKeyByMerkleRoot?.get(n),o=e.messageKeyCache;return!(!a||!o)&&(await r(e,t,o,a),e.messageKeyByMerkleRoot?.get(n)===a&&e.messageKeyByMerkleRoot.delete(n),!0)})();a??=new Map,a.set(n,i),Li.set(e,a);try{return await i}finally{a.get(n)===i&&a.delete(n),0===a.size&&Li.delete(e)}},zi=async(e,t,n,r,a=Bi)=>!!(e=>void 0!==e&&Number.isSafeInteger(e.savedSize)&&Number.isSafeInteger(e.totalSize)&&e.savedSize>=0&&e.totalSize>0&&e.savedSize===e.totalSize)(r)&&Fi(e,t,n,a),ji=()=>({date:new Date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!1,totalSize:0,messageType:xo.Text,filename:"",chunkHash:new Uint8Array,messageHash:new Uint8Array}),Hi=async(e,t,n=no)=>{try{return await n({...e,data:t.buffer})}catch(e){return console.error("Could not durably store received chunk",e),null}finally{t.fill(0)}},$i=async(e,t,n,r,a,o,i,s={})=>{if(i?.aborted)return ji();if(!r.ratchetState)return console.error("v3 receive: no ratchet state for peer"),ji();r.messageKeyCache||(r.messageKeyCache=r.pqHealingState?.activeReceiveKeys??new Map);const c=r.messageKeyCache;let l;try{const{header:t,pqEpoch:n}=si(e);l=vi(t.dhPub,t.N,r.pqHealingState?n:void 0)}catch{return ji()}if(c.size>=256)for(const e of c.keys()){if(c.size<256)break;if(c.get(e)?.fill(0),c.delete(e),r.messageKeyByMerkleRoot)for(const[t,n]of r.messageKeyByMerkleRoot)n===e&&r.messageKeyByMerkleRoot.delete(t)}let d,u;try{const n=await(async(e,t,n,r,a,o,i=Ui)=>qi(e,t,t=>{const i=e.pqHealingState,{header:s,pqEpoch:c}=si(n),l=vi(s.dhPub,s.N,i?c:void 0),d=new Map(r),u=Si(t,n,d,a,o,i?e=>i.resolveMessageContext(e):void 0);if(!u.stateAdvanced)return{value:u,advanced:!1};const h=d.get(l);if(!h||r.has(l))throw u.decrypted?.fill(0),new Error("ratchet persistence: invalid staged receive cache");if(i)return{value:u,advanced:!0,stageEdgeCryptoState:()=>i.serialize(d),commit:()=>{r.set(l,h),i.noteApplicationMessage()},rollback:()=>{h.fill(0),u.decrypted?.fill(0)}};const f=Uint8Array.from(h);for(t.skipped.set(l,f);t.skipped.size>ge;){const e=t.skipped.keys().next().value;if(void 0===e)break;t.skipped.get(e)?.fill(0),t.skipped.delete(e)}return{value:u,advanced:!0,commit:()=>r.set(l,h),rollback:()=>{f.fill(0),h.fill(0),u.decrypted?.fill(0)}}},i))(r,t,e,c,a,o,s.persistRatchetState);d=n.decrypted,u=n.ok}catch(e){return console.error("Could not durably decrypt message",e),ji()}if(!u||!d)return console.error("Could not decrypt or verify message"),ji();const h=ca(a);((e,t,n)=>{e.messageKeyByMerkleRoot??=new Map,e.messageKeyByMerkleRoot.set(t,n)})(r,h,l);try{if(i?.aborted)return ji();const e=d.subarray(0,ee),o=d.slice(ee,ee+N),c=d.subarray(ee+te),l=Po(e);(e=>{if(1!==e.schemaVersion)throw new Error("Unsupported metadata schema version");if(!Number.isSafeInteger(e.messageType)||e.messageType<1||e.messageType>64)throw new Error("Invalid metadata message type");if(e.hash.length!==N)throw new Error("Invalid metadata hash");if(!Number.isSafeInteger(e.totalSize)||e.totalSize<1||e.totalSize>Y)throw new Error("Invalid metadata total size");if(!Number.isSafeInteger(e.date.getTime()))throw new Error("Invalid metadata timestamp");for(const[t,n]of[["chunkStartIndex",e.chunkStartIndex],["chunkEndIndex",e.chunkEndIndex],["chunkIndex",e.chunkIndex]])if(!Number.isSafeInteger(n)||n<0)throw new Error(`Invalid metadata ${t}`);if(e.chunkEndIndex<e.chunkStartIndex)throw new Error("Invalid metadata chunk range")})(l);const u=l.chunkEndIndex-l.chunkStartIndex>l.totalSize||l.chunkEndIndex-l.chunkStartIndex>J?0:l.chunkEndIndex-l.chunkStartIndex,y=()=>({date:l.date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!0,totalSize:l.totalSize,messageType:l.messageType,filename:l.name,chunkHash:o,messageHash:l.hash});if(0===u)return y();if(f=l.chunkStartIndex,p=l.chunkEndIndex,m=c.length,!(Number.isSafeInteger(f)&&Number.isSafeInteger(p)&&f>=0&&p>=f&&p<=m))return y();const g=await _o(a,l.chunkIndex,o);if(i?.aborted)return g.fill(0),ji();const w=Ro(l.messageType),b=c.slice(l.chunkStartIndex,l.chunkEndIndex),v=await Hi({schemaVersion:l.schemaVersion,roomId:t,fromPeerId:r.withPeerId,channelLabel:n,timestamp:l.date.getTime(),merkleRoot:h,hash:ca(l.hash),filename:l.name,messageType:l.messageType,chunkIndex:l.chunkIndex,mimeType:w,leafHash:ca(o),realLen:u,totalSize:l.totalSize,storage:l.messageType===xo.Text?"indexeddb":"opfs"},b,s.storeReceiveChunk);if(!v)return g.fill(0),ji();if(i?.aborted)return g.fill(0),ji();const k=v.complete;return{date:l.date,chunkIndex:l.chunkIndex,chunkSize:u,receivedFullSize:k,chunkAlreadyExists:!v.stored,totalSize:l.totalSize,messageType:l.messageType,filename:l.name,chunkHash:g,messageHash:l.hash}}catch(e){return console.error("Could not parse or store decrypted message",e),ji()}finally{d.fill(0)}var f,p,m},Vi=new Map,Qi=(e,t)=>`${e}\0${t}`,Wi=(e,t)=>{const n=Qi(e,t);let r=Vi.get(n);if(!r){let e,t;const a=new Promise((n,r)=>{e=n,t=r});a.catch(()=>{}),r={promise:a,resolve:e,reject:t,settled:!1,outcome:"pending",lease:{token:Symbol("ratchet-gate")}},Vi.set(n,r)}return r},Xi=(e,t)=>Wi(e,t).promise,Gi=(e,t,n)=>Vi.get(Qi(e,t))?.lease===n,Ji=(e,t,n)=>{const r=Vi.get(Qi(e,t));return"open"===r?.outcome&&(void 0===n||r.lease===n)},Yi=(e,t,n,r)=>{const a=Wi(e,t);return(!r||a.lease===r)&&(a.settled||(a.settled=!0,a.outcome="rejected",a.reject(n)),!0)},Zi=e=>{if(e.length!==oe)throw new Error("Receipt token must be exactly 64 bytes");const t=new Uint8Array(ie);return t[0]=3,t.set(e,1),t},es=(e,t)=>"open"===e.readyState&&(e.send(Zi(t).buffer),!0),ts=async(e,t)=>{let n=0;for(const r of t){for(;"open"===e.readyState&&e.bufferedAmount>=Z;)await new Promise(e=>setTimeout(e,25));if("open"!==e.readyState)return!1;e.send(Zi(r).buffer),n++,32===n&&(n=0,await new Promise(e=>setTimeout(e,10)))}return"open"===e.readyState},ns=new WeakMap,rs=(e,t,n)=>{const r=e.coverRuntime;if(!r)return!1;if(64!==t.length||64!==n.length)return!1;const a=(e=>{let t=ns.get(e);return t||(t={pending:[],drainJobActive:!1,jobSequence:0},ns.set(e,t)),t})(e);for(a.pending.push({merkleRoot:Uint8Array.from(t),token:Uint8Array.from(n)});a.pending.length>4096;)a.pending.shift();return as(e,r,a),!0},as=(e,t,n)=>{if(n.drainJobActive||0===n.pending.length)return;const r=t.cellsPerLanePerCycle(),a=Math.min(n.pending.length,r);if(a<=0)return;n.drainJobActive=!0,n.jobSequence+=1;const o={id:t.randomLaneLabel(),kind:"control",declaredCellCount:a,nextCell:()=>{const e=n.pending.shift();if(!e)return null;try{return t.sealCoverContent({subtype:"receipt",merkleRoot:e.merkleRoot,token:e.token})}finally{e.merkleRoot.fill(0),e.token.fill(0)}}};try{t.enqueue(o)}catch(e){return n.drainJobActive=!1,void console.error("coverTransfer: could not enqueue receipt drain job",e)}t.onJobSettled(o.id,()=>{n.drainJobActive=!1,as(e,t,n)})},os=e=>{const t=ns.get(e);if(t){for(const e of t.pending)e.merkleRoot.fill(0),e.token.fill(0);t.pending.length=0,t.drainJobActive=!1,ns.delete(e)}},is=e=>{const t=e.runtime.cellsPerLanePerCycle();if(e.totalChunks>t)throw new Error(`coverTransfer: message of ${String(e.totalChunks)} cells exceeds the room F×D capacity of ${String(t)}`);const n=e.realChunkIndices??Array.from({length:e.totalChunks},(e,t)=>t);let r=0;return{id:e.channelMessageLabel,kind:"real",declaredCellCount:e.totalChunks,nextCell:async t=>{const a=(()=>{const t=e.getAckedChunks?.()??ss;for(;r<n.length;){const e=n[r];if(r+=1,!t.has(e))return e}return null})();if(null===a)return null;const o=await e.sealSlotCell(a);if(null===o)return null;if(o.length!==de)throw new Error("coverTransfer: sealed transfer cell is not the uniform length");return o}}},ss=new Set,cs=e=>{if(e.byteLength<32)return`${String(e.byteLength)}:${ca(e)}`;const t=new DataView(e.buffer,e.byteOffset,16),n=new DataView(e.buffer,e.byteOffset+e.byteLength-16,16);return t.getBigUint64(0,!1).toString(16).padStart(16,"0")+t.getBigUint64(8,!1).toString(16).padStart(16,"0")+n.getBigUint64(0,!1).toString(16).padStart(16,"0")+n.getBigUint64(8,!1).toString(16).padStart(16,"0")},ls=new Map,ds=new Map,us=new WeakMap,hs=new Map,fs=(e,t)=>`${String(e.length)}:${e}${t}`,ps=(e,t)=>{if(t.value||e.length>0)return;const n=t.idleWaiters;if(t.idleWaiters=void 0,n)for(const e of n)e()},ms=(e,t)=>t.value||0!==e.length?new Promise(e=>{t.idleWaiters??=new Set,t.idleWaiters.add(e)}):Promise.resolve(),ys=(e,t,n,r)=>{const a=Math.max(0,(us.get(e)??0)+r);0===a?us.delete(e):us.set(e,a);const o=fs(t,n),i=Math.max(0,(ds.get(o)??0)+r);0===i?ds.delete(o):ds.set(o,i)},gs=async(e,t)=>{const n=ls.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.then(()=>a);ls.set(e,o),await n;try{return await t()}finally{r(),ls.get(e)===o&&ls.delete(e)}},ws=(e,t)=>{const n=fs(e.roomId,e.peerId),r=Math.max(0,(hs.get(n)??0)+t);0===r?hs.delete(n):hs.set(n,r)},bs=async(e,t)=>{if(e.draining||e.released)return;e.draining=!0;const n=fs(e.roomId,e.peerId);try{for(;!e.released;){const r=e.pending.shift();if(!r)break;ws(e,-1);try{await gs(n,()=>t(r))}finally{e.seen.delete(cs(r))}}}catch(e){console.error(e)}finally{e.draining=!1,!e.released&&e.pending.length>0&&bs(e,t)}},vs=async(e,t,n,r,a,o,i,s,c,l,d)=>{if(d?.aborted)return{receivedFullSize:!1};if(c)try{const u=c.ratchetGateLease;if(!Gi(n,r,u))return{receivedFullSize:!1};if(await Xi(n,r),d?.aborted)return{receivedFullSize:!1};if(!Gi(n,r,u))return{receivedFullSize:!1};const h=await $i(e,n,a,c,i,l,d),{date:f,chunkSize:p,chunkIndex:m,receivedFullSize:y,chunkAlreadyExists:g,totalSize:w,messageType:b,filename:v,messageHash:k}=h;if(d?.aborted)return{receivedFullSize:!1};c?.coverRuntime||((e,t)=>{if(e.totalSize>0&&e.chunkHash.length===N&&e.chunkIndex>-1&&e.chunkSize>0)return!!t&&es(t,e.chunkHash);if("open"!==t?.readyState)return!1;const n=new Uint8Array(N);crypto.getRandomValues(n),es(t,n)})(h,s);const I=ca(k);return y&&c?.coverRuntime&&rs(c,i,i),y?(await(e=>Wa("closeReceiveFile",e))(o),t.dispatch(lt({roomId:n,merkleRootHex:o,sha512Hex:I,fromPeerId:r,totalSize:w,messageType:b,filename:v,channelLabel:a,timestamp:f.getTime(),alsoSendFinishedMessage:!0})),(e=>void 0===e?.coverRuntime)(c)&&s&&es(s,k)):p>0&&m>-1&&!g&&t.dispatch(ct({roomId:n,merkleRootHex:o,sha512Hex:I,fromPeerId:r,chunkSize:p,totalSize:w,messageType:b,filename:v,channelLabel:a,timestamp:f.getTime()})),t.dispatch(dt({roomId:n,merkleRootHex:o,real:p>0&&m>-1&&!g})),{receivedFullSize:y}}catch(e){return console.error(e),{receivedFullSize:!1}}return{receivedFullSize:!1}},ks=async(e,t,n,r,a,o,i,s,c,l,d,u,h)=>{if(n.value||n.released||h?.aborted)return;n.value=!0;const f=fs(a,o);try{for(;!n.released&&!h?.aborted;){const t=e.pop();if(!t)break;ys(e,a,o,-t.byteLength),await gs(f,async()=>vs(t,r,a,o,i,s,c,l,d,u,h))}}finally{n.value=!1,e.length>0&&!n.released&&!h?.aborted?ks(e,t,n,r,a,o,i,s,c,l,d,u,h):ps(e,n)}},Is=e=>Object.freeze({...e,wasmExports:Object.freeze({...e.wasmExports})}),Ss=Is({parameterSet:512,standardName:"ML-KEM-512",publicKeyBytes:800,secretKeyBytes:1632,ciphertextBytes:768,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem512_keypair",encaps:"_mlkem512_encaps",decaps:"_mlkem512_decaps"}}),Cs=Is({parameterSet:768,standardName:"ML-KEM-768",publicKeyBytes:1184,secretKeyBytes:2400,ciphertextBytes:1088,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem768_keypair",encaps:"_mlkem768_encaps",decaps:"_mlkem768_decaps"}}),As=Is({parameterSet:1024,standardName:"ML-KEM-1024",publicKeyBytes:1568,secretKeyBytes:3168,ciphertextBytes:1568,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem1024_keypair",encaps:"_mlkem1024_encaps",decaps:"_mlkem1024_decaps"}}),Es=Object.freeze({512:Ss,768:Cs,1024:As}),Ps=e=>{const t=Es[e];if(void 0===t)throw new RangeError(`unsupported ML-KEM parameter set: ${String(e)}`);return t},xs=(e,t,n)=>{if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(e.length!==n)throw new RangeError(`${t} must be exactly ${String(n)} bytes`)},Ks=(e,t,n,r)=>{const a=e._malloc(n);if(0===a)throw new Error(`${t.standardName}: failed to allocate ${r}`);return a},Rs=(e,t,n)=>new Uint8Array(e.wasmMemory.buffer,t,n),Ms=(e,t)=>{void 0!==t&&e._free(t)},_s=(e,t,n)=>{void 0!==t&&Da(e,Rs(e,t,n))};class Us{#e;#t;suite;constructor(e,t){this.#e=e,this.suite=t,this.#t=((e,t)=>{const n=e,r=t.wasmExports,a=[r.keypair,r.encaps,r.decaps].filter(e=>"function"!=typeof n[e]);if(0!==a.length)throw new Error(`${t.standardName} WASM exports are unavailable; rebuild libcrypto.wasm (missing ${a.join(", ")})`);return{keypair:n[r.keypair].bind(e),encaps:n[r.encaps].bind(e),decaps:n[r.decaps].bind(e)}})(e,t)}async generateKeyPair(){await Promise.resolve();const e=this.#e,t=this.suite;let n,r,a;try{n=Ks(e,t,t.publicKeyBytes,"public key"),r=Ks(e,t,t.secretKeyBytes,"secret key"),a=Ks(e,t,t.keyPairRandomBytes,"key-generation randomness");const o=Rs(e,a,t.keyPairRandomBytes);Pa(o);const i=this.#t.keypair(n,r,a);if(0!==i)throw new Error(`${t.standardName} key generation failed (${String(i)})`);return((e,t)=>{let n=!1;return{publicKey:e,secretKey:t,get destroyed(){return n},destroy(){n||(t.fill(0),n=!0)}}})(Uint8Array.from(Rs(e,n,t.publicKeyBytes)),Uint8Array.from(Rs(e,r,t.secretKeyBytes)))}finally{Ms(e,n),_s(e,r,t.secretKeyBytes),_s(e,a,t.keyPairRandomBytes)}}async encapsulate(e){await Promise.resolve();const t=this.#e,n=this.suite;let r,a,o,i;xs(e,`${n.standardName} public key`,n.publicKeyBytes);try{r=Ks(t,n,n.ciphertextBytes,"ciphertext"),a=Ks(t,n,n.sharedSecretBytes,"shared secret"),o=Ks(t,n,n.publicKeyBytes,"public key"),i=Ks(t,n,n.encapsRandomBytes,"encapsulation randomness"),Rs(t,o,n.publicKeyBytes).set(e);const s=Rs(t,i,n.encapsRandomBytes);Pa(s);const c=this.#t.encaps(r,a,o,i);if(0!==c)throw new Error(`${n.standardName} encapsulation failed (${String(c)})`);return((e,t)=>{let n=!1;return{ciphertext:e,sharedSecret:t,get destroyed(){return n},destroy(){n||(t.fill(0),n=!0)}}})(Uint8Array.from(Rs(t,r,n.ciphertextBytes)),Uint8Array.from(Rs(t,a,n.sharedSecretBytes)))}finally{Ms(t,r),_s(t,a,n.sharedSecretBytes),Ms(t,o),_s(t,i,n.encapsRandomBytes)}}async decapsulate(e,t){await Promise.resolve();const n=this.#e,r=this.suite;let a,o,i;xs(e,`${r.standardName} ciphertext`,r.ciphertextBytes),xs(t,`${r.standardName} secret key`,r.secretKeyBytes);try{a=Ks(n,r,r.sharedSecretBytes,"shared secret"),o=Ks(n,r,r.ciphertextBytes,"ciphertext"),i=Ks(n,r,r.secretKeyBytes,"secret key"),Rs(n,o,r.ciphertextBytes).set(e),Rs(n,i,r.secretKeyBytes).set(t);const s=this.#t.decaps(a,o,i);if(0!==s)throw new Error(`${r.standardName} decapsulation failed (${String(s)})`);return(e=>{let t=!1;return{sharedSecret:e,get destroyed(){return t},destroy(){t||(e.fill(0),t=!0)}}})(Uint8Array.from(Rs(n,a,r.sharedSecretBytes)))}finally{_s(n,a,r.sharedSecretBytes),Ms(n,o),_s(n,i,r.secretKeyBytes)}}}const Ds=(e,t)=>{const n=Ps(t.parameterSet);if(t!==n)throw new TypeError("ML-KEM suite descriptor must be one of the exported canonical suites");return new Us(e,n)},Ts=32,Ns=32,qs=64,Os=new Uint8Array([80,50,81,72]),Bs=(new TextEncoder).encode("p2party/pq-healing/root/v1\0"),Ls=(1n<<64n)-1n;class Fs extends Error{code;constructor(e,t){super(`pqHealing: ${t}`),this.name="PqHealingError",this.code=e}}const zs=(e,t)=>{throw new Fs(e,t)},js=(e,t,n)=>e instanceof Uint8Array?e.length!==n?zs("invalid-record",`${t} must be exactly ${String(n)} bytes`):e:zs("invalid-record",`${t} must be a Uint8Array`),Hs=(e,t)=>{("bigint"!=typeof e||e<0n||e>Ls)&&zs("overflow",`${t} is outside the unsigned 64-bit range`)},$s=(e,t)=>{Hs(e,t),e===Ls&&zs("overflow",`${t} cannot advance beyond uint64`)},Vs=e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return zs("invalid-record","advance acknowledgement must be a plain record");const t=e,n=Reflect.ownKeys(t);2===n.length&&n.includes("epoch")&&n.includes("advanceCounter")||zs("invalid-record","advance acknowledgement must contain only epoch and advanceCounter");const r=Object.getOwnPropertyDescriptor(t,"epoch"),a=Object.getOwnPropertyDescriptor(t,"advanceCounter");if(!(void 0!==r&&void 0!==a&&"value"in r&&"value"in a&&r.enumerable&&a.enumerable))return zs("invalid-record","advance acknowledgement fields must be enumerable data properties");const o=r.value,i=a.value;return"bigint"!=typeof o||"bigint"!=typeof i?zs("invalid-record","advance acknowledgement fields must be bigint values"):(Hs(o,"advance acknowledgement epoch"),Hs(i,"advance acknowledgement counter"),{epoch:o,advanceCounter:i})},Qs=(e,t,n)=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return zs("invalid-record",`${t} must be a plain record`);const r=e,a=Reflect.ownKeys(r);if(a.length!==n.length||n.some(e=>!a.includes(e)))return zs("invalid-record",`${t} does not contain exactly its canonical fields`);for(const e of n){const n=Object.getOwnPropertyDescriptor(r,e);void 0!==n&&"value"in n&&n.enumerable||zs("invalid-record",`${t}.${e} must be an enumerable data property`)}return r},Ws=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},Xs=e=>768===e?1:512===e?2:1024===e?3:zs("suite-mismatch","unsupported ML-KEM parameter set"),Gs=e=>1===e?768:2===e?512:3===e?1024:zs("invalid-record","record has an unknown ML-KEM suite tag"),Js=(e,t)=>Reflect.get(e,t),Ys=e=>{const t=Ps(e.parameterSet);e.standardName===t.standardName&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes&&Js(e,"sharedSecretBytes")===t.sharedSecretBytes&&Js(e,"keyPairRandomBytes")===t.keyPairRandomBytes&&Js(e,"encapsRandomBytes")===t.encapsRandomBytes||zs("suite-mismatch","selected suite does not match its canonical FIPS 203 descriptor")},Zs=(e,t)=>{Ys(e),Ys(t),e.parameterSet===t.parameterSet&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes||zs("suite-mismatch","room-selected suite does not exactly match the ML-KEM backend")},ec=e=>qs+e.publicKeyBytes,tc=e=>qs+ec(e)+e.ciphertextBytes,nc=(e,t,n)=>{Ys(t),js(n,"binding",Ts),js(e,"ACK",64),Ws(e.subarray(0,4),Os)||zs("invalid-record","ACK magic is invalid"),1!==e[4]&&zs("invalid-record","ACK version is unsupported"),3!==e[5]&&zs("invalid-record","ACK type is unexpected"),0!==e[7]&&zs("invalid-record","ACK reserved flags must be zero");Gs(e[6])!==t.parameterSet&&zs("suite-mismatch","ACK suite differs from the authenticated room suite"),Ws(e.subarray(8,40),n)||zs("binding-mismatch","ACK belongs to a different authenticated edge");const r=new DataView(e.buffer,e.byteOffset,e.byteLength);return 0n!==r.getBigUint64(56,!1)&&zs("invalid-record","ACK reserved bytes must be zero"),{advanceCounter:r.getBigUint64(40,!1),epoch:r.getBigUint64(48,!1)}},rc=(e,t,n,r,a,o,i)=>{js(n,"binding",Ts),Hs(r,"sender counter"),Hs(a,"from epoch"),Hs(o,"to epoch"),a!==Ls&&o===a+1n||zs("invalid-record","record must advance exactly one PQ epoch");const s=new Uint8Array(i);s.set(Os,0),s[4]=1,s[5]=e,s[6]=Xs(t.parameterSet),s[7]=0,s.set(n,8);const c=new DataView(s.buffer,s.byteOffset,s.byteLength);return c.setBigUint64(40,r,!1),c.setBigUint64(48,a,!1),c.setBigUint64(56,o,!1),s},ac=(e,t,n,r)=>{e instanceof Uint8Array||zs("invalid-record","record must be a Uint8Array"),e.length<qs&&zs("invalid-record","record is shorter than its canonical header"),Ws(e.subarray(0,4),Os)||zs("invalid-record","record magic is invalid"),1!==e[4]&&zs("invalid-record","record version is unsupported"),e[5]!==t&&zs("invalid-record","record type is unexpected"),0!==e[7]&&zs("invalid-record","record reserved flags must be zero");Gs(e[6])!==n.parameterSet&&zs("suite-mismatch","record suite differs from the authenticated room suite");const a=e.subarray(8,40);void 0===r||Ws(a,r)||zs("binding-mismatch","record belongs to a different authenticated edge");const o=new DataView(e.buffer,e.byteOffset,e.byteLength),i=o.getBigUint64(40,!1),s=o.getBigUint64(48,!1),c=o.getBigUint64(56,!1);return s!==Ls&&c===s+1n||zs("invalid-record","record must advance exactly one PQ epoch"),{senderCounter:i,fromEpoch:s,toEpoch:c}},oc=(e,t,n)=>{const r=ac(e,1,t,n);return e.length!==ec(t)&&zs("invalid-record","OFFER length is not canonical for its suite"),{...r,bytes:Uint8Array.from(e),publicKey:e.slice(qs)}},ic=(e,t,n)=>{const r=ac(e,2,t,n);e.length!==tc(t)&&zs("invalid-record","ADVANCE length is not canonical for its suite");const a=ec(t),o=e.slice(qs,qs+a),i=oc(o,t,n);return i.fromEpoch===r.fromEpoch&&i.toEpoch===r.toEpoch||zs("fork","ADVANCE epoch does not exactly match its embedded OFFER"),{...r,bytes:Uint8Array.from(e),offer:i,ciphertext:e.slice(qs+a)}},sc=(e,t)=>{if(Ys(t),!(e instanceof Uint8Array))return zs("invalid-record","record must be a Uint8Array");if(e.length<qs)return zs("invalid-record","record is shorter than its canonical header");if(1===e[5]){const n=oc(e,t);return{type:"offer",parameterSet:t.parameterSet,binding:n.bytes.slice(8,40),senderCounter:n.senderCounter,fromEpoch:n.fromEpoch,toEpoch:n.toEpoch,publicKey:Uint8Array.from(n.publicKey)}}if(2===e[5]){const n=ic(e,t),r={type:"offer",parameterSet:t.parameterSet,binding:n.offer.bytes.slice(8,40),senderCounter:n.offer.senderCounter,fromEpoch:n.offer.fromEpoch,toEpoch:n.offer.toEpoch,publicKey:Uint8Array.from(n.offer.publicKey)};return{type:"advance",parameterSet:t.parameterSet,binding:n.bytes.slice(8,40),senderCounter:n.senderCounter,fromEpoch:n.fromEpoch,toEpoch:n.toEpoch,offerBytes:Uint8Array.from(n.offer.bytes),offer:r,ciphertext:Uint8Array.from(n.ciphertext)}}return zs("invalid-record","record type is unknown")},cc=(e,t,n,r)=>{js(e,"PQ root",Ns);const a=No(e,t,r),o=((...e)=>{const t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n})(Bs,n);try{return qo(a,o,Ns,r)}finally{a.fill(0)}},lc=(e,t)=>{const n=Uint8Array.from(e),r=Uint8Array.from(t);let a=!1;return{publicKey:n,secretKey:r,get destroyed(){return a},destroy(){a||(r.fill(0),a=!0)}}},dc=e=>{switch(e.kind){case"idle":return{kind:"idle"};case"outbound-offer":return{kind:e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared",offer:Uint8Array.from(e.offer.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey)};case"inbound-offer":return{kind:"inbound-offer",offer:Uint8Array.from(e.offer.bytes)};case"outbound-advance-prepared":return{kind:"outbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),nextRoot:Uint8Array.from(e.nextRoot)};case"outbound-advance-awaiting-ack":return{kind:"outbound-advance-awaiting-ack",advance:Uint8Array.from(e.advance.bytes)};case"inbound-advance-prepared":return{kind:"inbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey),nextRoot:Uint8Array.from(e.nextRoot)};case"inbound-advance-awaiting-ack-dispatch":return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Uint8Array.from(e.advance.bytes)}}},uc=(e,t)=>"bigint"!=typeof e?zs("invalid-record",`${t} must be a bigint`):(Hs(e,t),e),hc=(e,t,n)=>{const r=(e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return zs("invalid-record","snapshot.phase must be a plain record");const t=Object.getOwnPropertyDescriptor(e,"kind");return void 0!==t&&"value"in t&&t.enumerable&&"string"==typeof t.value?t.value:zs("invalid-record","snapshot.phase.kind must be an enumerable string data property")})(e);switch(r){case"idle":return Qs(e,"snapshot.phase",["kind"]),{kind:"idle"};case"outbound-offer-prepared":case"outbound-offer-dispatched":{const a=Qs(e,"snapshot.phase",["kind","offer","secretKey"]),o=oc(js(a.offer,"snapshot.phase.offer",ec(t)),t,n),i=js(a.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes);return{kind:"outbound-offer",dispatched:"outbound-offer-dispatched"===r,offer:o,keyPair:lc(o.publicKey,i)}}case"inbound-offer":{const r=Qs(e,"snapshot.phase",["kind","offer"]);return{kind:"inbound-offer",offer:oc(js(r.offer,"snapshot.phase.offer",ec(t)),t,n)}}case"outbound-advance-prepared":{const r=Qs(e,"snapshot.phase",["kind","advance","nextRoot"]),a=ic(js(r.advance,"snapshot.phase.advance",tc(t)),t,n);return{kind:"outbound-advance-prepared",offer:a.offer,advance:a,nextRoot:Uint8Array.from(js(r.nextRoot,"snapshot.phase.nextRoot",Ns))}}case"outbound-advance-awaiting-ack":{const r=Qs(e,"snapshot.phase",["kind","advance"]),a=ic(js(r.advance,"snapshot.phase.advance",tc(t)),t,n);return{kind:"outbound-advance-awaiting-ack",offer:a.offer,advance:a}}case"inbound-advance-prepared":{const r=Qs(e,"snapshot.phase",["kind","advance","secretKey","nextRoot"]),a=ic(js(r.advance,"snapshot.phase.advance",tc(t)),t,n),o=js(r.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes),i=Uint8Array.from(js(r.nextRoot,"snapshot.phase.nextRoot",Ns));return{kind:"inbound-advance-prepared",offer:a.offer,advance:a,keyPair:lc(a.offer.publicKey,o),nextRoot:i}}case"inbound-advance-awaiting-ack-dispatch":{const r=Qs(e,"snapshot.phase",["kind","advance"]);return{kind:"inbound-advance-awaiting-ack-dispatch",advance:ic(js(r.advance,"snapshot.phase.advance",tc(t)),t,n)}}default:return zs("invalid-record","snapshot phase is unknown")}},fc=(e,t)=>{e||zs("invalid-record",`snapshot ${t}`)},pc=(e,t)=>{Zs(t.suite,t.backend.suite),js(t.binding,"binding",Ts);const n=Qs(e,"snapshot",["formatVersion","parameterSet","binding","rootKey","epoch","localCounter","remoteCounter","nextOfferer","phase","lastInboundOffer","lastInboundAdvance"]);1!==n.formatVersion&&zs("invalid-record","snapshot format version is unsupported"),n.parameterSet!==t.suite.parameterSet&&zs("suite-mismatch","snapshot suite differs from the authenticated room suite");const r=js(n.binding,"snapshot.binding",Ts);Ws(r,t.binding)||zs("binding-mismatch","snapshot belongs to a different authenticated edge");const a=js(n.rootKey,"snapshot.rootKey",Ns),o=uc(n.epoch,"snapshot.epoch"),i=uc(n.localCounter,"snapshot.localCounter"),s=uc(n.remoteCounter,"snapshot.remoteCounter");if("local"!==n.nextOfferer&&"remote"!==n.nextOfferer)return zs("invalid-record","snapshot.nextOfferer must be local or remote");const c=Uint8Array.from(a);let l;try{l=hc(n.phase,t.suite,t.binding);const e=null===n.lastInboundOffer?null:oc(js(n.lastInboundOffer,"snapshot.lastInboundOffer",ec(t.suite)),t.suite,t.binding),r=null===n.lastInboundAdvance?null:ic(js(n.lastInboundAdvance,"snapshot.lastInboundAdvance",tc(t.suite)),t.suite,t.binding),a={rootKey:c,epoch:o,localCounter:i,remoteCounter:s,nextOfferer:n.nextOfferer,phase:l,lastInboundOffer:e,lastInboundAdvance:r};return(e=>{const{epoch:t,localCounter:n,remoteCounter:r,nextOfferer:a,phase:o,lastInboundOffer:i,lastInboundAdvance:s}=e;switch(null!==i&&(fc(i.toEpoch<=t,"last inbound OFFER is from a future epoch"),fc(i.senderCounter<r,"last inbound OFFER counter was not consumed")),null!==s&&(fc(s.toEpoch<=t,"last inbound ADVANCE is from a future epoch"),fc(s.senderCounter<r,"last inbound ADVANCE counter was not consumed")),o.kind){case"idle":return;case"outbound-offer":return void fc("local"===a&&o.offer.senderCounter===n&&o.offer.fromEpoch===t,"outbound OFFER does not match the current turn/counter/epoch");case"inbound-offer":return void fc("remote"===a&&o.offer.senderCounter===r&&o.offer.fromEpoch===t,"inbound OFFER does not match the current turn/counter/epoch");case"outbound-advance-prepared":return void fc("remote"===a&&o.advance.senderCounter===n&&o.offer.senderCounter===r&&o.advance.fromEpoch===t,"prepared outbound ADVANCE does not match current state");case"outbound-advance-awaiting-ack":return fc("local"===a&&o.advance.senderCounter+1n===n&&o.offer.senderCounter+1n===r&&o.advance.toEpoch===t,"outbound ADVANCE awaiting ACK does not match committed state"),void fc(null!==i&&Ws(i.bytes,o.offer.bytes),"outbound ADVANCE is missing its exact inbound OFFER replay record");case"inbound-advance-prepared":return void fc("local"===a&&o.advance.senderCounter===r&&o.offer.senderCounter===n&&o.advance.fromEpoch===t,"prepared inbound ADVANCE does not match current state");case"inbound-advance-awaiting-ack-dispatch":fc("remote"===a&&o.advance.senderCounter+1n===r&&o.advance.offer.senderCounter+1n===n&&o.advance.toEpoch===t,"inbound ADVANCE awaiting ACK dispatch does not match committed state"),fc(null!==s&&Ws(s.bytes,o.advance.bytes),"pending ACK is missing its exact inbound ADVANCE replay record")}})(a),a}catch(e){throw c.fill(0),void 0!==l&&("outbound-offer"===l.kind&&l.keyPair.destroy(),"outbound-advance-prepared"===l.kind&&l.nextRoot.fill(0),"inbound-advance-prepared"===l.kind&&(l.keyPair.destroy(),l.nextRoot.fill(0))),e}};class mc{#e;#n;#r;#a;#o;#i;#s;#c;#l;#d={kind:"idle"};#u=null;#h=null;#f=!1;#p=!1;constructor(e){Zs(e.suite,e.backend.suite),js(e.binding,"binding",Ts),js(e.rootKey,"PQ root",Ns);const t=e.nextOfferer;"local"!==t&&"remote"!==t&&zs("invalid-state","nextOfferer must be local or remote");const n=e.epoch??0n,r=e.localCounter??0n,a=e.remoteCounter??0n;Hs(n,"epoch"),Hs(r,"local counter"),Hs(a,"remote counter"),this.#e=e.module,this.#n=e.backend,this.#r=e.suite,this.#a=Uint8Array.from(e.binding),this.#o=Uint8Array.from(e.rootKey),this.#i=n,this.#s=r,this.#c=a,this.#l=e.nextOfferer}static restore(e,t){const n=pc(e,t);try{const e=new mc({...t,rootKey:n.rootKey,epoch:n.epoch,localCounter:n.localCounter,remoteCounter:n.remoteCounter,nextOfferer:n.nextOfferer});return e.#d=n.phase,e.#u=n.lastInboundOffer,e.#h=n.lastInboundAdvance,n.rootKey.fill(0),e}catch(e){throw n.rootKey.fill(0),"outbound-offer"===n.phase.kind&&n.phase.keyPair.destroy(),"outbound-advance-prepared"===n.phase.kind&&n.phase.nextRoot.fill(0),"inbound-advance-prepared"===n.phase.kind&&(n.phase.keyPair.destroy(),n.phase.nextRoot.fill(0)),e}}get suite(){return this.#r}get phase(){return this.#p?"destroyed":(e=>{switch(e.kind){case"idle":return"idle";case"outbound-offer":return e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared";case"inbound-offer":return"inbound-offer";case"outbound-advance-prepared":return"outbound-advance-prepared";case"outbound-advance-awaiting-ack":return"outbound-advance-awaiting-ack";case"inbound-advance-prepared":return"inbound-advance-prepared";case"inbound-advance-awaiting-ack-dispatch":return"inbound-advance-awaiting-ack-dispatch"}})(this.#d)}get epoch(){return this.#m(),this.#i}get localCounter(){return this.#m(),this.#s}get remoteCounter(){return this.#m(),this.#c}get nextOfferer(){return this.#m(),this.#l}get trafficBlocked(){return this.#p||"idle"!==this.#d.kind}copyRootKey(){return this.#m(),Uint8Array.from(this.#o)}snapshot(){return this.#y(),{formatVersion:1,parameterSet:this.#r.parameterSet,binding:Uint8Array.from(this.#a),rootKey:Uint8Array.from(this.#o),epoch:this.#i,localCounter:this.#s,remoteCounter:this.#c,nextOfferer:this.#l,phase:dc(this.#d),lastInboundOffer:null===this.#u?null:Uint8Array.from(this.#u.bytes),lastInboundAdvance:null===this.#h?null:Uint8Array.from(this.#h.bytes)}}clone(){const e=this.snapshot();try{return mc.restore(e,{module:this.#e,backend:this.#n,suite:this.#r,binding:this.#a})}finally{yc(e)}}adopt(e){this.#y(),e.#y(),e===this&&zs("invalid-state","cannot adopt a machine into itself"),this.#r.parameterSet===e.#r.parameterSet&&Ws(this.#a,e.#a)||zs("invalid-state","cannot adopt a machine from another suite or authenticated edge"),this.#g(this.#d),this.#o.fill(0),this.#o=e.#o,this.#i=e.#i,this.#s=e.#s,this.#c=e.#c,this.#l=e.#l,this.#d=e.#d,this.#u=e.#u,this.#h=e.#h,e.#o=new Uint8Array(Ns),e.#a.fill(0),e.#d={kind:"idle"},e.#u=null,e.#h=null,e.#p=!0}copyPendingOutboundRecord(){this.#y();const e=this.#d;return"outbound-offer"===e.kind?Uint8Array.from(e.offer.bytes):"outbound-advance-prepared"===e.kind||"outbound-advance-awaiting-ack"===e.kind?Uint8Array.from(e.advance.bytes):zs("invalid-state","there is no pending outbound record")}async prepareOffer(){let e;this.#w();try{"idle"!==this.#d.kind&&zs("invalid-state","cannot prepare an OFFER while another transition is pending"),"local"!==this.#l&&zs("wrong-turn","the remote peer owns the next OFFER turn"),this.#b(),e=await this.#n.generateKeyPair(),this.#m(),js(e.publicKey,"ML-KEM public key",this.#r.publicKeyBytes),js(e.secretKey,"ML-KEM secret key",this.#r.secretKeyBytes);const t=((e,t,n,r,a)=>{js(a,"ML-KEM public key",e.publicKeyBytes);const o=rc(1,e,t,n,r,r+1n,ec(e));return o.set(a,qs),o})(this.#r,this.#a,this.#s,this.#i,e.publicKey),n=oc(t,this.#r,this.#a);return this.#d={kind:"outbound-offer",dispatched:!1,offer:n,keyPair:e},e=void 0,Uint8Array.from(t)}finally{e?.destroy(),this.#v()}}markOfferDispatched(){this.#y();const e=this.#d;if("outbound-offer"!==e.kind)return zs("invalid-state","there is no outbound OFFER to dispatch");e.dispatched&&zs("invalid-state","outbound OFFER was already marked dispatched"),this.#d={...e,dispatched:!0}}abortUnsentOffer(){this.#y();const e=this.#d;if("outbound-offer"!==e.kind||e.dispatched)return zs("invalid-state","only an undispatched OFFER can be aborted");e.keyPair.destroy(),this.#d={kind:"idle"}}acceptAuthenticatedOffer(e){this.#y();const t=oc(e,this.#r,this.#a);this.#k(t),"idle"!==this.#d.kind&&zs("invalid-state","another PQ healing transition is pending"),"remote"!==this.#l&&zs("wrong-turn","the local peer owns the next OFFER turn"),this.#I(t.senderCounter),this.#S(t.fromEpoch),this.#b(),this.#d={kind:"inbound-offer",offer:t}}async prepareAdvance(){let e;this.#w();try{const t=this.#d;if("inbound-offer"!==t.kind)return zs("invalid-state","an authenticated inbound OFFER is required");$s(this.#s,"local counter"),e=await this.#n.encapsulate(t.offer.publicKey),this.#m(),js(e.ciphertext,"ML-KEM ciphertext",this.#r.ciphertextBytes),js(e.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const n=((e,t,n,r,a)=>{js(a,"ML-KEM ciphertext",e.ciphertextBytes);const o=rc(2,e,t,n,r.fromEpoch,r.toEpoch,tc(e));return o.set(r.bytes,qs),o.set(a,qs+r.bytes.length),o})(this.#r,this.#a,this.#s,t.offer,e.ciphertext),r=ic(n,this.#r,this.#a),a=cc(this.#o,e.sharedSecret,n,this.#e);return this.#d={kind:"outbound-advance-prepared",offer:t.offer,advance:r,nextRoot:a},Uint8Array.from(n)}finally{e?.destroy(),this.#v()}}commitPreparedAdvance(){this.#y();const e=this.#d;return"outbound-advance-prepared"!==e.kind?zs("invalid-state","there is no prepared outbound ADVANCE"):(this.#C(e.nextRoot),this.#i=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="local",this.#u=e.offer,this.#d={kind:"outbound-advance-awaiting-ack",offer:e.offer,advance:e.advance},Uint8Array.from(e.advance.bytes))}acceptAuthenticatedAdvanceAcknowledgement(e){this.#y();const t=Vs(e),n=this.#d;if("outbound-advance-awaiting-ack"!==n.kind)return zs("invalid-state","no outbound ADVANCE is awaiting acknowledgement");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||zs("invalid-record","advance acknowledgement does not bind the pending transition"),this.#d={kind:"idle"}}async acceptAuthenticatedAdvance(e){let t;this.#w();try{const n=ic(e,this.#r,this.#a);this.#A(n);const r=this.#d;if("outbound-offer"!==r.kind||!r.dispatched)return zs("invalid-state","a dispatched outbound OFFER is required before ADVANCE");this.#I(n.senderCounter),this.#S(n.fromEpoch),Ws(n.offer.bytes,r.offer.bytes)||zs("fork","ADVANCE answers a different OFFER"),t=await this.#n.decapsulate(n.ciphertext,r.keyPair.secretKey),this.#m(),js(t.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const a=cc(this.#o,t.sharedSecret,n.bytes,this.#e);this.#d={kind:"inbound-advance-prepared",offer:r.offer,advance:n,keyPair:r.keyPair,nextRoot:a}}finally{t?.destroy(),this.#v()}}commitAcceptedAdvance(){this.#y();const e=this.#d;return"inbound-advance-prepared"!==e.kind?zs("invalid-state","there is no accepted ADVANCE to commit"):(e.keyPair.destroy(),this.#C(e.nextRoot),this.#i=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="remote",this.#h=e.advance,this.#d={kind:"inbound-advance-awaiting-ack-dispatch",advance:e.advance},{epoch:this.#i,advanceCounter:e.advance.senderCounter})}markAdvanceAcknowledgementDispatched(e){this.#y();const t=Vs(e),n=this.#d;if("inbound-advance-awaiting-ack-dispatch"!==n.kind)return zs("invalid-state","no advance acknowledgement is pending dispatch");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||zs("invalid-record","advance acknowledgement does not bind the committed transition"),this.#d={kind:"idle"}}destroy(){this.#p||(this.#g(this.#d),this.#o.fill(0),this.#a.fill(0),this.#u=null,this.#h=null,this.#d={kind:"idle"},this.#p=!0)}#m(){this.#p&&zs("destroyed","state machine is destroyed")}#y(){this.#m(),this.#f&&zs("invalid-state","another asynchronous transition is in flight")}#w(){this.#y(),this.#f=!0}#v(){this.#f=!1}#b(){$s(this.#i,"epoch"),$s(this.#s,"local counter"),$s(this.#c,"remote counter")}#I(e){e<this.#c&&zs("replay","record sender counter was already consumed"),e>this.#c&&zs("counter-gap","record sender counter skips an expected transition")}#S(e){e<this.#i&&zs("replay","record PQ epoch was already consumed"),e>this.#i&&zs("epoch-gap","record skips the current PQ epoch")}#k(e){let t=this.#u;const n=this.#d;var r,a;("inbound-offer"!==n.kind&&"outbound-advance-prepared"!==n.kind&&"outbound-advance-awaiting-ack"!==n.kind||(t=n.offer),null!==t&&(a=t,(r=e).senderCounter===a.senderCounter&&r.fromEpoch===a.fromEpoch&&r.toEpoch===a.toEpoch))&&(Ws(e.bytes,t.bytes)&&zs("replay","OFFER is an exact replay"),zs("fork","different OFFER bytes reuse an authenticated slot"))}#A(e){let t=this.#h;const n=this.#d;var r,a;("inbound-advance-prepared"!==n.kind&&"inbound-advance-awaiting-ack-dispatch"!==n.kind||(t=n.advance),null!==t&&(a=t,(r=e).senderCounter===a.senderCounter&&r.fromEpoch===a.fromEpoch&&r.toEpoch===a.toEpoch))&&(Ws(e.bytes,t.bytes)&&zs("replay","ADVANCE is an exact replay"),zs("fork","different ADVANCE bytes reuse an authenticated slot"))}#C(e){js(e,"candidate PQ root",Ns),this.#o.fill(0),this.#o=e}#g(e){"outbound-offer"===e.kind&&e.keyPair.destroy(),"outbound-advance-prepared"===e.kind&&e.nextRoot.fill(0),"inbound-advance-prepared"===e.kind&&(e.keyPair.destroy(),e.nextRoot.fill(0))}}const yc=e=>{e.binding.fill(0),e.rootKey.fill(0),e.lastInboundOffer?.fill(0),e.lastInboundAdvance?.fill(0);const t=e.phase;switch(t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return t.offer.fill(0),void t.secretKey.fill(0);case"inbound-offer":return void t.offer.fill(0);case"outbound-advance-prepared":return t.advance.fill(0),void t.nextRoot.fill(0);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void t.advance.fill(0);case"inbound-advance-prepared":return t.advance.fill(0),t.secretKey.fill(0),void t.nextRoot.fill(0)}},gc=de-69-H,wc=(1n<<64n)-1n,bc=(new TextEncoder).encode("p2party/pq-control-frame/key/v1\0");class vc extends Error{code;constructor(e,t){super(`pqHealingFrame: ${t}`),this.name="PqControlFrameError",this.code=e}}const kc=(e,t)=>{throw new vc(e,t)},Ic=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},Sc=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&kc("invalid-frame",`${t} must be exactly ${String(n)} bytes`),e):kc("invalid-frame",`${t} must be a Uint8Array`),Cc=(e,t)=>"bigint"!=typeof e||e<0n||e>wc?kc("invalid-frame",`${t} must be an unsigned 64-bit bigint`):e,Ac=(e,t,n,r,a,o)=>{Sc(n,"PQ root",Ns),Sc(r,"binding",Ts);const i=(e=>{const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t})(Cc(o,"keyEpoch")),s=new Uint8Array(bc.length+1+1+r.length+i.length);s.set(bc,0),s[bc.length]=(e=>{const t=Ps(e.parameterSet);return e.standardName!==t.standardName||e.publicKeyBytes!==t.publicKeyBytes||e.secretKeyBytes!==t.secretKeyBytes||e.ciphertextBytes!==t.ciphertextBytes||e.sharedSecretBytes!==t.sharedSecretBytes||e.keyPairRandomBytes!==t.keyPairRandomBytes||e.encapsRandomBytes!==t.encapsRandomBytes?kc("invalid-frame","ML-KEM suite descriptor is not canonical"):768===e.parameterSet?1:512===e.parameterSet?2:1024===e.parameterSet?3:kc("invalid-frame","ML-KEM suite is unsupported")})(t),s[bc.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:kc("invalid-direction","control direction is unknown"))(a),s.set(r,bc.length+2),s.set(i,bc.length+2+r.length);const c=No(n,r,e);try{return qo(c,s,z,e)}finally{c.fill(0),i.fill(0)}},Ec=(e,t,n)=>{if(Sc(e,"control record"),64===e.length){const r=nc(e,t,n);return{counter:r.advanceCounter,keyEpoch:r.epoch}}const r=sc(e,t);return Ic(r.binding,n)?{counter:r.senderCounter,keyEpoch:r.fromEpoch}:kc("binding-mismatch","control record belongs to another authenticated edge")},Pc=e=>{const t=Sc(e.binding,"binding",Ts),n=Cc(e.keyEpoch,"keyEpoch"),r=Ec(e.record,e.suite,t);r.keyEpoch!==n&&kc("epoch-mismatch","control record is not authenticated under its required epoch"),e.record.length>gc-4&&kc("invalid-frame","control record does not fit the uniform cell");const a=(()=>{const e=new Uint8Array(j);return crypto.getRandomValues(e),e})(),o=new Uint8Array(69);o[0]=5,o.set(t,1);const i=new DataView(o.buffer,o.byteOffset,o.byteLength);i.setBigUint64(33,r.counter,!1),i.setBigUint64(49,n,!1),o.set(a,57);const s=new Uint8Array(gc);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e.record.length,!1),s.set(e.record,4);const c=Ac(e.module,e.suite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+H,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{return new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a),0!==e._encrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?kc("invalid-frame","control-frame AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{Da(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),Da(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),Da(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,c,a,s,o),n=new Uint8Array(de);return n.set(o,0),n.set(t,69),n}finally{c.fill(0),s.fill(0)}},xc=e=>{const t=Sc(e.frame,"control frame",de),n=Sc(e.binding,"binding",Ts),r=Cc(e.keyEpoch,"keyEpoch");5!==t[0]&&kc("invalid-frame","frame type is not PQ control"),Ic(t.subarray(1,33),n)||kc("binding-mismatch","control frame belongs to another edge");const a=t.subarray(0,69),o=new DataView(t.buffer,t.byteOffset,t.byteLength),i=o.getBigUint64(33,!1);0n!==o.getBigUint64(41,!1)&&kc("invalid-frame","control-frame reserved header must be zero"),o.getBigUint64(49,!1)!==r&&kc("epoch-mismatch","control-frame epoch is not the expected epoch");const s=t.subarray(57,69),c=t.subarray(69),l=Ac(e.module,e.suite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-H,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a);const u=new Uint8Array(e.wasmMemory.buffer,d,o);return u.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?kc("authentication-failed","control-frame authentication failed"):Uint8Array.from(u)}finally{Da(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),Da(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,l,s,c,a);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,!1);(0===t||t>gc-4)&&kc("invalid-padding","encrypted control-record length is invalid");const o=4+t;let u=0;for(let e=o;e<d.length;e+=1)u|=d[e];0!==u&&kc("invalid-padding","encrypted control padding must be all zero");const h=d.slice(4,o),f=Ec(h,e.suite,n);return f.keyEpoch!==r&&kc("epoch-mismatch","decrypted control record does not match its frame epoch"),f.counter!==i&&kc("record-mismatch","decrypted control counter does not match its public header"),h}finally{l.fill(0),d?.fill(0)}},Kc=new Uint8Array([80,50,69,68,71,69,52,0]),Rc=(1n<<64n)-1n,Mc=262144,_c=Math.min(ge,256),Uc=/^[0-9a-f]{64}:[0-9]+:[0-9]+$/,Dc=new TextEncoder,Tc=new TextDecoder("utf-8",{fatal:!0}),Nc=e=>{throw new Error(`pqHealingRuntime: ${e}`)},qc=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},Oc=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&Nc(`${t} must be exactly ${String(n)} bytes`),e):Nc(`${t} must be a Uint8Array`),Bc=(e,t)=>"number"!=typeof e||!Number.isSafeInteger(e)||e<0?Nc(`${t} must be a non-negative safe integer`):e,Lc=e=>1===e?"local":2===e?"remote":Nc("checkpoint has an invalid next-offerer turn");class Fc{#E=[];#P=0;bytes(e){const t=Uint8Array.from(e);this.#E.push(t),this.#P+=t.length,this.#P>Mc&&Nc("checkpoint exceeds the encrypted edge-state budget")}u8(e){(!Number.isInteger(e)||e<0||e>255)&&Nc("u8 value is out of range"),this.bytes(Uint8Array.of(e))}u16(e){(!Number.isInteger(e)||e<0||e>65535)&&Nc("u16 value is out of range");const t=new Uint8Array(2);new DataView(t.buffer).setUint16(0,e,!1),this.bytes(t),t.fill(0)}u32(e){(!Number.isInteger(e)||e<0||e>4294967295)&&Nc("u32 value is out of range");const t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e,!1),this.bytes(t),t.fill(0)}u64(e){((e,t)=>{("bigint"!=typeof e||e<0n||e>Rc)&&Nc(`${t} must be an unsigned 64-bit bigint`)})(e,"checkpoint counter");const t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e,!1),this.bytes(t),t.fill(0)}sized(e){null!==e?(0===e.length&&Nc("present checkpoint byte strings must not be empty"),this.u32(e.length),this.bytes(e)):this.u32(0)}finish(){const e=new Uint8Array(this.#P);let t=0;try{for(const n of this.#E)e.set(n,t),t+=n.length;return e}finally{for(const e of this.#E)e.fill(0);this.#E.length=0,this.#P=0}}}class zc{#x;#K=0;constructor(e){(0===e.length||e.length>Mc)&&Nc("checkpoint length is invalid"),this.#x=Uint8Array.from(e)}take(e){if(!Number.isSafeInteger(e)||e<0||this.#K+e>this.#x.length)return Nc("checkpoint is truncated");const t=this.#x.slice(this.#K,this.#K+e);return this.#K+=e,t}u8(){const e=this.take(1),t=e[0];return e.fill(0),t}u16(){const e=this.take(2),t=new DataView(e.buffer).getUint16(0,!1);return e.fill(0),t}u32(){const e=this.take(4),t=new DataView(e.buffer).getUint32(0,!1);return e.fill(0),t}u64(){const e=this.take(8),t=new DataView(e.buffer).getBigUint64(0,!1);return e.fill(0),t}sized(e){const t=this.u32();return 0===t?null:t>e?Nc("checkpoint field exceeds its budget"):this.take(t)}finish(){this.#K!==this.#x.length&&Nc("checkpoint contains trailing bytes")}destroy(){this.#x.fill(0),this.#K=this.#x.length}}const jc=(e,t,n)=>e.sized(t)??Nc(`${n} is missing`),Hc=(e,t)=>{const n=64+t.publicKeyBytes,r=64+n+t.ciphertextBytes;switch(e.u8()){case 0:return{kind:"idle"};case 1:return{kind:"outbound-offer-prepared",offer:jc(e,n,"prepared OFFER"),secretKey:jc(e,t.secretKeyBytes,"prepared OFFER secret key")};case 2:return{kind:"outbound-offer-dispatched",offer:jc(e,n,"dispatched OFFER"),secretKey:jc(e,t.secretKeyBytes,"dispatched OFFER secret key")};case 3:return{kind:"inbound-offer",offer:jc(e,n,"inbound OFFER")};case 4:return{kind:"outbound-advance-prepared",advance:jc(e,r,"prepared ADVANCE"),nextRoot:jc(e,32,"candidate PQ root")};case 5:return{kind:"outbound-advance-awaiting-ack",advance:jc(e,r,"outbound ADVANCE")};case 6:return{kind:"inbound-advance-prepared",advance:jc(e,r,"inbound ADVANCE"),secretKey:jc(e,t.secretKeyBytes,"inbound ADVANCE secret key"),nextRoot:jc(e,32,"candidate PQ root")};case 7:return{kind:"inbound-advance-awaiting-ack-dispatch",advance:jc(e,r,"acknowledged ADVANCE")};default:return Nc("checkpoint has an unknown PQ phase")}},$c=e=>{for(const t of e.values())t.fill(0);e.clear()};class Vc{#e;#R;#M;#r;#n;#a;#_;#U;#D;#T;#N=null;#q=null;#O=null;#B=null;#L=new Map;#F=0;#z;#p=!1;constructor(e){const t=ve(e.pqMode);ke(e.pqMode)!==e.rootSuite&&Nc("authenticated root suite and room PQ mode disagree"),Oc(e.binding,"edge binding",32),Oc(e.rootKey,"PQ root",32),this.#e=e.module,this.#R=e.pqMode,this.#M=e.rootSuite,this.#r=Ps(t),this.#n=Ds(e.module,this.#r),this.#a=Uint8Array.from(e.binding),this.#D=new mc({module:e.module,backend:this.#n,suite:this.#r,binding:this.#a,rootKey:e.rootKey,nextOfferer:e.nextOfferer}),this.#T=this.#D.copyRootKey(),this.#z=Bc(e.now??Date.now(),"initial healing time"),this.#_=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#U=e.amInitiator?"responder-to-initiator":"initiator-to-responder"}get pqMode(){return this.#R}get rootSuite(){return this.#M}get epoch(){return this.#j(),this.#D.epoch}get phase(){return this.#D.phase}get trafficBlocked(){return this.#p||this.#D.trafficBlocked}get nextOfferer(){return this.#D.nextOfferer}get activeReceiveKeys(){return this.#j(),this.#L}get messagesSinceHealing(){return this.#j(),this.#F}get lastHealedAt(){return this.#j(),this.#z}currentMessageContext(){return this.#j(),{rootKey:this.#T,binding:this.#a,rootSuite:this.#M,epoch:this.#D.epoch}}resolveMessageContext(e){return this.#j(),e===this.#D.epoch?this.currentMessageContext():null}noteApplicationMessage(){this.#j(),this.#F>=Number.MAX_SAFE_INTEGER&&Nc("application-message counter overflow"),this.#F+=1}healingDue(e=Date.now()){return this.#j(),Bc(e,"healing clock"),!this.#D.trafficBlocked&&"local"===this.#D.nextOfferer&&(this.#F>=64||e-this.#z>=864e5)}copyPendingFrame(){return this.#j(),this.#N?Uint8Array.from(this.#N.frame):null}get pendingRetryAt(){return this.#j(),this.#N?.nextRetryAt??null}get pendingAttempts(){return this.#j(),this.#N?.attempts??0}markPendingDispatched(e=Date.now()){this.#j();const t=this.#N;if(!t)return Nc("there is no PQ control outbox");Bc(e,"dispatch clock"),t.attempts>=8&&Nc("PQ control retry budget is exhausted"),this.#N={kind:t.kind,frame:t.frame,attempts:t.attempts+1,nextRetryAt:e+5e3}}async prepareHealingOffer(e=Date.now()){this.#j(),this.healingDue(e)||Nc("a local sparse-PQ healing exchange is not due");const t=await this.#D.prepareOffer(),n=this.#D.copyRootKey();try{const r=Pc({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#_,keyEpoch:this.#D.epoch,record:t});return this.#D.markOfferDispatched(),this.#N?.frame.fill(0),this.#N={kind:"offer",frame:Uint8Array.from(r),attempts:0,nextRetryAt:e},this.#H(),r}finally{n.fill(0),t.fill(0)}}async acceptControlFrame(e,t=Date.now()){if(this.#j(),Oc(e,"PQ control frame",de),Bc(t,"control clock"),this.#q&&"advance"===this.#N?.kind&&qc(e,this.#q))return{dispatch:Uint8Array.from(this.#N.frame),changed:!1};if(this.#O&&this.#B&&qc(e,this.#O))return{dispatch:Uint8Array.from(this.#B),changed:!1};const n=this.#D.copyRootKey();let r=null;try{if(r=xc({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#U,keyEpoch:this.#D.epoch,frame:e}),64===r.length){const e=this.#N;if("advance"!==e?.kind)return Nc("unexpected PQ ADVANCE acknowledgement");const n=nc(r,this.#r,this.#a);return this.#D.acceptAuthenticatedAdvanceAcknowledgement(n),e.frame.fill(0),this.#N=null,this.#H(),this.#F=0,this.#z=t,this.#$(),{dispatch:null,changed:!0}}if("offer"===sc(r,this.#r).type){this.#D.acceptAuthenticatedOffer(r);const a=await this.#D.prepareAdvance();let o;try{o=Pc({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#_,keyEpoch:this.#D.epoch,record:a}),this.#D.commitPreparedAdvance()}finally{a.fill(0)}return this.#N?.frame.fill(0),this.#N={kind:"advance",frame:Uint8Array.from(o),attempts:0,nextRetryAt:t},this.#q?.fill(0),this.#q=Uint8Array.from(e),this.#O?.fill(0),this.#O=null,this.#B?.fill(0),this.#B=null,this.#$(),{dispatch:o,changed:!0}}const a=this.#N;if("offer"!==a?.kind)return Nc("unexpected PQ ADVANCE without a persisted OFFER");await this.#D.acceptAuthenticatedAdvance(r);const o=this.#D.commitAcceptedAdvance(),i=((e,t,n)=>{Ys(t),js(n,"binding",Ts);const r=Vs(e),a=new Uint8Array(64);a.set(Os,0),a[4]=1,a[5]=3,a[6]=Xs(t.parameterSet),a[7]=0,a.set(n,8);const o=new DataView(a.buffer,a.byteOffset,a.byteLength);return o.setBigUint64(40,r.advanceCounter,!1),o.setBigUint64(48,r.epoch,!1),a})(o,this.#r,this.#a),s=this.#D.copyRootKey();try{const n=Pc({module:this.#e,suite:this.#r,rootKey:s,binding:this.#a,direction:this.#_,keyEpoch:o.epoch,record:i});return this.#D.markAdvanceAcknowledgementDispatched(o),a.frame.fill(0),this.#N=null,this.#O?.fill(0),this.#O=Uint8Array.from(e),this.#B?.fill(0),this.#B=Uint8Array.from(n),this.#q?.fill(0),this.#q=null,this.#F=0,this.#z=t,this.#$(),{dispatch:n,changed:!0}}finally{s.fill(0),i.fill(0)}}finally{n.fill(0),r?.fill(0)}}clone(){this.#j();const e=this.#D.copyRootKey();let t=null;try{return t=new Vc({module:this.#e,pqMode:this.#R,rootSuite:this.#M,binding:this.#a,rootKey:e,nextOfferer:this.#D.nextOfferer,amInitiator:"initiator-to-responder"===this.#_,now:this.#z}),t.#D.destroy(),t.#D=this.#D.clone(),t.#T.fill(0),t.#T=Uint8Array.from(this.#T),t.#N=null===(n=this.#N)?null:{kind:n.kind,frame:Uint8Array.from(n.frame),attempts:n.attempts,nextRetryAt:n.nextRetryAt},t.#q=null===this.#q?null:Uint8Array.from(this.#q),t.#O=null===this.#O?null:Uint8Array.from(this.#O),t.#B=null===this.#B?null:Uint8Array.from(this.#B),t.#L=(e=>{const t=new Map;for(const[n,r]of e)t.set(n,Uint8Array.from(r));return t})(this.#L),t.#F=this.#F,t.#z=this.#z,t}catch(e){throw t?.destroy(),e}finally{e.fill(0)}var n}adopt(e){this.#j(),e.#j(),e===this&&Nc("cannot adopt a PQ runtime into itself"),e.#e===this.#e&&e.#R===this.#R&&e.#M===this.#M&&e.#_===this.#_&&qc(e.#a,this.#a)||Nc("cannot adopt a PQ runtime from another authenticated edge"),this.#D.destroy(),this.#T.fill(0),this.#N?.frame.fill(0),this.#q?.fill(0),this.#O?.fill(0),this.#B?.fill(0),$c(this.#L),this.#D=e.#D,this.#T=e.#T,this.#N=e.#N,this.#q=e.#q,this.#O=e.#O,this.#B=e.#B,this.#L=e.#L,this.#F=e.#F,this.#z=e.#z,e.#T=new Uint8Array(32),e.#N=null,e.#q=null,e.#O=null,e.#B=null,e.#L=new Map,e.#a.fill(0),e.#p=!0}serialize(e=this.#L){this.#j();const t=this.#D.snapshot(),n=new Fc;try{return n.bytes(Kc),n.u8(1),n.u8(512===(a=this.#r.parameterSet)?1:768===a?2:1024===a?3:Nc("unsupported ML-KEM suite")),n.u8("initiator-to-responder"===this.#_?1:2),n.u8(0),n.u64(BigInt(this.#z)),n.u64(BigInt(this.#F)),n.bytes(t.binding),n.bytes(t.rootKey),n.u64(t.epoch),n.u64(t.localCounter),n.u64(t.remoteCounter),n.u8("local"===(r=t.nextOfferer)?1:"remote"===r?2:Nc("invalid next-offerer turn")),((e,t)=>{switch(e.u8((e=>{switch(e.kind){case"idle":return 0;case"outbound-offer-prepared":return 1;case"outbound-offer-dispatched":return 2;case"inbound-offer":return 3;case"outbound-advance-prepared":return 4;case"outbound-advance-awaiting-ack":return 5;case"inbound-advance-prepared":return 6;case"inbound-advance-awaiting-ack-dispatch":return 7}})(t)),t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return e.sized(t.offer),void e.sized(t.secretKey);case"inbound-offer":return void e.sized(t.offer);case"outbound-advance-prepared":return e.sized(t.advance),void e.sized(t.nextRoot);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void e.sized(t.advance);case"inbound-advance-prepared":e.sized(t.advance),e.sized(t.secretKey),e.sized(t.nextRoot)}})(n,t.phase),n.sized(t.lastInboundOffer),n.sized(t.lastInboundAdvance),((e,t)=>{null!==t?(e.u8("offer"===t.kind?1:2),e.u8(t.attempts),e.u64(BigInt(t.nextRetryAt)),e.sized(t.frame)):e.u8(0)})(n,this.#N),n.sized(this.#q),n.sized(this.#O),n.sized(this.#B),((e,t)=>{t.size>_c&&Nc("too many active receive message keys");const n=[...t.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0);e.u16(n.length);for(const[t,r]of n){Uc.test(t)||Nc("active receive cache key is non-canonical");const n=Dc.encode(t);(0===n.length||n.length>160)&&Nc("active receive cache key length is invalid"),Oc(r,"active receive message key",32),e.u16(n.length),e.bytes(n),e.bytes(r)}})(n,e),n.finish()}finally{yc(t)}var r,a}static readCheckpointBinding(e){Oc(e,"checkpoint");const t=Kc.length+1+1+1+1+8+8;return e.length<t+32?Nc("checkpoint is too short to contain a binding"):e.slice(t,t+32)}static restore(e,t){Oc(e,"encrypted edge checkpoint plaintext"),Oc(t.binding,"expected edge binding",32);const n=new zc(e);let r=null,a=null,o=null,i=null,s=null,c=null,l=null,d=null;try{const e=n.take(Kc.length),h=qc(e,Kc);e.fill(0),h||Nc("checkpoint magic is invalid"),1!==n.u8()&&Nc("checkpoint version is unsupported");const f=1===(u=n.u8())?512:2===u?768:3===u?1024:Nc("checkpoint has an unknown ML-KEM suite");f!==ve(t.pqMode)&&Nc("checkpoint suite disagrees with the authenticated room policy"),ke(t.pqMode)!==t.rootSuite&&Nc("authenticated root suite and room PQ mode disagree");const p=n.u8();p!==(t.amInitiator?1:2)&&Nc("checkpoint belongs to the opposite edge direction"),0!==n.u8()&&Nc("checkpoint reserved byte is non-zero");const m=n.u64(),y=n.u64();(m>BigInt(Number.MAX_SAFE_INTEGER)||y>BigInt(Number.MAX_SAFE_INTEGER))&&Nc("checkpoint counters exceed the safe-integer range");const g=n.take(32);qc(g,t.binding)||Nc("checkpoint belongs to another authenticated edge");const w=n.take(32),b=Ps(f);r={formatVersion:1,parameterSet:f,binding:g,rootKey:w,epoch:n.u64(),localCounter:n.u64(),remoteCounter:n.u64(),nextOfferer:Lc(n.u8()),phase:Hc(n,b),lastInboundOffer:n.sized(8192),lastInboundAdvance:n.sized(8192)},s=(e=>{const t=e.u8();if(0===t)return null;if(1!==t&&2!==t)return Nc("checkpoint outbox kind is invalid");const n=e.u8();n>8&&Nc("checkpoint outbox attempts exceed the retry budget");const r=e.u64();r>BigInt(Number.MAX_SAFE_INTEGER)&&Nc("checkpoint retry deadline exceeds the safe-integer range");const a=jc(e,de,"outbox frame");return Oc(a,"outbox frame",de),{kind:1===t?"offer":"advance",attempts:n,nextRetryAt:Number(r),frame:a}})(n),c=n.sized(de),l=n.sized(de),d=n.sized(de);for(const e of[c,l,d])e&&Oc(e,"cached control frame",de);i=(e=>{const t=e.u16();t>_c&&Nc("checkpoint has too many active receive message keys");const n=new Map;try{for(let r=0;r<t;r+=1){const t=e.u16();(0===t||t>160)&&Nc("checkpoint active receive cache key length is invalid");const r=e.take(t);let a;try{a=Tc.decode(r)}finally{r.fill(0)}0!==a.length&&Uc.test(a)&&!n.has(a)||Nc("checkpoint active receive cache key is non-canonical"),n.set(a,e.take(32))}return n}catch(e){for(const e of n.values())e.fill(0);throw n.clear(),e}})(n),n.finish();const v=Ds(t.module,b);a=mc.restore(r,{module:t.module,backend:v,suite:b,binding:t.binding});const k=a.copyRootKey();try{o=new Vc({module:t.module,pqMode:t.pqMode,rootSuite:t.rootSuite,binding:t.binding,rootKey:k,nextOfferer:a.nextOfferer,amInitiator:t.amInitiator,now:Number(m)})}finally{k.fill(0)}return o.#D.destroy(),o.#D=a,a=null,o.#T.fill(0),o.#T=o.#D.copyRootKey(),o.#N=s,s=null,o.#q=c,c=null,o.#O=l,l=null,o.#B=d,d=null,o.#L=i,i=null,o.#F=Number(y),o.#V(),o}catch(e){throw o?.destroy(),e}finally{n.destroy(),r&&yc(r),a?.destroy(),s?.frame.fill(0),c?.fill(0),l?.fill(0),d?.fill(0),i&&$c(i)}var u}destroy(){this.#p||(this.#D.destroy(),this.#a.fill(0),this.#T.fill(0),this.#N?.frame.fill(0),this.#q?.fill(0),this.#O?.fill(0),this.#B?.fill(0),$c(this.#L),this.#N=null,this.#q=null,this.#O=null,this.#B=null,this.#p=!0)}#$(){const e=this.#D.copyRootKey();this.#T.fill(0),this.#T=e}#H(){this.#q?.fill(0),this.#O?.fill(0),this.#B?.fill(0),this.#q=null,this.#O=null,this.#B=null}#V(){const e=this.#D.phase;("outbound-offer-dispatched"===e&&"offer"!==this.#N?.kind||"outbound-advance-awaiting-ack"===e&&"advance"!==this.#N?.kind||"offer"===this.#N?.kind&&"outbound-offer-dispatched"!==e||"advance"===this.#N?.kind&&"outbound-advance-awaiting-ack"!==e)&&Nc("checkpoint PQ phase and sealed outbox disagree"),null!==this.#q&&"advance"!==this.#N?.kind&&Nc("checkpoint cached OFFER has no matching ADVANCE outbox"),null===this.#O!=(null===this.#B)&&Nc("checkpoint ADVANCE replay and ACK cache must be paired"),null!==this.#q&&null!==this.#O&&Nc("checkpoint contains mutually exclusive replay caches")}#j(){this.#p&&Nc("state is destroyed")}}const Qc=new TextEncoder,Wc=Qc.encode("CPaceRistretto255"),Xc=Qc.encode("CPaceRistretto255_ISK"),Gc=new Uint8Array(0),Jc=(e,t,n)=>{if(t.length!==n)throw new Error(`cpace: ${e} must be ${n} bytes`)},Yc=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("cpace: invalid transcript field length");const t=[];let n=e;do{let e=n%128;n=Math.floor(n/128),0!==n&&(e|=128),t.push(e)}while(0!==n);return Uint8Array.from(t)},Zc=(e,t,n,r=!1)=>{if(0===n.length)return;const a=e._malloc(n.length),o=new Uint8Array(e.wasmMemory.buffer,a,n.length);try{if(o.set(n),0!==e._sha512_update(t,a,n.length))throw new Error("sha512_update failed")}finally{r?Da(e,o):e._free(a)}},el=(e,t,n)=>{Zc(e,t,Yc(n.data.length)),Zc(e,t,n.data,n.secret)},tl=(e,t,n,r)=>{const a=Math.max(0,127-(Yc(Wc.length).length+Wc.length)-(Yc(e.length).length+e.length)),o=((e,t)=>{const n=e._malloc(q),r=e._malloc(N),a=new Uint8Array(e.wasmMemory.buffer,n,q),o=new Uint8Array(e.wasmMemory.buffer,r,N);try{if(a.fill(0),o.fill(0),0!==e._sha512_init(n))throw new Error("sha512_init failed");for(const r of t)el(e,n,r);if(0!==e._sha512_final(n,r))throw new Error("sha512_final failed");return Uint8Array.from(o)}finally{Da(e,a),Da(e,o)}})(r,[{data:Wc},{data:e,secret:!0},{data:new Uint8Array(a)},{data:n},{data:t}]),i=r._malloc(Q),s=r._malloc(V),c=new Uint8Array(r.wasmMemory.buffer,i,Q),l=new Uint8Array(r.wasmMemory.buffer,s,V);try{return c.set(o),l.fill(0),r._cpace_ristretto255_from_hash(s,i),Uint8Array.from(l)}finally{o.fill(0),Da(r,c),r._free(s)}},nl=(new TextEncoder).encode("p2party-interactive-3dh-v2"),rl=new Uint8Array(64),al=e=>{const t=new Uint8Array(ue.length+e.length);return t.set(ue,0),t.set(e,ue.length),t},ol=async(e,t,n)=>Na(al(e),t,n),il=async(e,t,n,r)=>qa(al(e),t,n,r),sl=e=>{const t=(e=>{if("hybrid-mlkem768"===e)return se;if("hybrid-mlkem512"===e)return new Uint8Array([2]);if("hybrid-mlkem1024"===e)return new Uint8Array([3]);throw new Error("handshake: unsupported room PQ mode")})(e.pqMode??"hybrid-mlkem768"),n=[e.channelId,e.ikInitiator,e.ikResponder,e.fpInitiator,e.fpResponder,t];let r=0;for(const e of n)r+=e.length;const a=new Uint8Array(r);let o=0;for(const e of n)a.set(e,o),o+=e.length;return a},cl=(new TextEncoder).encode("p2party-v4-hs-kc-transcript-v4"),ll=(new TextEncoder).encode("p2party-v4-hs-kc-responder-v4"),dl=(new TextEncoder).encode("p2party-v4-hs-kc-initiator-ratchet-dh-v4"),ul=(new TextEncoder).encode("p2party-v4-hs-kc-responder-finish-v4"),hl=new Uint8Array(64),fl=(new TextEncoder).encode("p2party-v4-pq-healing-extract-v1"),pl=(new TextEncoder).encode("p2party-v4-pq-healing-root-v1"),ml=(new TextEncoder).encode("p2party-v4-pq-healing-binding-v1\0"),yl=64,gl=129,wl=e=>{const t=Ps(ve(e)),n=193+t.publicKeyBytes;return{suite:t,publicKeyOffset:193,ciphertextOffset:n,length:n+t.ciphertextBytes}},bl=(e,t,n)=>{const r=n._malloc(e.length),a=n._malloc(t.length),o=n._malloc(yl);try{new Uint8Array(n.wasmMemory.buffer,r,e.length).set(e),new Uint8Array(n.wasmMemory.buffer,a,t.length).set(t);if(0!==n._hkdf_sha512_extract(o,r,e.length,a,t.length))throw new Error("handshake hmac_sha512 failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,o,yl))}finally{Da(n,new Uint8Array(n.wasmMemory.buffer,r,e.length)),n._free(a),n._free(o)}},vl=e=>{let t=0;for(const n of e)t|=n;return 0===t},kl=(e,t)=>{const n=new Uint8Array(97);return n[0]=2,n.set(e,1),n.set(t,33),n},Il=async(e,t,n)=>{const{mode:r,pqMode:a="hybrid-mlkem768",pin:o,channelInput:i,amInitiator:s,idSelfSec:c,selfIdentityX25519Pub:l,selfIdentityCrossSignature:d,peerIdentityEd25519Pub:u}=t,h=wl(a),f=Ds(n,h.suite),p=ke(a),m=crypto.getRandomValues(new Uint8Array(32)),y=Uo(n);let g=new Uint8Array(32),w=null;const b=new Uint8Array(h.suite.publicKeyBytes),v=new Uint8Array(h.suite.ciphertextBytes);let k,I,S,C,A,E,P,x,K=null,R=null,M=null;const _=e=>{if("pin"!==r)return null;if(!o)throw new Error("PIN mode requires a PIN");const t=tl(o,e,i,n),a=((e,t)=>{Jc("generator",e,V);const n=t._malloc(W),r=t._malloc(V),a=t._malloc(V),o=new Uint8Array(t.wasmMemory.buffer,n,W),i=new Uint8Array(t.wasmMemory.buffer,r,V),s=new Uint8Array(t.wasmMemory.buffer,a,V);try{if(o.fill(0),s.fill(0),i.set(e),t._cpace_ristretto255_scalar_random(n),0!==t._cpace_ristretto255_scalarmult(a,n,r))throw new Error("cpace: public share is the identity");return{y:Uint8Array.from(o),Y:Uint8Array.from(s)}}finally{Da(t,o),t._free(r),t._free(a)}})(t,n);return t.fill(0),a},U=()=>((e,t,n,r,a,o,i,s)=>{const c=new Uint8Array(e.length);return c[0]=1,c.set(t,1),c.set(n,33),c.set(r,65),c.set(a,97),c.set(o,gl),c.set(i,e.publicKeyOffset),c.set(s,e.ciphertextOffset),c})(h,m,y.publicKey,g,l,d,b,v);try{let t;if(s){K=await f.generateKeyPair(),b.set(K.publicKey);const n=_(m);n&&(w=n.y,g=n.Y),await e.send(U()),t=await e.recv()}else t=await e.recv();if(t.length!==h.length||1!==t[0])throw new Error("Malformed handshake HELLO");const a=t.subarray(1,33),o=t.subarray(33,65),D=t.subarray(65,97),T=t.subarray(97,129),O=t.subarray(gl,193),B=t.subarray(h.publicKeyOffset,h.publicKeyOffset+h.suite.publicKeyBytes),L=t.subarray(h.ciphertextOffset,h.ciphertextOffset+h.suite.ciphertextBytes);if(s){if(!vl(B))throw new Error("Malformed handshake HELLO: responder ML-KEM public-key field must be zero");if(vl(L))throw new Error("Malformed handshake HELLO: responder ML-KEM ciphertext is required")}else{if(vl(B))throw new Error("Malformed handshake HELLO: initiator ML-KEM public key is required");if(!vl(L))throw new Error("Malformed handshake HELLO: initiator ML-KEM ciphertext field must be zero")}if(!await il(T,O,u,n))throw new Error("Handshake peer X25519 identity cross-signature invalid");if(s){if(!K)throw new Error("Handshake ML-KEM initiator keypair is unavailable");R=await f.decapsulate(L,K.secretKey),K.destroy()}else{const t=await f.encapsulate(B);R=t,v.set(t.ciphertext);const n=_(a);n&&(w=n.y,g=n.Y),await e.send(U())}k=((e,t,n,r,a,o)=>{let i,s;const c=To(n,r,o);a?(i=To(e,r,o),s=To(n,t,o)):(i=To(n,t,o),s=To(e,r,o));const l=new Uint8Array(96);l.set(i,0),l.set(s,32),l.set(c,64);const d=No(rl,l,o),u=qo(d,nl,32,o);return l.fill(0),i.fill(0),s.fill(0),c.fill(0),d.fill(0),u})(c,T,y.secretKey,o,s,n);const F=s?m:a,z=s?a:m,j=s?y.publicKey:o,H=s?o:y.publicKey,$=s?g:D,Q=s?D:g,X=s?l:T,G=s?d:O,J=s?T:l,Y=s?O:d,Z=s?b:B,ee=s?v:L,te=s?B:b,ne=s?L:v;if("pin"===r){if(!w)throw new Error("Handshake CPace scalar is unavailable");I=((e,t)=>{const{y:n,peerShare:r,sid:a,initiatorShare:o,responderShare:i,initiatorAssociatedData:s=Gc,responderAssociatedData:c=Gc}=e;Jc("private scalar",n,W),Jc("peer share",r,V),Jc("initiator share",o,V),Jc("responder share",i,V);const l=t._malloc(W),d=t._malloc(V),u=t._malloc(V),h=t._malloc(q),f=t._malloc(N),p=new Uint8Array(t.wasmMemory.buffer,l,W),m=new Uint8Array(t.wasmMemory.buffer,d,V),y=new Uint8Array(t.wasmMemory.buffer,u,V),g=new Uint8Array(t.wasmMemory.buffer,h,q),w=new Uint8Array(t.wasmMemory.buffer,f,N);try{if(p.set(n),m.set(r),y.fill(0),g.fill(0),w.fill(0),0!==t._cpace_ristretto255_scalarmult(u,l,d))throw new Error("cpace: peer share is invalid or the identity");if(0!==t._sha512_init(h))throw new Error("sha512_init failed");if(el(t,h,{data:Xc}),el(t,h,{data:a}),Zc(t,h,Yc(V)),0!==t._sha512_update(h,u,V))throw new Error("sha512_update failed");if(el(t,h,{data:o}),el(t,h,{data:s}),el(t,h,{data:i}),el(t,h,{data:c}),0!==t._sha512_final(h,f))throw new Error("sha512_final failed");return Uint8Array.from(w)}finally{Da(t,p),t._free(d),Da(t,y),Da(t,g),Da(t,w)}})({y:w,peerShare:D,sid:F,initiatorShare:$,responderShare:Q},n)}const re=((e,t)=>(new TextEncoder).encode("pin"===e?`p2party-v4-hybrid-root-cpace21-3dh-ml-kem-${String(t)}-v4`:`p2party-v4-hybrid-root-3dh-ml-kem-${String(t)}-v4`))(r,h.suite.parameterSet);S=await ia("pin"===r?[I,k,R.sharedSecret]:[k,R.sharedSecret]),C=No(hl,S,n);const ae=await ia([re,i,X,G,J,Y,Z,ne]);A=qo(C,ae,32,n);const oe=await ia([ml,i,F,z,j,H,X,G,J,Y,Z,ne]);try{x=new Uint8Array(await crypto.subtle.digest("SHA-256",oe.slice().buffer))}finally{oe.fill(0)}E=No(fl,A,n);const ie=await ia([pl,x]);try{P=qo(E,ie,32,n)}finally{ie.fill(0),E.fill(0),E=void 0}k.fill(0),I?.fill(0),S.fill(0),C.fill(0),R.destroy();const se=(e,t,n,r=[])=>ia([cl,e,F,z,j,H,$,Q,X,G,J,Y,Z,ee,te,ne,t,...n?[n]:[],...r,i]);if(s){const t=await e.recv();if(97!==t.length||2!==t[0])throw new Error("Malformed handshake CONFIRM");const r=Uint8Array.from(t.subarray(1,33)),a=t.subarray(33,97);M=$o(A,!0,r,n,p);const o=M.dhSelfPub,i=await se(dl,r,o,[a]),s=bl(A,i,n);try{await e.send(kl(o,s));const t=await se(ll,r),i=bl(A,t,n),c=await sa(a,i);if(i.fill(0),!c)throw new Error("Handshake key-confirmation failed");const l=await e.recv();if(65!==l.length||3!==l[0])throw new Error("Malformed handshake FINISH");const d=l.subarray(1,65),u=await se(ul,r,o,[a,s]),h=bl(A,u,n),f=await sa(d,h);if(h.fill(0),!f)throw new Error("Handshake final confirmation failed")}finally{s.fill(0)}}else{M=$o(A,!1,null,n,p);const t=M.dhSelfPub,r=await se(ll,t),a=bl(A,r,n);try{await e.send(kl(t,a));const r=await e.recv();if(97!==r.length||2!==r[0])throw new Error("Malformed handshake CONFIRM");const o=Uint8Array.from(r.subarray(1,33)),i=r.subarray(33,97),s=await se(dl,t,o,[a]),c=bl(A,s,n),l=await sa(i,c);if(c.fill(0),!l)throw new Error("Handshake key-confirmation failed");((e,t,n)=>{if(t.length!==ce)throw new Error("ratchet: invalid initiator DH public key");if(e.sendingChainKey||e.receivingChainKey||e.dhRemotePub||0!==e.Ns||0!==e.Nr||0!==e.PN||0!==e.skipped.size)throw new Error("ratchet: responder bootstrap requires pristine state");Wo(e,{dhPub:t},n)})(M,o,n);const d=await se(ul,t,o,[a,i]),u=bl(A,d,n);try{await e.send((e=>{const t=new Uint8Array(65);return t[0]=3,t.set(e,1),t})(u))}finally{u.fill(0)}}finally{a.fill(0)}}if(!M)throw new Error("Handshake ratchet initialization failed");if(!P||!x)throw new Error("Handshake PQ-healing bootstrap failed");const le=M;M=null;const de={rootKey:P,binding:x,nextOfferer:s?"local":"remote"};return P=void 0,x=void 0,{state:le,secret:A,pqHealing:de}}catch(e){throw A?.fill(0),P?.fill(0),x?.fill(0),e}finally{y.secretKey.fill(0),w?.fill(0),k?.fill(0),I?.fill(0),S?.fill(0),C?.fill(0),E?.fill(0),P?.fill(0),x?.fill(0),R?.destroy(),K?.destroy(),M&&ti(M)}},Sl=/a=fingerprint:sha-256\s+([0-9A-Fa-f:]+)/,Cl=e=>{const t=Sl.exec(e);if(!t)throw new Error("No sha-256 DTLS fingerprint found in SDP");const n=t[1].split(":").map(e=>parseInt(e,16));if(32!==n.length||n.some(e=>Number.isNaN(e)))throw new Error("Malformed sha-256 DTLS fingerprint in SDP");return Uint8Array.from(n)},Al=e=>e.replace(/:/g,"").toLowerCase(),El=new Map,Pl=(e,t)=>`${e}\0${t}`,xl=(e,t,n=new Error("Handshake channel closed"),r)=>{const a=Pl(e,t),o=El.get(a);if(!o||r&&o.lease!==r)return!1;El.delete(a);for(const e of o.waiters)e.reject(n);return!0},Kl=(e,t,n,r)=>{const a=El.get(Pl(e,t));if(!a||a.lease!==r)return!1;if(null===a.nextStep||!((e,t,n="hybrid-mlkem768")=>1===t?e.length===wl(n).length&&1===e[0]:2===t?97===e.length&&2===e[0]:65===e.length&&3===e[0])(n,a.nextStep,a.pqMode))return xl(e,t,new Error("Malformed, surplus, or out-of-order handshake frame"),r),!1;a.nextStep=1===a.nextStep?2:2===a.nextStep&&a.expectFinish?3:null;const o=a.waiters.shift();return o?o.resolve(n):a.queue.push(n),!0},Rl=async(e,t,n,r,a,o,i,s,c)=>{let l=null,d=null,u=null,h=null;try{await(async e=>{const t=e.localDescription?.sdp??"",n=e.remoteDescription?.sdp??"",r=Al(ca(Cl(t))),a=Al(ca(Cl(n))),o=await e.getStats();let i,s,c=!1;if(o.forEach(e=>{"transport"===e.type&&(i=e.localCertificateId??i,s=e.remoteCertificateId??s),"certificate"===e.type&&(c=!0)}),!c&&void 0===i)return void console.warn("p2party: this browser does not report WebRTC certificate statistics, so the post-connect DTLS certificate check cannot run. The SDP fingerprints remain bound into the authenticated handshake transcript.");const l=e=>{if(!e)return null;let t=null;return o.forEach((n,r)=>{"certificate"!==n.type||r!==e&&n.id!==e||!n.fingerprint||(t=Al(n.fingerprint))}),t},d=l(i),u=l(s);if(null===d||d!==r)throw new Error("DTLS fingerprint mismatch: local certificate not found or does not match local SDP fingerprint");if(null===u||u!==a)throw new Error("DTLS fingerprint mismatch: remote certificate not found or does not match remote SDP fingerprint (possible MITM)")})(e);const{publicKey:f}=Xu.getState().keyPair,p=Fa(f,e.withPeerPublicKey),m=await lo();if(!m)throw new Error("X25519 identity not provisioned");l=new Uint8Array(m.secret);const y=new Uint8Array(m.pub),g=new Uint8Array(m.crossSig),w=la(e.withPeerPublicKey),b=((e,t,n)=>{const r=Pl(e,t),a=El.get(r);if(!a||a.lease!==n)throw new Error(`No owned handshake channel registered for ${t}`);const o=()=>{if(El.get(r)!==a||a.lease!==n)throw new Error("Handshake channel lease is stale")};return{send:e=>{o();const t=new Uint8Array(1+e.length);t[0]=1,t.set(e,1),a.channel.send(t.buffer)},recv:()=>{try{o()}catch(e){return Promise.reject(e)}return a.queue.length>0?Promise.resolve(a.queue.shift()):new Promise((e,t)=>{const n={resolve:t=>{clearTimeout(r),e(t)},reject:e=>{clearTimeout(r),t(e)}},r=setTimeout(()=>{const e=a.waiters.indexOf(n);e>-1&&a.waiters.splice(e,1),t(new Error("Handshake step timed out"))},3e4);a.waiters.push(n)})}}})(t,e.withPeerId,s),v=await Il(b,{mode:n,pqMode:r,pin:a,channelInput:o,amInitiator:p,idSelfSec:l,selfIdentityX25519Pub:y,selfIdentityCrossSignature:g,peerIdentityEd25519Pub:w},i);if(u=v.state,d=v.secret,h=((e,t,n,r,a)=>{try{return new Vc({module:e,pqMode:t,rootSuite:n,binding:a.binding,rootKey:a.rootKey,nextOfferer:a.nextOfferer,amInitiator:r})}finally{a.rootKey.fill(0),a.binding.fill(0)}})(i,r,u.rootSuite,p,v.pqHealing),!Gi(t,e.withPeerId,c))throw new Error("Handshake transport lease is stale");Ri(e,t),await(async(e,t,n,r,a,o)=>{const i=()=>n.pqRuntime.serialize();e.serializeEdgeCryptoState=i;try{await Di(e,n.state,t,()=>{r(),e.ratchetState&&ti(e.ratchetState),e.ratchetState=n.state,e.pqHealingState?.destroy(),e.pqHealingState=n.pqRuntime,e.messageKeyCache=n.pqRuntime.activeReceiveKeys},a,o)}catch(t){throw e.serializeEdgeCryptoState===i&&(e.serializeEdgeCryptoState=void 0),t}})(e,t,{state:u,pqRuntime:h},()=>{if(!Gi(t,e.withPeerId,c))throw new Error("Handshake transport lease was replaced during persistence");if(!((e,t,n)=>{const r=Wi(e,t);return r.lease===n&&!r.settled&&(r.settled=!0,r.outcome="open",r.resolve(),!0)})(t,e.withPeerId,c))throw new Error("Handshake transport gate is already settled")}),u=null,h=null}catch(n){throw Yi(t,e.withPeerId,n,c),n}finally{d?.fill(0),l?.fill(0),u&&ti(u),h?.destroy(),xl(t,e.withPeerId,new Error("Handshake attempt finished"),s)}},Ml=new WeakMap,_l=(e,t,n,r)=>(async(e,t,n,r)=>Ki(n,e.withPeerPublicKey,async()=>{Mi(e,n);const a=r?.()??e.serializeEdgeCryptoState?.()??null;try{await _i(t,n,e.withPeerPublicKey,e.withPeerId,a)}finally{a?.fill(0)}Mi(e,n)}))(e,t,n,r),Ul=e=>{throw new Error(`pqHealingOrchestrator: ${e}`)};class Dl extends Error{constructor(e){super("pqHealingOrchestrator: edge checkpoint persistence failed",{cause:e}),this.name="PqPersistenceError"}}const Tl=e=>{const t=Ml.get(e);return!(!t||!t.inboundBlocked&&!t.failed)||(e.pqHealingState?.trafficBlocked??!1)},Nl=(e,t)=>0===(e.messageChannels?.size??0)&&!((e,t)=>{const n=fs(e,t);return(ds.get(n)??0)>0||ls.has(n)})(t,e.withPeerId),ql=async(e,t,n)=>Ni(e,async()=>{const r=e.pqHealingState,a=e.ratchetState;if(!r||!a)return Ul("edge has no live PQ runtime or ratchet");const o=r.clone();let i;try{if(i=await n(o),i.persist){try{await t.persistEdge(e,a,t.roomId,()=>o.serialize())}catch(e){throw new Dl(e)}if(e.pqHealingState!==r)throw new Dl(new Error("live PQ runtime changed during persistence"));r.adopt(o),e.messageKeyCache=r.activeReceiveKeys}else o.destroy()}catch(e){throw o.destroy(),e}i.dispatch&&(i.dispatch=Uint8Array.from(i.dispatch),t.hooks.sendControlFrame(i.dispatch)||i.dispatch.fill(0))}),Ol=e=>{const t=Ml.get(e);t&&(t.destroyed=!0,null!==t.interval&&clearInterval(t.interval),t.interval=null,Ml.delete(e))},Bl=(e,t)=>{e.failed||(e.failed=!0,e.hooks.failEdge(t))},Ll=async e=>{const t=Ml.get(e),n=e.pqHealingState;if(t&&!t.destroyed&&!t.failed&&!t.busy&&n){t.busy=!0;try{const r=t.now(),a=n.pendingRetryAt;if(null!==a&&r>=a)return n.pendingAttempts>=8?void Bl(t,new Error("pqHealingOrchestrator: control retry budget exhausted; failing the authenticated edge")):void await ql(e,t,e=>{e.markPendingDispatched(r);const t=e.copyPendingFrame();return t?Promise.resolve({dispatch:t,persist:!0}):Ul("retry tick found no persisted outbox")});n.healingDue(r)&&!n.trafficBlocked&&!t.inboundBlocked&&Nl(e,t.roomId)&&await ql(e,t,async e=>{const t=await e.prepareHealingOffer(r);return e.markPendingDispatched(r),{dispatch:t,persist:!0}})}catch(e){console.error("pqHealingOrchestrator: tick transition failed",e)}finally{t.busy=!1}}},Fl=async(e,t,n)=>{const r=Ml.get(e),a=e.pqHealingState;if(r&&!r.destroyed&&!r.failed&&a)if(n.length===de){r.inboundBlocked=!0;try{await(async(e,t)=>{const n=fs(e,t);for(;;){const e=ls.get(n);if(!e&&0===(ds.get(n)??0))return;e?await e.catch(()=>{}):await new Promise(e=>setTimeout(e,10))}})(t,e.withPeerId);const a=r.now();await ql(e,r,async e=>{const t=await e.acceptControlFrame(Uint8Array.from(n),a);return t.changed?(null!==t.dispatch&&null!==e.pendingRetryAt&&e.markPendingDispatched(a),{dispatch:t.dispatch,persist:!0}):{dispatch:t.dispatch,persist:!1}})}catch(e){if(e instanceof Dl)return void console.error("pqHealingOrchestrator: inbound transition not durable",e);Bl(r,new Error("pqHealingOrchestrator: unauthenticated or forked control cell; failing the authenticated edge",{cause:e}))}finally{r.inboundBlocked=!1}}else Bl(r,new Error("pqHealingOrchestrator: malformed control cell length"))},zl=(e,t)=>{if(!Number.isSafeInteger(t))throw new Error(`coverScheduler: ${e} must be a safe integer`)},jl=(e,t)=>{if(!(t instanceof Uint8Array))throw new Error(`coverScheduler: ${e} must return a Uint8Array`);return t},Hl=e=>e.cancelRequested?0:"control"===e.job.kind?1:2,$l=(e,t)=>{const n=Hl(e)-Hl(t);if(0!==n)return n;return(t.job.priority??0)-(e.job.priority??0)||e.sequence-t.sequence},Vl=e=>({id:e.job.id,kind:e.job.kind,declaredCellCount:e.job.declaredCellCount});class Ql{schedule;clock;laneFactory;makeDummy;maxTimerDriftMs;onStatusChange;onJobResult;onJobInterrupted;cycleDurationMs;slotsPerEpoch;slotsPerLane;status="stopped";running=!1;sequence=0;generation=0;timer;hasTimer=!1;cycle;queued=[];jobs=new Map;constructor(e){if(Xl(e.schedule),this.schedule=Object.freeze({...e.schedule}),this.clock=e.clock,this.laneFactory=e.laneFactory,this.makeDummy=e.makeDummy,this.onStatusChange=e.onStatusChange,this.onJobResult=e.onJobResult,this.onJobInterrupted=e.onJobInterrupted,this.maxTimerDriftMs=e.maxTimerDriftMs??0,!Number.isFinite(this.maxTimerDriftMs)||this.maxTimerDriftMs<0||this.maxTimerDriftMs>=Wl(this.schedule))throw new Error("coverScheduler: max timer drift must be non-negative and less than one slot");this.cycleDurationMs=this.schedule.coverCadenceMs*this.schedule.coverDurationEpochs,this.slotsPerEpoch=this.schedule.coverLanes*this.schedule.coverFramesPerCell,this.slotsPerLane=this.schedule.coverFramesPerCell*this.schedule.coverDurationEpochs,this.assertClockNow()}getStatus(){return this.status}getQueuedJobIds(){return[...this.queued].sort($l).map(({job:e})=>e.id)}enqueue(e){if("string"!=typeof e.id||0===e.id.length)throw new Error("coverScheduler: job id must not be empty");if(this.jobs.has(e.id))throw new Error("coverScheduler: job id is already queued or admitted");if("real"!==e.kind&&"control"!==e.kind)throw new Error("coverScheduler: unsupported job kind");if(zl("declared cell count",e.declaredCellCount),e.declaredCellCount<1||e.declaredCellCount>this.slotsPerLane)throw new Error("coverScheduler: job does not fit the configured F x D lane capacity");if("function"!=typeof e.nextCell)throw new Error("coverScheduler: job nextCell must be a function");void 0!==e.priority&&zl("job priority",e.priority);const t={job:e,sequence:this.sequence++,state:"queued",everAdmitted:!1,sentCells:0,cancelRequested:!1,cancelSent:!1,completed:!1,settled:!1};this.jobs.set(e.id,t),this.queued.push(t),this.sortQueue()}cancel(e){const t=this.jobs.get(e);if(!t||t.settled)return"not-found";if(!t.everAdmitted)return this.removeQueued(t),this.settle(t,{jobId:e,outcome:"cancelled-before-admission"}),"cancelled-before-admission";if("function"!=typeof t.job.cancelCell)throw new Error("coverScheduler: an admitted cancellable job requires cancelCell");return t.cancelRequested=!0,t.completed=!1,this.sortQueue(),"cancel-pending"}complete(e){const t=this.jobs.get(e);return!(!t||t.settled)&&(this.removeQueued(t),t.completed=!0,t.pendingCell=void 0,this.settle(t,{jobId:e,outcome:"completed"}),!0)}start(){if("stopped"!==this.status)return!1;this.running=!0,this.setStatus("starting");const e=this.assertClockNow();return this.cycle?(this.armCycleBoundary(this.cycle.endMs),!0):(this.armOpenBoundary(this.nextCycleBoundary(e,!0)),!0)}suspend(e="suspended"){if("stopped"===this.status||"suspended"===this.status)return!1;this.disarm(),this.setStatus("suspended",e);const t=this.assertClockNow();return!this.cycle||(this.interruptCycle("suspended"),t<=this.cycle.endMs?this.armCycleBoundary(this.cycle.endMs):this.closeCurrentCycle("late-cleanup"),!0)}resume(){if("suspended"!==this.status)return!1;this.running=!0,this.disarm(),this.setStatus("starting");const e=this.assertClockNow();return this.cycle&&e<this.cycle.endMs?(this.armCycleBoundary(this.cycle.endMs),!0):(this.cycle&&this.closeCurrentCycle("late-cleanup"),this.armOpenBoundary(this.nextCycleBoundary(e,!1)),!0)}stop(){if("stopped"===this.status&&!this.cycle)return!1;this.running=!1,this.disarm(),this.setStatus("stopped");for(const e of[...this.jobs.values()])this.removeQueued(e),this.settle(e,{jobId:e.job.id,outcome:"failed",reason:"stopped"});if(this.cycle){for(const e of this.cycle.lanes)e.job=void 0;this.assertClockNow()<=this.cycle.endMs?this.armCycleBoundary(this.cycle.endMs):this.closeCurrentCycle("late-cleanup")}return!0}assertClockNow(){const e=this.clock.now();if(!Number.isFinite(e))throw new Error("coverScheduler: clock returned a non-finite time");return e}nextCycleBoundary(e,t){const n=(e-this.schedule.phaseOffsetMs)/this.cycleDurationMs;let r=Math.ceil(n),a=this.schedule.phaseOffsetMs+r*this.cycleDurationMs;if(!t&&a<=e&&(r++,a=this.schedule.phaseOffsetMs+r*this.cycleDurationMs),!Number.isSafeInteger(a))throw new Error("coverScheduler: next cycle boundary is out of range");return a}cycleIndexAtBoundary(e){const t=Math.round((e-this.schedule.phaseOffsetMs)/this.cycleDurationMs);return zl("cycle index",t),t}sortQueue(){this.queued.sort($l)}removeQueued(e){const t=this.queued.indexOf(e);-1!==t&&this.queued.splice(t,1)}dequeue(){return this.sortQueue(),this.queued.shift()}requeue(e,t){e.settled||e.completed||e.cancelSent||(e.state="queued",this.queued.includes(e)||this.queued.push(e),this.sortQueue(),this.safeNotify(()=>this.onJobInterrupted?.({jobId:e.job.id,reason:t})))}settle(e,t){e.settled||(e.settled=!0,e.state="terminal",this.removeQueued(e),this.jobs.get(e.job.id)===e&&this.jobs.delete(e.job.id),this.safeNotify(()=>this.onJobResult?.(t)))}setStatus(e,t){if(this.status===e)return;const n=this.status;this.status=e,this.safeNotify(()=>this.onStatusChange?.({previous:n,status:e,reason:t}))}safeNotify(e){try{e()}catch{}}disarm(){this.generation++,this.hasTimer&&(this.clock.clearTimeout(this.timer),this.hasTimer=!1,this.timer=void 0)}arm(e,t,n){this.disarm();const r=this.generation,a=()=>{if(r!==this.generation)return;const o=this.assertClockNow(),i=e-o,s=Math.min(2147483647,Math.max(0,i));this.hasTimer=!0,this.timer=this.clock.setTimeout(()=>{if(r!==this.generation)return;this.hasTimer=!1,this.timer=void 0;const o=this.assertClockNow();o<e?a():o>e+this.maxTimerDriftMs?this.handleLateTimer(t,e,o):Promise.resolve(n(r)).catch(()=>{"slot"===t?this.degrade("cell-production-failed"):this.suspend("boundary-handler-failed")})},s)};a()}armOpenBoundary(e){this.arm(e,"open-boundary",t=>this.openCycle(e,t))}armCycleBoundary(e){this.arm(e,"cycle-boundary",()=>this.handleCycleBoundary(e))}armSlot(e){const t=this.slotAt(e,e.nextSlotOrdinal);this.arm(t.deadlineMs,"slot",e=>this.sendSlot(t,e))}handleLateTimer(e,t,n){"slot"!==e?(this.cycle&&(this.interruptCycle("suspended"),this.closeCurrentCycle("late-cleanup")),"stopped"!==this.status&&this.setStatus("suspended","timer-drift")):this.degrade("missed-deadline")}async openCycle(e,t){if(t!==this.generation||!this.running||"stopped"===this.status||"suspended"===this.status)return;const n=this.cycleIndexAtBoundary(e),r=e+this.cycleDurationMs;if(!Number.isSafeInteger(r))throw new Error("coverScheduler: cycle end is out of range");const a=[];for(let e=0;e<this.schedule.coverLanes;e++)a.push(this.dequeue());for(const e of a)e&&(e.state="admitted",e.everAdmitted=!0);const o=[];let i=!1;for(let t=0;t<this.schedule.coverLanes;t++){const s=a[t],c={cycleIndex:n,cycleStartMs:e,cycleEndMs:r,laneIndex:t,job:s?Vl(s):null};try{const e=this.laneFactory(c);if(null===e||"object"!=typeof e||"function"!=typeof e.send||"function"!=typeof e.close)throw new Error("invalid lane");o.push({laneIndex:t,handle:e,openContext:c,job:s})}catch{i=!0}}if(this.cycle={index:n,startMs:e,endMs:r,lanes:o,nextSlotOrdinal:0},i){this.setStatus("degraded","lane-open-failed");for(const e of this.cycle.lanes)e.job=void 0;for(const e of a)e&&this.requeue(e,"lane-open-failed");this.armCycleBoundary(r)}else this.setStatus("active"),t===this.generation&&"active"===this.status&&this.cycle?.index===n&&this.armSlot(this.cycle)}slotAt(e,t){const n=Math.floor(t/this.slotsPerEpoch),r=t%this.slotsPerEpoch,a=Math.floor(r/this.schedule.coverLanes),o=r%this.schedule.coverLanes,i=e.startMs+n*this.schedule.coverCadenceMs,s=(2*r+1)*this.schedule.coverCadenceMs;return{deadlineMs:i+Math.floor(s/(2*this.slotsPerEpoch)),cycleIndex:e.index,cycleStartMs:e.startMs,cycleEndMs:e.endMs,epochIndex:e.index*this.schedule.coverDurationEpochs+n,epochInCycle:n,laneIndex:o,frameIndex:a,laneSlotIndex:n*this.schedule.coverFramesPerCell+a}}jobSlot(e,t){return{...t,jobId:e.job.id,jobKind:e.job.kind,jobCellIndex:e.sentCells}}async requestForSlot(e,t){const n=e.job;if(n&&!n.settled){const e=this.jobSlot(n,t);if(n.cancelRequested&&!n.cancelSent){return{cell:n.pendingCancelCell??jl("cancelCell",await(n.job.cancelCell?.(e))),source:"cancel",slot:t,jobId:n.job.id,jobCellIndex:n.sentCells}}if(!n.completed&&n.sentCells<n.job.declaredCellCount){const r=n.pendingCell??await n.job.nextCell(e);if(null!==r){return{cell:jl("nextCell",r),source:n.job.kind,slot:t,jobId:n.job.id,jobCellIndex:n.sentCells}}}}return{cell:jl("makeDummy",await this.makeDummy(t)),source:"dummy",slot:t,...n?{jobId:n.job.id}:{}}}cacheUnsent(e,t){const n=(t.jobId?this.jobs.get(t.jobId):void 0)??e.job;n&&!n.settled&&("cancel"===t.source?n.pendingCancelCell=t.cell:"real"!==t.source&&"control"!==t.source||(n.pendingCell=t.cell))}acceptSent(e,t){const n=e.job;if(n&&!n.settled)return"cancel"===t.source?(n.pendingCancelCell=void 0,n.cancelSent=!0,void this.settle(n,{jobId:n.job.id,outcome:"cancelled"})):void("real"!==t.source&&"control"!==t.source||(n.pendingCell=void 0,n.sentCells++,n.sentCells===n.job.declaredCellCount&&(n.completed=!0,this.settle(n,{jobId:n.job.id,outcome:"completed"}))))}async sendSlot(e,t){const n=this.cycle;if(t!==this.generation||!n||"active"!==this.status)return;const r=n.lanes.find(({laneIndex:t})=>t===e.laneIndex);if(!r)return void this.degrade("lane-open-failed");let a,o;try{a=await this.requestForSlot(r,e)}catch{return void this.degrade("cell-production-failed")}if(t!==this.generation)return void this.cacheUnsent(r,a);if(this.assertClockNow()>e.deadlineMs+this.maxTimerDriftMs)return this.cacheUnsent(r,a),void this.degrade("missed-deadline");try{o=await r.handle.send(a)}catch{return this.cacheUnsent(r,a),void this.degrade("send-failed")}if(!1===o)return this.cacheUnsent(r,a),void this.degrade("backpressure");if(this.acceptSent(r,a),t!==this.generation||this.cycle!==n)return;n.nextSlotOrdinal++;const i=this.slotsPerEpoch*this.schedule.coverDurationEpochs;n.nextSlotOrdinal<i?this.armSlot(n):this.armCycleBoundary(n.endMs)}degrade(e){if("stopped"===this.status||"suspended"===this.status)return;this.disarm(),this.setStatus("degraded",e);const t=this.assertClockNow();if(this.cycle){if(this.interruptCycle(e),t<=this.cycle.endMs)return void this.armCycleBoundary(this.cycle.endMs);this.closeCurrentCycle("late-cleanup")}this.running&&this.armOpenBoundary(this.nextCycleBoundary(t,!1))}interruptCycle(e){if(this.cycle)for(const t of this.cycle.lanes){const n=t.job;t.job=void 0,n&&this.requeue(n,e)}}finalizeCycleJobs(){if(this.cycle)for(const e of this.cycle.lanes){const t=e.job;e.job=void 0,t&&!t.settled&&(t.cancelRequested&&!t.cancelSent?this.requeue(t,"missed-deadline"):this.settle(t,{jobId:t.job.id,outcome:"failed",reason:"capacity-exhausted"}))}}closeCurrentCycle(e){const t=this.cycle;if(!t)return!0;let n=!0;for(const r of[...t.lanes].sort((e,t)=>e.laneIndex-t.laneIndex))try{r.handle.close({...r.openContext,reason:e})}catch{n=!1}return this.cycle=void 0,n}handleCycleBoundary(e){const t=this.cycle;if(!t||t.endMs!==e)return;this.finalizeCycleJobs();if(!this.closeCurrentCycle("boundary"))return"stopped"!==this.status&&this.setStatus("degraded","lane-close-failed"),void(this.running&&this.armOpenBoundary(this.nextCycleBoundary(this.assertClockNow(),!1)));this.running&&"stopped"!==this.status&&"suspended"!==this.status&&this.openCycle(e,this.generation).catch(()=>{this.suspend("boundary-handler-failed")})}}const Wl=e=>e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell),Xl=e=>{if(null===e||"object"!=typeof e)throw new Error("coverScheduler: schedule must be an object");if(zl("phase offset",e.phaseOffsetMs),zl("cover cadence",e.coverCadenceMs),zl("cover lanes",e.coverLanes),zl("cover frames per cell",e.coverFramesPerCell),zl("cover duration epochs",e.coverDurationEpochs),e.coverCadenceMs<1)throw new Error("coverScheduler: cover cadence must be positive");if(e.coverLanes<1||e.coverLanes>16)throw new Error("coverScheduler: cover lanes must be between 1 and 16");if(e.coverFramesPerCell<1)throw new Error("coverScheduler: cover frames per cell must be positive");if(e.coverDurationEpochs<1)throw new Error("coverScheduler: cover duration epochs must be positive");const t=e.coverLanes*e.coverFramesPerCell,n=e.coverFramesPerCell*e.coverDurationEpochs,r=e.coverCadenceMs*e.coverDurationEpochs;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||!Number.isSafeInteger(r))throw new Error("coverScheduler: schedule geometry is out of range");if(Wl(e)<25)throw new Error("coverScheduler: schedule requires at least 25ms per staggered slot")},Gl=de-69-H,Jl=N,Yl=Gl-1-4,Zl=(1n<<64n)-1n,ed=(new TextEncoder).encode("p2party/cover-cell/key/v1\0");class td extends Error{code;constructor(e,t){super(`coverCell: ${t}`),this.name="CoverCellError",this.code=e}}const nd=(e,t)=>{throw new td(e,t)},rd=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&nd("invalid-cell",`${t} must be exactly ${String(n)} bytes`),e):nd("invalid-cell",`${t} must be a Uint8Array`),ad=(e,t)=>"bigint"!=typeof e||e<0n||e>Zl?nd("invalid-cell",`${t} must be an unsigned 64-bit bigint`):e,od=(e,t,n,r,a,o)=>{rd(n,"PQ message root",32),rd(r,"edge binding",32);const i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,ad(o,"keyEpoch"),!1);const s=new Uint8Array(ed.length+1+1+r.length+i.length);s.set(ed,0),s[ed.length]=(e=>e===fe?1:e===he?2:e===pe?3:nd("invalid-cell","authenticated room suite is unsupported"))(t),s[ed.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:nd("invalid-direction","cover-cell direction is unknown"))(a),s.set(r,ed.length+2),s.set(i,ed.length+2+r.length);const c=No(n,r,e);try{return qo(c,s,z,e)}finally{c.fill(0),i.fill(0)}},id=e=>{const t=rd(e.binding,"edge binding",32),n=ad(e.keyEpoch,"keyEpoch"),r=ad(e.counter,"counter"),a=(e=>{if("dummy"===e.subtype)return new Uint8Array(0);if("cancel"===e.subtype)return Uint8Array.from(rd(e.merkleRoot,"cancel transfer root",Jl));const t=rd(e.merkleRoot,"receipt transfer root",Jl),n=rd(e.token,"receipt token",Jl),r=new Uint8Array(t.length+n.length);return r.set(t,0),r.set(n,t.length),r})(e.content);a.length>Yl&&nd("invalid-cell","cover payload does not fit the uniform cell");const o=(()=>{const e=new Uint8Array(j);return crypto.getRandomValues(e),e})(),i=new Uint8Array(69);i[0]=4,i.set(t,1);const s=new DataView(i.buffer,i.byteOffset,i.byteLength);s.setBigUint64(33,r,!1),s.setBigUint64(49,n,!1),i.set(o,57);const c=new Uint8Array(Gl);var l;c[0]="dummy"===(l=e.content.subtype)?1:"cancel"===l?2:"receipt"===l?3:nd("invalid-cell","cover-cell subtype is unknown"),new DataView(c.buffer,c.byteOffset,c.byteLength).setUint32(1,a.length,!1),c.set(a,5);const d=od(e.module,e.rootSuite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+H,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{return new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a),0!==e._encrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?nd("invalid-cell","cover-cell AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{Da(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),Da(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),Da(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,d,o,c,i),n=new Uint8Array(de);return n.set(i,0),n.set(t,69),n}finally{d.fill(0),c.fill(0),a.fill(0)}},sd=e=>{const t=rd(e.frame,"cover cell",de),n=rd(e.binding,"edge binding",32),r=ad(e.keyEpoch,"keyEpoch");4!==t[0]&&nd("invalid-cell","frame type is not a cover cell"),((e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n})(t.subarray(1,33),n)||nd("binding-mismatch","cover cell belongs to another edge");const a=t.subarray(0,69),o=new DataView(t.buffer,t.byteOffset,t.byteLength),i=o.getBigUint64(33,!1);0n!==o.getBigUint64(41,!1)&&nd("invalid-cell","cover-cell reserved header must be zero"),o.getBigUint64(49,!1)!==r&&nd("epoch-mismatch","cover-cell epoch is not the expected epoch"),void 0!==e.counterAbove&&(ad(e.counterAbove,"counterAbove"),i<=e.counterAbove&&nd("replayed-counter","cover-cell counter is not strictly newer"));const s=t.subarray(57,69),c=t.subarray(69),l=od(e.module,e.rootSuite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-H,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a);const u=new Uint8Array(e.wasmMemory.buffer,d,o);return u.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?nd("authentication-failed","cover-cell authentication failed"):Uint8Array.from(u)}finally{Da(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),Da(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,l,s,c,a);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(1,!1);t>Yl&&nd("invalid-padding","encrypted cover payload length is invalid");const n=5,r=n+t;let o=0;for(let e=r;e<d.length;e+=1)o|=d[e];0!==o&&nd("invalid-padding","encrypted cover padding must be all zero");return{content:(u=d[0],h=d.subarray(n,r),1===u?(0!==h.length&&nd("invalid-cell","dummy cover cells carry no payload"),{subtype:"dummy"}):2===u?(h.length!==Jl&&nd("invalid-cell","CANCEL payload must be one 64-byte transfer root"),{subtype:"cancel",merkleRoot:Uint8Array.from(h)}):3===u?(h.length!==2*Jl&&nd("invalid-cell","receipt payload must be root ‖ token"),{subtype:"receipt",merkleRoot:h.slice(0,Jl),token:h.slice(Jl)}):nd("invalid-cell","cover-cell subtype is unknown")),counter:i}}finally{l.fill(0),d?.fill(0)}var u,h},cd={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},ld=(e,t)=>{if(e.length<8)throw new Error("coverRuntime: policy hash must be at least 8 bytes");if(!Number.isSafeInteger(t)||t<=0)throw new Error("coverRuntime: cover cadence must be a positive integer");const n=new DataView(e.buffer,e.byteOffset,e.byteLength);return Number(n.getBigUint64(0,!1)%BigInt(t))};class dd{#Q;#e;#W;#_;#U;#X;#G=0n;#J=null;#Y=new Set;static#Z=1024n;#ee=new Map;#te=!1;#p=!1;#ne="stopped";constructor(e){this.#Q=e.epc,this.#e=e.module,this.#W=e,this.#_=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#U=e.amInitiator?"responder-to-initiator":"initiator-to-responder";const t={...e.schedule,phaseOffsetMs:ld(e.policyHash,e.schedule.coverCadenceMs)},n=Wl(t),r=e.maxTimerDriftMs??Math.max(0,Math.min(Math.floor(n)-1,500));this.#X=(e=>new Ql(e))({schedule:t,maxTimerDriftMs:r,clock:e.clock??cd,laneFactory:e=>this.#re(e),makeDummy:e=>this.#ae(e),onStatusChange:t=>{this.#ne=t.status,e.onStatusChange?.(t)},onJobResult:t=>{const n=this.#ee.get(t.jobId);n&&(this.#ee.delete(t.jobId),n()),e.onJobResult?.(t)},onJobInterrupted:e.onJobInterrupted})}cellsPerLanePerCycle(){return this.#W.schedule.coverFramesPerCell*this.#W.schedule.coverDurationEpochs}onJobSettled(e,t){this.#j(),this.#ee.set(e,t)}randomLaneLabel(){return this.#oe()}get status(){return this.#ne}start(){this.#j(),this.#ie(),this.#X.start()}stop(){this.#se(),this.#X.stop()}destroy(){this.#p||(this.stop(),this.#p=!0)}suspend(e){this.#j(),this.#X.suspend(e)}resume(){this.#j(),this.#X.resume()}enqueue(e){this.#j(),this.#X.enqueue(e)}cancel(e){return this.#j(),this.#X.cancel(e)}complete(e){this.#j(),this.#X.complete(e)}getQueuedJobIds(){return this.#X.getQueuedJobIds()}sealCoverContent(e){return this.#j(),this.#ce(e)}processInboundCoverCell(e){this.#j();const t=this.#Q.pqHealingState;if(!t||e.length!==de)return!1;const n=t.currentMessageContext();try{const t=sd({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#U,keyEpoch:n.epoch,frame:e});return!!this.#le(t.counter)&&("cancel"===t.content.subtype?this.#W.onRemoteCancel?.(ca(t.content.merkleRoot)):"receipt"===t.content.subtype&&this.#W.onScheduledReceipt?.(ca(t.content.merkleRoot),t.content.token),!0)}catch{return!1}}async makeDummyLaneLabel(){const e=new Uint8Array(64);return crypto.getRandomValues(e),po(this.#W.laneLabelName,e)}#le(e){const t=this.#J;if(null!==t&&t>=dd.#Z&&e<=t-dd.#Z)return!1;if(this.#Y.has(e))return!1;if(this.#Y.add(e),(null===t||e>t)&&(this.#J=e,e>=dd.#Z)){const t=e-dd.#Z;for(const e of this.#Y)e<=t&&this.#Y.delete(e)}return!0}#ce(e){const t=this.#Q.pqHealingState;if(!t)throw new Error("coverRuntime: edge has no live PQ runtime");const n=t.currentMessageContext(),r=this.#G;return this.#G+=1n,id({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#_,keyEpoch:n.epoch,counter:r,content:e})}#ae(e){return this.#ce({subtype:"dummy"})}#re(e){const t=null!==e.job?e.job.id:this.#oe(),n=this.#W.openLaneChannel(t);return{send:e=>{if(e.cell.length!==de)throw new Error("coverRuntime: refusing a non-uniform cell at the lane boundary");if("open"!==n.readyState)return!1;if(n.bufferedAmount>=Z)return!1;const t=Uint8Array.from(e.cell);return n.send(t.buffer),!0},close:e=>{"closed"!==n.readyState&&n.close()}}}#oe(){const e=(new TextEncoder).encode(this.#W.laneLabelName),t=new Uint8Array(32);t.set(e.subarray(0,Math.min(32,e.length)));const n=new Uint8Array(64);return crypto.getRandomValues(n),`${ca(t)}~${ca(n)}`}#de=()=>{"undefined"!=typeof document&&("hidden"===document.visibilityState?this.#X.suspend("page-hidden"):this.#X.resume())};#ue=()=>{this.#X.suspend("pagehide")};#he=()=>{this.#X.suspend("freeze")};#fe=()=>{this.#X.suspend("offline")};#pe=()=>{this.#X.resume()};#ie(){this.#te||(this.#te=!0,"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.#de),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.#ue),window.addEventListener("freeze",this.#he),window.addEventListener("offline",this.#fe),window.addEventListener("online",this.#pe)))}#se(){this.#te&&(this.#te=!1,"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.#de),"undefined"!=typeof window&&(window.removeEventListener("pagehide",this.#ue),window.removeEventListener("freeze",this.#he),window.removeEventListener("offline",this.#fe),window.removeEventListener("online",this.#pe)))}#j(){if(this.#p)throw new Error("coverRuntime: runtime is destroyed")}}const ud=new WeakMap,hd=e=>{if(e.coverRuntime&&(e.coverRuntime.destroy(),e.coverRuntime=void 0),e.coverChannels){for(const t of e.coverChannels)"closed"!==t.readyState&&t.close();e.coverChannels.clear(),e.coverChannels=void 0}},fd=(e,t,n,r,a)=>{let o=ud.get(e);o||(o=new Map,ud.set(e,o)),o.set(r,{transferId:a,peerId:n,roomId:t})},pd=e=>{const t=e.epc.coverRuntime;if(!t)return!1;const n=is({runtime:t,channelMessageLabel:e.channelMessageLabel,totalChunks:e.totalChunks,sealSlotCell:e.sealSlotCell,getAckedChunks:e.getAckedChunks});return t.enqueue(n),!0},md=new Map,yd=(e,t)=>{const n=md.get(e);n&&(n.delete(t),0===n.size&&md.delete(e))},gd=(e,t)=>{e.controller.signal.aborted||e.controller.abort(t)},wd=()=>{const e=new Uint8Array(32);globalThis.crypto.getRandomValues(e);let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t},bd=e=>/^[0-9a-f]{64}$/.test(e),vd=(e,t=wd())=>{if(0===e.length)throw new Error("Transfer roomId must not be empty");if(!bd(t))throw new Error("Transfer ID must be 32-byte lowercase hex");if([...md.get(e)??[]].some(e=>e.transferId===t))throw new Error("Transfer ID is already active in this room");const n={transferId:t,controller:new AbortController,finished:!1};let r=md.get(e);return r||(r=new Set,md.set(e,r)),r.add(n),{transferId:t,signal:n.controller.signal,bindHash(e){n.hashHex=e},bindMerkleRoot(e){n.merkleRootHex=e},finish(){n.finished||(n.finished=!0,yd(e,n))}}},kd=(e,t)=>{if(!t.transferId&&!t.hashHex&&!t.merkleRootHex)throw new Error("Transfer cancellation requires a transfer ID, hash, or Merkle root");if(t.transferId&&!bd(t.transferId))throw new Error("Transfer ID must be 32-byte lowercase hex");const n=md.get(e);if(!n)return 0;const r=[...n].filter(e=>void 0!==t.transferId?e.transferId===t.transferId:void 0!==t.merkleRootHex?e.merkleRootHex===t.merkleRootHex:e.hashHex===t.hashHex);if(void 0===t.transferId&&r.length>1)throw new Error("Transfer selector is ambiguous; cancel with the random transfer ID");let a=0;for(const e of r)gd(e,new Error("Message transfer cancelled")),a++;return a},Id=e=>{const t=md.get(e);if(!t)return 0;let n=0;for(const e of t)gd(e,new Error("Room transfers cancelled")),n++;return n},Sd=()=>{let e=0;for(const t of[...md.keys()])e+=Id(t);return e},Cd=e=>{if(e?.aborted){if(e.reason instanceof Error)throw e.reason;throw new Error("Message transfer cancelled")}},Ad=async(e,t)=>(Cd(t),t?new Promise((n,r)=>{const a=()=>{o(),r(t.reason instanceof Error?t.reason:new Error("Message transfer cancelled"))},o=()=>t.removeEventListener("abort",a);t.addEventListener("abort",a,{once:!0}),e.then(e=>{o(),n(e)},e=>{o(),r(e)})}):e),Ed=e=>{e.fill(0)},Pd=e=>{if("string"!=typeof e||0===e.length)throw new Error("roomPinVault: room context must be a non-empty string")};const xd=new class{#me=new Map;#ye;constructor(e=Ed){this.#ye=e}put(e,t){Pd(e),(e=>{if(!(e instanceof Uint8Array))throw new Error("roomPinVault: PIN must be a Uint8Array");if(0===e.length)throw new Error("roomPinVault: PIN must not be empty")})(t);const n=Uint8Array.from(t),r=this.#me.get(e);r&&this.#ye(r),this.#me.set(e,n)}get(e){Pd(e);const t=this.#me.get(e);return t?Uint8Array.from(t):void 0}has(e){return Pd(e),this.#me.has(e)}delete(e){Pd(e);const t=this.#me.get(e);return!!t&&(this.#ye(t),this.#me.delete(e))}clear(){for(const e of this.#me.values())this.#ye(e);this.#me.clear()}},Kd=e=>xd.delete(e),Rd=()=>{xd.clear()},Md=3e5,_d=new Map,Ud=(e,t)=>{const n=t-Md,r=(_d.get(e)??[]).filter(e=>e>n);return 0===r.length?_d.delete(e):_d.set(e,r),r},Dd=async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=Ud(e,t);if(!(n.length<30))throw new Error(`PIN retries for this room are temporarily throttled until ${new Date(n[0]+Md).toISOString()}`)})(e,n);const r=await co(e,t);if(r&&r.retryAfter>n)throw new Error(`PIN retry for this peer identity is throttled until ${new Date(r.retryAfter).toISOString()}`)},Td=async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=Ud(e,t);n.push(t),_d.set(e,n)})(e,n),await((e,t,n,r,a,o)=>Wa("incrementPinAttemptState",e,t,n,r,a,o))(e,t,n,3,500,3e5)},Nd=(e,t)=>(void 0===t&&(e=>{_d.delete(e)})(e),((e,t)=>Wa("deletePinAttemptState",e,t))(e,t)),qd=new Map,Od=(new TextEncoder).encode("p2party/room-channel/v1\0"),Bd=(e,t,n)=>{const r=la(e);if(32!==r.length)throw new Error("Room capability must be 32 bytes");if(32!==n.length)throw new Error("Room policy hash must be 32 bytes");const a=(new TextEncoder).encode(t),o=new Uint8Array(Od.length+r.length+n.length+a.length);let i=0;return o.set(Od,i),i+=Od.length,o.set(r,i),i+=r.length,o.set(n,i),i+=n.length,o.set(a,i),o},Ld=async({channel:e,epc:t,roomId:n,dataChannels:r,incoming:a=!1},o)=>{const{keyPair:i,rooms:s}=o.getState(),c=s.findIndex(e=>e.id===n),l=[],d=new Set,u={value:!1},h=new AbortController,f=((e,t)=>({roomId:e,peerId:t,pending:[],seen:new Set,draining:!1,released:!1}))(n,t.withPeerId);if("string"==typeof e){const a=r.findIndex(r=>r.label===e&&r.withPeerId===t.withPeerId&&r.roomIds.includes(n));if(a>-1&&"open"===r[a].readyState)return r[a]}const p="string"==typeof e?e:e.label;if(0===p.length||p.length>193||!p.includes("~")&&(new TextEncoder).encode(p).length>32)throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected invalid or oversized DataChannel label");if(a&&"main"===p&&(m=i.publicKey,y=t.withPeerPublicKey,Fa(m,y)))throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected incoming main DataChannel on the designated opener side");var m,y;if(!a&&"main"===p&&!Fa(i.publicKey,t.withPeerPublicKey))throw new Error("Only the designated identity may create main DataChannel");if("main"===p&&t.mainChannel&&"closing"!==t.mainChannel.readyState&&"closed"!==t.mainChannel.readyState){if(!a)return t.mainChannel;if(t.mainChannel!==e)throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected duplicate main DataChannel")}const g="string"==typeof e?t.createDataChannel(e,{ordered:"main"===e,protocol:"raw"}):e;g.binaryType="arraybuffer";const w=g;w.withPeerId=t.withPeerId,w.roomIds=[n],"main"===w.label&&(t.mainChannel=w);const b="main"!==w.label&&void 0!==t.coverRuntime;if(b)t.coverChannels??=new Set,t.coverChannels.add(w);else if("main"!==w.label){if(t.messageChannels??=new Set,!t.messageChannels.has(w)&&t.messageChannels.size>=64)throw"closed"!==w.readyState&&w.close(),new Error("Too many message DataChannels on one peer edge");t.messageChannels.add(w)}const v=t.ratchetGateLease,k="main"===w.label?t.ratchetGateLease:void 0,I="main"===w.label?((e,t,n,r="hybrid-mlkem768",a=!1)=>{const o=Pl(e,t),i=El.get(o);if(i){const e=new Error("Handshake channel replaced");for(const t of i.waiters)t.reject(e)}const s={token:Symbol("handshake-inbox")};return El.set(o,{lease:s,pqMode:r,expectFinish:a,channel:n,queue:[],nextStep:1,waiters:[]}),s})(n,t.withPeerId,w,s[c]?.policy.pqMode??"hybrid-mlkem768",Fa(i.publicKey,t.withPeerPublicKey)):void 0;let S;try{S=await mo(p)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw t.messageChannels?.delete(w),t.mainChannel===w&&(t.mainChannel=void 0),I&&xl(n,t.withPeerId,r,I),"closed"!==w.readyState&&w.close(),r}const{channelLabel:C,merkleRoot:A,merkleRootHex:E}=S;let P=!1,x=!1;const K=()=>{x||(x=!0,(e=>{if(e.released)return;e.released=!0;const t=e.pending.length;e.pending.length=0,e.seen.clear(),t>0&&ws(e,-t)})(f),t.messageChannels?.delete(w))},R=()=>{P||(P=!0,h.signal.aborted||h.abort(new Error("Message channel processing stopped")),((e,t,n,r)=>{r&&(r.released=!0);const a=e.reduce((e,t)=>e+t.byteLength,0);e.length=0,a>0&&ys(e,t,n,-a),r&&ps(e,r)})(l,n,t.withPeerId,u),K())};w.releaseProtocolResources=R;let M,_=!1;const U=()=>M||(_=!0,R(),M=(async()=>{await ms(l,u),""!==E&&(await Fi(t,n,E),await ro(E))})(),M);return"main"!==w.label&&(w.cancelReceiveTransfer=U),w.onclose=async()=>{if(St(`Channel with label ${w.label} has closed.`),b){if(t.coverChannels?.delete(w),K(),await ms(l,u),""!==E)try{const e=await Ya(E);await zi(t,n,E,e)}catch(e){console.error(e)}R()}else if("main"===w.label){if(R(),k&&!Gi(n,t.withPeerId,k))return;I&&xl(n,t.withPeerId,new Error("Main data channel closed"),I),await o.dispatch(Du.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}));const e=Date.now(),r=qd.get(n)??0;e-r>2e3?(qd.set(n,e),o.dispatch(Ze({roomId:n,connectingToPeers:!0}))):St(`Skipping reconnection for ${n} - debounce (${String(e-r)}ms since last)`)}else{if(!r.includes(w))return;K(),await ms(l,u);let e,a=!1;if(_)try{await M,a=!0}catch(e){console.error(e)}else if(""!==E)try{e=await Ya(E);const r="connected"===t.connectionState&&Gi(n,t.withPeerId,v);a=void 0===t.coverRuntime&&((e,t,n)=>n&&void 0!==e&&e.fromPeerId===t&&Number.isFinite(e.totalSize)&&Number.isFinite(e.savedSize)&&e.totalSize>0&&e.savedSize>=0&&e.savedSize<e.totalSize)(e,t.withPeerId,r),void 0===t.coverRuntime&&!e&&r&&t.messageKeyByMerkleRoot?.has(E)&&(a=!0)}catch(e){console.error(e),a=!1}if(a)try{await U()}catch(e){console.error(e),a=!1}else{if(""!==E)try{await zi(t,n,E,e)}catch(e){console.error(e)}R()}await o.dispatch(Du.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:w.label,channel:w,alsoDeleteData:a}))}},w.onerror=async e=>{if(console.error(e),"main"===w.label){if(k&&!Gi(n,t.withPeerId,k))return;await o.dispatch(Du.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}))}else{if(!r.includes(w))return R(),void("closed"!==w.readyState&&w.close());await o.dispatch(Du.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:w.label,channel:w}))}const a=Date.now(),i=qd.get(n)??0;a-i>2e3?(qd.set(n,a),o.dispatch(Ze({roomId:n,connectingToPeers:!0}))):St(`Skipping reconnection for ${n} - debounce (${String(a-i)}ms since last)`)},w.onmessage=async e=>{const r=new Uint8Array(e.data);if("main"!==w.label&&!Ji(n,t.withPeerId,v))return console.error("Rejected application data before peer authentication"),R(),void("closed"!==w.readyState&&w.close());const a=(e=>{const t=e.length>=1?e[0]:-1,n=3===t&&e.length!==ie?-1:t;return{type:n,payload:-1===n?e.subarray(e.length):e.subarray(1)}})(r);if("main"!==w.label&&3===a.type){return void(((e,t,n)=>{if(t.released)return!1;const r=cs(e);if(t.seen.has(r))return!0;const a=hs.get(fs(t.roomId,t.peerId))??0;return!(t.pending.length>=2048||a>=8192||(t.seen.add(r),t.seen.size>4096&&t.seen.clear(),t.pending.push(e),ws(t,1),t.draining||bs(t,n),0))})(a.payload,f,async e=>{Ji(n,t.withPeerId,v)&&await Ao(e,w.label,w.withPeerId,n,o)})||(console.error("Closing message DataChannel: receipt queue budget exceeded"),R(),"closed"!==w.readyState&&w.close()))}if(2===a.type&&r.length===de){const e=((e,t,n,r,a,o,i,s,c,l,d,u,h,f)=>{if(r.released||f?.aborted)return!1;const p=cs(e);if(n.has(p))return!0;const m=ds.get(fs(o,i))??0;return!(t.length>=64||m+e.byteLength>16777216)&&(n.add(p),n.size>4096&&n.clear(),t.push(e),ys(t,o,i,e.byteLength),r.value||ks(t,n,r,a,o,i,s,c,l,d,u,h,f),!0)})(r,l,d,u,o,n,w.withPeerId,C,E,A,w,t,t.receiveMessageModule,h.signal);return void(e||(console.error("Closing message DataChannel: receive queue budget exceeded"),R(),"closed"!==w.readyState&&w.close()))}if(("main"===w.label||b)&&5===a.type&&r.length===de)return Ji(n,t.withPeerId,v)?void Fl(t,n,r):void console.error("Rejected PQ control cell before peer authentication");if(4===a.type&&r.length===de&&t.coverRuntime)return Ji(n,t.withPeerId,v)?void t.coverRuntime.processInboundCoverCell(r):void console.error("Rejected cover cell before peer authentication");if("main"===w.label){const{type:e,payload:r}=a;if(1===e)return void(I&&!Kl(n,t.withPeerId,r,I)&&(console.error("Closing main DataChannel: malformed or surplus handshake frame"),R(),"closed"!==w.readyState&&w.close()))}console.error(new Error("Wrong data length received"))},w.onopen=()=>{if("main"!==w.label&&!Gi(n,t.withPeerId,v))return R(),void("closed"!==w.readyState&&w.close());St(`Channel with label "${w.label}" and client ${t.withPeerId} is open.`),r.includes(w)||r.push(w),""===E&&C.length>0&&o.dispatch(it({roomId:n,label:p,peerId:w.withPeerId})),"main"===w.label&&(async()=>{let e,r=!1,a=!1;o.dispatch(ot({roomId:n,peerId:t.withPeerId,status:"authenticating"}));try{if(!k||!I)throw new Error("Main channel has no transport ownership lease");const d=s[c];if(!d)throw new Error("Handshake room is unavailable");if("pin"===d.policy.authMode&&(r=!0,l=d.url,e=xd.get(l),!e))throw new Error("PIN room has no local PIN");r&&await Dd(n,t.withPeerPublicKey);const u=Fa(i.publicKey,t.withPeerPublicKey),h=la(i.publicKey),f=la(t.withPeerPublicKey),p=Cl(t.localDescription?.sdp??""),m=Cl(t.remoteDescription?.sdp??""),y=await Ve(d.policy),g=sl({channelId:Bd(d.url,w.label,y),ikInitiator:u?h:f,ikResponder:u?f:h,fpInitiator:u?p:m,fpResponder:u?m:p,pqMode:d.policy.pqMode});a=!0,await Rl(t,n,d.policy.authMode,d.policy.pqMode,e??null,g,t.receiveMessageModule,I,k),o.dispatch(ot({roomId:n,peerId:t.withPeerId,status:"authenticated"})),((e,t,n)=>{e.pqHealingState||Ul("cannot install an orchestrator without a PQ runtime"),Ol(e);const r={roomId:t,hooks:n,now:n.now??Date.now,persistEdge:n.persistEdge??_l,interval:null,busy:!1,inboundBlocked:!1,destroyed:!1,failed:!1};Ml.set(e,r);const a=n.tickMs??1e3;a>0&&(r.interval=setInterval(()=>{Ll(e)},a))})(t,n,{sendControlFrame:e=>"open"===w.readyState&&(w.send(e.buffer),!0),failEdge:e=>{console.error(e),"closed"!==w.readyState&&w.close(),"closed"!==t.connectionState&&t.close()}}),(e=>{const{epc:t,roomId:n,policy:r}=e;if("scheduled"!==r.coverMode)return;hd(t),t.coverChannels??=new Set;const a=new dd({epc:t,roomId:n,module:e.module,amInitiator:e.amInitiator,schedule:{coverCadenceMs:r.coverCadenceMs,coverLanes:r.coverLanes,coverFramesPerCell:r.coverFramesPerCell,coverDurationEpochs:r.coverDurationEpochs},policyHash:e.policyHash,laneLabelName:"p2party-cover",openLaneChannel:e=>{const r=t.createDataChannel(e,{ordered:!0,protocol:"raw"});return r.binaryType="arraybuffer",r.withPeerId=t.withPeerId,r.roomIds=[n],t.coverChannels.add(r),r.addEventListener("close",()=>{t.coverChannels?.delete(r)}),{label:r.label,get readyState(){return r.readyState},get bufferedAmount(){return r.bufferedAmount},send:e=>r.send(e),close:()=>{"closed"!==r.readyState&&r.close()}}},onStatusChange:e.onStatusChange,onRemoteCancel:e.onRemoteCancel,onScheduledReceipt:e=>{const n=ud.get(t)?.get(e);n&&ko(n.roomId,n.peerId,n.transferId)}});t.coverRuntime=a,a.start()})({epc:t,roomId:n,policy:d.policy,policyHash:y,amInitiator:u,module:t.receiveMessageModule,onStatusChange:({status:e})=>{o.dispatch(at({roomId:n,peerId:t.withPeerId,status:e}))},onRemoteCancel:e=>{try{kd(n,{merkleRootHex:e})}catch(e){console.error("scheduled CANCEL abort failed",e)}}}),r&&await Nd(n,t.withPeerPublicKey).catch(e=>{console.error("Could not clear successful PIN attempt state:",e)})}catch(e){const i=e instanceof Error?e:new Error(String(e));r&&a&&/key-confirmation/i.test(i.message)&&await Td(n,t.withPeerPublicKey).catch(e=>{console.error("Could not persist PIN attempt state:",e)});let s,c="transport";const l=/throttled until (\S+)/.exec(i.message);if(l){c="pin-throttled";const e=Date.parse(l[1]);Number.isFinite(e)&&(s=e)}else if(a&&/key-confirmation/i.test(i.message)&&(c=r?"pin-mismatch":"policy",r))try{const e=await co(n,t.withPeerPublicKey);e&&e.retryAfter>Date.now()&&(s=e.retryAfter)}catch{}o.dispatch(ot({roomId:n,peerId:t.withPeerId,status:"failed",reason:c,retryAfter:s})),k&&Yi(n,t.withPeerId,i,k),I&&xl(n,t.withPeerId,i,I),console.error("protocol-v4 handshake failed:",i),"closed"!==w.readyState&&w.close(),"closed"!==t.connectionState&&t.close()}finally{e?.fill(0)}var l})(),""!==E&&"string"!=typeof e&&(async()=>{try{if(!await(async()=>!!Gi(n,t.withPeerId,v)&&(await Xi(n,t.withPeerId),Gi(n,t.withPeerId,v)))())return;const e=await(e=>Wa("getDBAllChunkLeafHashes",e))(E);if(0===e.length)return;let r=[];for(const{chunkIndex:t,leafHash:n}of e)if(n?.length===2*N&&(r.push(await _o(A,t,la(n))),32===r.length)){if(!await ts(w,r))return;r=[]}if(r.length>0&&!await ts(w,r))return;const a=await Ya(E);a&&a.totalSize>0&&a.savedSize===a.totalSize&&a.hash.length===2*N&&es(w,la(a.hash))}catch(e){console.error(e)}})()},w},Fd=/(?:^|\r?\n)a=ice-ufrag:([^\r\n]+)/g,zd=/(?:^|\s)ufrag\s+([^\s]+)/i,jd=(e,t)=>{const n=(e=>{const t=new Set,n=e?.sdp;if(!n)return t;for(const e of n.matchAll(Fd)){const n=e[1].trim();n&&t.add(n)}return t})(t);if(0===n.size)return!0;const r=(e=>{const t=e.usernameFragment?.trim();if(t)return t;const n=e.candidate?.match(zd)?.[1];return n?.trim()||null})(e);return null===r||n.has(r)},Hd=async(e,t)=>{if(!("closed"===e.connectionState||"closed"===e.signalingState))try{return e.restartIce(),"restarted"}catch{}return await t(),"disconnected"},$d=(e,t,n)=>e.findIndex(e=>((e,t,n)=>e.roomId===t&&e.withPeerId===n)(e,t,n)),Vd=(e,t,n)=>{const r=$d(e,t,n);return r<0?void 0:e[r]};class Qd{queue=[];locked=!1;idleWaiters=[];async acquire(){if(this.locked)return new Promise(e=>{this.queue.push(e)});this.locked=!0}release(){const e=this.queue.shift();if(e)e();else{this.locked=!1;for(const e of this.idleWaiters.splice(0))e()}}isIdle(){return!this.locked&&0===this.queue.length}whenIdle(){return this.isIdle()?Promise.resolve():new Promise(e=>{this.idleWaiters.push(e)})}async runExclusive(e){await this.acquire();try{return await e()}finally{this.release()}}}const Wd=new Map,Xd=new Map,Gd=(e,t)=>`${String(e.length)}:${e}${t}`,Jd=(e,t)=>`${String(e.length)}:${e}${t}`,Yd=(e,t)=>{const n=Gd(e,t);let r=Wd.get(n);return r||(r=new Qd,Wd.set(n,r)),r},Zd=(e,t)=>{const n=Gd(e,t),r=Wd.get(n);r&&(async()=>{for(;;)if(await r.whenIdle(),r.isIdle())return void(Wd.get(n)===r&&Wd.delete(n))})()},eu=async({peerId:t,peerPublicKey:n,roomId:r,peerConnections:a,rtcConfig:o},i)=>{const{keyPair:s,signalingServer:c}=i.getState();if(o??=We,!e(t))throw new Error("PeerId is not a valid uuidv4");if(La(s.publicKey,"Self Ed25519 identity"),La(n,"Peer Ed25519 identity"),n===s.publicKey)throw new Error("Cannot connect to the same Ed25519 identity");const l=((e,t)=>{const n=Jd(e,t);let r=Xd.get(n);return r||(r=new Qd,Xd.set(n,r)),r})(r,n);await l.acquire();try{const e=((e,t,n,r)=>e.filter(e=>e.roomId===t&&e.withPeerPublicKey===r&&e.withPeerId!==n))(a,r,t,n);for(const t of e)await i.dispatch(Du.endpoints.disconnectFromPeer.initiate({roomId:r,peerId:t.withPeerId}));let l=Vd(a,r,t);if(l&&l.withPeerPublicKey!==n&&(await i.dispatch(Du.endpoints.disconnectFromPeer.initiate({roomId:r,peerId:t})),l=void 0),l)return await l.initialization,l;const d=((e,t,n=new Error("Ratchet gate reset"))=>{const r=Qi(e,t),a=Vi.get(r);return a&&!a.settled&&(a.settled=!0,a.outcome="rejected",a.reject(n)),Vi.delete(r),Wi(e,t).lease})(r,t,new Error("Ratchet transport replaced by a new room/peer connection")),u=new RTCPeerConnection(o);u.roomId=r,u.withPeerId=t,u.withPeerPublicKey=n,u.makingOffer=!1,u.ignoreOffer=!1,u.iceCandidates=[],u.ratchetGateLease=d,Ri(u,r),a.push(u);const h=()=>{if(!a.includes(u))throw new Error("WebRTC transport was replaced during initialization")},f=(async()=>{const e=ya(),a=await Ua(e);h(),u.receiveMessageModule=a,c.isConnected&&(await i.dispatch($u.endpoints.connectWithPeer.initiate({roomId:r,peerId:t,peerPublicKey:n})),h())})();u.initialization=f;try{await f}catch(e){const t=a.indexOf(u);throw t>-1&&a.splice(t,1),"closed"!==u.connectionState&&u.close(),e}finally{u.initialization=void 0}u.onnegotiationneeded=async()=>{if(u.makingOffer||"stable"!==u.signalingState)St(`Skipping negotiation with ${t} - already making offer: ${String(u.makingOffer)}, state: ${u.signalingState}`);else try{u.makingOffer=!0,await u.setLocalDescription(),u.localDescription&&(await i.dispatch($u.endpoints.sendMessage.initiate({content:{type:"description",description:u.localDescription,fromPeerId:s.peerId,fromPeerPublicKey:s.publicKey,toPeerId:t,roomId:r,protocolVersion:4}})),St(`Negotiation was needed with ${t} and you sent a description ${u.localDescription.type}.`))}catch(e){console.error(e)}finally{u.makingOffer=!1}},u.onicecandidate=async({candidate:e})=>{e&&""!==e.candidate&&await i.dispatch($u.endpoints.sendMessage.initiate({content:{type:"candidate",candidate:e,fromPeerId:s.peerId,toPeerId:t,roomId:r,protocolVersion:4}}))},u.onicecandidateerror=e=>{console.error(e)};let p=0;const m=3e3;let y;return u.oniceconnectionstatechange=async()=>{if("failed"===u.iceConnectionState||"disconnected"===u.iceConnectionState){const{signalingServer:e}=i.getState();!e.isConnected&&!e.isEstablishingConnection&&e.serverUrl.length>0&&await i.dispatch($u.endpoints.connectWebSocket.initiate(e.serverUrl));const n=Date.now();n-p>m&&(p=n,St(`ICE ${u.iceConnectionState} with ${t}, restarting`),u.restartIce())}St(`ICE candidate connection state with ${t} is ${u.iceConnectionState}.`)},u.onicegatheringstatechange=()=>{St(`ICE gathering state with ${t} is ${u.iceGatheringState}.`)},u.onsignalingstatechange=async()=>{St(`Signaling state with ${t} is ${u.signalingState}.`),"stable"===u.signalingState&&u.remoteDescription&&await(async e=>{for(;e.iceCandidates.length>0&&"stable"===e.signalingState&&e.remoteDescription;){const t=e.iceCandidates.shift();if(t&&jd(t,e.remoteDescription))try{await e.addIceCandidate(t)}catch(e){console.warn("Could not add queued ICE candidate:",e)}}})(u)},u.onconnectionstatechange=async()=>{if("disconnected"===u.connectionState)await Hd(u,()=>{}).catch(()=>{}),y&&clearTimeout(y),y=setTimeout(()=>{"disconnected"===u.connectionState&&(i.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:r})),console.error(`RTC Connection with peer ${t} in room ${r} has disconnected.`))},8e3);else if("closed"===u.connectionState||"failed"===u.connectionState){if(y&&(clearTimeout(y),y=void 0),await i.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:r})),console.error(`RTC Connection with peer ${t} in room ${r} has ${u.connectionState}.`),"closed"===u.connectionState){const{signalingServer:e}=i.getState();e.isConnected&&await i.dispatch($u.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:s.peerId,roomId:r,protocolVersion:4}}))}}else y&&(clearTimeout(y),y=void 0),"connected"===u.connectionState&&(i.dispatch(rt({roomId:r,peerId:t,peerPublicKey:n})),St(`RTC Connection status with peer ${t} is ${u.connectionState}.`))},u}finally{l.release(),((e,t)=>{const n=Jd(e,t),r=Xd.get(n);r&&r.whenIdle().then(()=>{r.isIdle()&&Xd.get(n)===r&&Xd.delete(n)})})(r,n)}},tu=async(e,t,n)=>{const r=e.createDataChannel("main",{ordered:!0,protocol:"raw"});e.mainChannel=await Ld({channel:r,epc:e,roomId:e.roomId,dataChannels:t},n)},nu=(e,t,n)=>{for(let r=e.length-1;r>=0;r--)e[r].roomId===t&&e[r].withPeerId===n&&e.splice(r,1)},ru=async({peerId:e,peerPublicKey:t,roomId:n,description:r,rtcConfig:a,peerConnections:o,iceCandidates:i,dataChannels:s},c)=>Yd(n,e).runExclusive(async()=>{const{keyPair:l}=c.getState(),d=$d(o,n,e),u=d>-1?o[d]:await eu({peerId:e,peerPublicKey:t,roomId:n,peerConnections:o,rtcConfig:a},c);-1!==d&&null!=o[d].ondatachannel||(u.ondatachannel=async e=>{try{const t=await Ld({channel:e.channel,epc:u,roomId:u.roomId,dataChannels:s,incoming:!0},c);"main"===t.label&&(u.mainChannel=t)}catch(e){console.error("Rejected incoming DataChannel:",e)}});const h="offer"===r.type&&(u.makingOffer||"stable"!==u.signalingState),f=l.peerId<u.withPeerId,p=!f&&h;u.ignoreOffer=p;const m=()=>{((e,t,n,r)=>{e.length=0,nu(t,n,r)})(u.iceCandidates,i,n,e)};if(p)return m(),{data:void 0};if(h&&f)try{await u.setLocalDescription({type:"rollback"}),St(`Polite peer rolled back local description for ${e}`)}catch(t){console.error(`Failed to rollback for ${e}:`,t)}if(u.iceCandidates.push(...((e,t,n)=>{const r=[];for(let a=e.length-1;a>=0;a--){const o=e[a];o.roomId===t&&o.withPeerId===n&&(r.unshift(o),e.splice(a,1))}return r})(i,n,e)),-1===$d(o,n,e)&&o.push(u),"closed"===u.signalingState)return m(),{data:void 0};if("answer"===r.type&&"have-local-offer"!==u.signalingState)return console.warn(`Ignoring stale answer from ${e} in signaling state ${u.signalingState}`),m(),{data:void 0};try{await u.setRemoteDescription(r)}catch(t){const n=t;if("answer"===r.type&&n.message?.includes("Called in wrong state"))return console.warn(`Ignoring late answer from ${e}: ${n.message}`),m(),{data:void 0};if(!n.message?.includes("ICE restart"))return console.error(`setRemoteDescription failed for ${e}:`,t),m(),{data:void 0};console.warn(`ICE restart mismatch with ${e}, accepting remote restart`);try{"stable"!==u.signalingState&&await u.setLocalDescription({type:"rollback"}),await u.setRemoteDescription(r)}catch(t){return console.error(`Failed to handle ICE restart for ${e}:`,t),m(),{data:void 0}}}if("offer"===r.type){try{await u.setLocalDescription()}catch(t){return console.error(`setLocalDescription failed for ${e}:`,t),m(),{data:void 0}}const t=u.localDescription;t&&await c.dispatch($u.endpoints.sendMessage.initiate({content:{type:"description",description:t,fromPeerId:l.peerId,fromPeerPublicKey:l.publicKey,toPeerId:e,roomId:n,protocolVersion:4}}))}if("connected"===u.connectionState&&d>-1&&Fa(l.publicKey,u.withPeerPublicKey)&&(!u.mainChannel||"closing"===u.mainChannel.readyState||"closed"===u.mainChannel.readyState)){const e=u.createDataChannel("main",{ordered:!0,protocol:"raw"});u.mainChannel=await Ld({channel:e,epc:u,roomId:u.roomId,dataChannels:s},c)}return{data:void 0}}),au=(e,t)=>new Promise((n,r)=>{try{if(e===t)return void n(e);if(t<e)throw new RangeError("randomNumberInRange: max must be >= min");const r=BigInt(t)-BigInt(e),a=Math.ceil(r.toString(2).length/8),o=(1n<<BigInt(8*a))/r*r,i=new Uint8Array(a);let s=o;for(;s>=o;){window.crypto.getRandomValues(i),s=0n;for(let e=0;e<a;e++)s=(s<<8n)+BigInt(i[e])}n(e+Number(s%r))}catch(e){r(e instanceof Error?e:new Error(String(e)))}}),ou=async(e,t,n=!0,r=!0,a=!0)=>{if(t??=e,0===t&&e===t)return"";const o=t>e?await au(e,t):e,i=await((e,t=!0,n=!0,r=!0)=>new Promise((a,o)=>{try{let o="";t&&(o+="abcdefghijklmnopqrstuvwxyz"),n&&(o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"),r&&(o+="0123456789");let i="";for(let t=0;t<e;t++)i+=o[iu(0,o.length)];a(i)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}))(o,n,r,a);return i};function iu(e,t){if(!(t>e))return e;const n=t-e,r=Math.floor(4294967296/n)*n;let a;do{a=crypto.getRandomValues(new Uint32Array(1))[0]}while(a>=r);return e+a%n}const su=(e,t)=>{const n=t._malloc(q),r=t._malloc(1+e.length),a=t._malloc(N);try{const o=new Uint8Array(t.wasmMemory.buffer,r,1+e.length);if(o[0]=0,o.set(e,1),0!==t._sha512_init(n))throw new Error("hashMerkleLeafWasm: sha512_init failed");if(0!==t._sha512_update(n,r,1+e.length))throw new Error("hashMerkleLeafWasm: sha512_update failed");if(0!==t._sha512_final(n,a))throw new Error("hashMerkleLeafWasm: sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,a,N))}finally{t._free(n),t._free(r),t._free(a)}},cu=async e=>{const t=new Uint8Array(1+e.length);t[0]=0,t.set(e,1);const n=await window.crypto.subtle.digest("SHA-512",t);return new Uint8Array(n)},lu=async(e,t)=>{if(e.length%N!==0)throw new Error("Hashes were not passed");const n=e.length/N;if(0===n)throw new Error("Cannot calculate Merkle root of tree with no leaves.");if(1===n)return e;const r=t?.wasmMemory??ga(n),a=t??await Ua(r),o=a._malloc(n*N),i=new Uint8Array(r.buffer,o,n*N);i.set(e);const s=a._malloc(N),c=new Uint8Array(r.buffer,s,N),l=a._get_merkle_root(n,i.byteOffset,c.byteOffset);switch(a._free(o),l){case 0:{const e=Uint8Array.from([...c]);return a._free(s),e}case-1:throw a._free(s),new Error("Could not allocate memory for hash concatenation helper array.");case-2:throw a._free(s),new Error("Could not calculate hash.");default:throw a._free(s),new Error("Unexpected error occured.")}},du=async(e,t,n,r)=>{if(e.length%N!==0)throw new Error("Hashes were not passed");const a=e.length/N;if(0===a)throw new Error("Cannot calculate Merkle proof of element of empty tree.");if(1===a){const e=new Uint8Array(N+1);if(e.set(t),r){const t=N+1,n=globalThis.crypto.getRandomValues(new Uint8Array(r));let a=0;const o=4;return new DataView(n.buffer,a,o).setUint32(0,t,!1),a+=o,n.set(e,a),n}return e}const o=n?.wasmMemory??wa(a),i=n??await Ua(o),s=i._malloc(a*N),c=new Uint8Array(o.buffer,s,a*N);c.set(e);const l=i._malloc(N),d=new Uint8Array(o.buffer,l,N);d.set(t);const u=a*(N+1),h=i._malloc(u),f=new Uint8Array(o.buffer,h,u),p=i._get_merkle_proof(a,c.byteOffset,d.byteOffset,f.byteOffset);switch(i._free(s),i._free(l),p){case-1:throw i._free(h),new Error("Element not in tree.");case-2:throw i._free(h),new Error("Could not allocate memory for hash concatenation helper array.");case-3:throw i._free(h),new Error("Could not calculate hash.");default:if(p>0){if(r&&r>=p){const e=globalThis.crypto.getRandomValues(new Uint8Array(r));let t=0;const n=4;return new DataView(e.buffer,t,n).setUint32(0,p,!1),t+=n,e.set(f.slice(0,p),t),i._free(h),e}{const e=Uint8Array.from([...f.slice(0,p)]);return i._free(h),e}}throw i._free(h),new Error("An unexpected error occured")}},uu=[1],hu=(e,t=1,n=ne,r=.9)=>{if(t<1)throw new Error("Need at least one chunk.");if(r<1e-4||r>.99)throw new Error("Percentage of useful data in chunk should be in (0, 0.99].");if(n>ne||n<=re)throw new Error(`Chunk length needs to be between ${String(re)} and ${String(ne)}`);if(!Number.isSafeInteger(e)||e<1)throw new Error("No data to split in chunks");if(e>Y)throw new Error(`Message exceeds the ${String(Y)} byte protocol limit`);const a=Math.ceil(n*r),o=Math.ceil(e/a);return Math.max(t,o)},fu=async(e,t,n,r,a,o,i=1,s=ne,c=.9,l=1)=>{const{keyPair:d}=t.getState();if(!uu.includes(l))throw new Error("Unknown metadata version schema.");const u=(e=>{if("string"==typeof e)return xo.Text;const t=e.name.split(".").pop()?.toLowerCase()??"";return{png:xo.ImagePNG,jpeg:xo.ImageJPEG,jpg:xo.ImageJPG,gif:xo.ImageGIF,bmp:xo.ImageBMP,tiff:xo.ImageTIFF,svg:xo.ImageSVG,webp:xo.ImageWEBP,heic:xo.ImageHEIC,pdf:xo.DocumentPDF,doc:xo.DocumentDOC,docx:xo.DocumentDOCX,xls:xo.DocumentXLS,xlsx:xo.DocumentXLSX,ppt:xo.DocumentPPT,pptx:xo.DocumentPPTX,txt:xo.DocumentTXT,rtf:xo.DocumentRTF,odt:xo.DocumentODT,mp3:xo.AudioMP3,wav:xo.AudioWAV,aac:xo.AudioAAC,flac:xo.AudioFLAC,ogg:xo.AudioOGG,m4a:xo.AudioM4A,mp4:xo.VideoMP4,avi:xo.VideoAVI,mkv:xo.VideoMKV,mov:xo.VideoMOV,wmv:xo.VideoWMV,flv:xo.VideoFLV,webm:xo.VideoWEBM,zip:xo.CompressedZIP,rar:xo.CompressedRAR,"7z":xo.Compressed7Z,tar:xo.CompressedTAR,gz:xo.CompressedGZ,html:xo.CodeHTML,css:xo.CodeCSS,js:xo.CodeJS,ts:xo.CodeTS,jsx:xo.CodeJSX,tsx:xo.CodeTSX,json:xo.CodeJSON,xml:xo.CodeXML,py:xo.CodePY,java:xo.CodeJAVA,c:xo.CodeC,cpp:xo.CodeCPP,cs:xo.CodeCS,rb:xo.CodeRB,php:xo.CodePHP,sql:xo.CodeSQL,epub:xo.EbookEPUB,mobi:xo.EbookMOBI,azw:xo.EbookAZW,ttf:xo.FontTTF,otf:xo.FontOTF,ico:xo.ImageICO,exe:xo.ExecutableEXE,dmg:xo.ExecutableDMG,apk:xo.ExecutableAPK}[t]??xo.Unknown})(e),h=u===xo.Text?await ou(256):e.name.substring(0,255),f="string"==typeof e?(new TextEncoder).encode(e):e,p="string"==typeof e?f.length:f.size,m=hu(p,i,s,c),y=await navigator.storage.estimate(),g=y.quota??10737418240,w=y.usage??65536,b=Math.max(0,g-w),v=((e,t,n)=>{if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<1||!Number.isSafeInteger(n)||n<1)throw new Error("Invalid outbound staging geometry");const r=e+t*(n+ee+te+2048);return Number.isSafeInteger(r)?r:Number.POSITIVE_INFINITY})(p,m,s);if(v>b)throw new Error("Not enough space to stage the padded encrypted transfer in the browser.");const k=new Date;let I;if(o.signal.aborted)throw o.signal.reason instanceof Error?o.signal.reason:new Error("Message transfer cancelled");if("string"==typeof e){const e=await window.crypto.subtle.digest("SHA-512",f.buffer);I=new Uint8Array(e)}else I=await(async(e,t,n)=>{const r=()=>{if(n?.aborted){if(n.reason instanceof Error)throw n.reason;throw new Error("Message transfer cancelled")}},a=t._malloc(q),o=t._malloc(be),i=t._malloc(N);try{if(r(),0!==t._sha512_init(a))throw new Error("sha512_init failed");const n=new Uint8Array(t.wasmMemory.buffer,o,be);for(let i=0;i<e.size;i+=we){r();const s=Math.min(i+we,e.size),c=new Uint8Array(await e.slice(i,s).arrayBuffer());r();for(let e=0;e<c.length;e+=be){r();const i=Math.min(be,c.length-e);if(n.set(c.subarray(e,e+i),0),0!==t._sha512_update(a,o,i))throw new Error("sha512_update failed")}}if(r(),0!==t._sha512_final(a,i))throw new Error("sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,i,N))}finally{t._free(a),t._free(o),t._free(i)}})(f,a,o.signal);if(o.signal.aborted)throw o.signal.reason instanceof Error?o.signal.reason:new Error("Message transfer cancelled");const S=ca(I);o.bindHash(S);const C={schemaVersion:l,messageType:u,hash:I,name:h,totalSize:p,date:k};let A=0;const E=new Uint8Array(s),P=new Uint8Array(m*N),x=Math.floor(s*(1-c)),K=Math.ceil(s*c);for(let a=0;a<m&&!o.signal.aborted;a++){window.crypto.getRandomValues(E);const i=await au(0,x),s=p-A,c=Math.min(Math.max(s,0),K);let l=i+c;if(s>0){const t=f.slice(A,A+c);if("string"==typeof e)E.set(t,i);else{const e=await t.arrayBuffer();if(o.signal.aborted)break;E.set(new Uint8Array(e),i)}A+=c}else{const e=l+p+1,t=Number.MAX_SAFE_INTEGER-e;l+=await au(e,t)}const y=await cu(E),g=ca(y);P.set(y,a*N);const w=Eo({...C,chunkStartIndex:i,chunkEndIndex:l,chunkIndex:a});await ao({transferId:o.transferId,hash:S,merkleRoot:"",chunkIndex:a,leafHash:g,receiptToken:"",data:E.slice().buffer,metadata:w.buffer,merkleProof:(new Uint8Array).buffer}),t.dispatch(ct({roomId:r.id,transferId:o.transferId,merkleRootHex:"",sha512Hex:S,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:a+1,totalChunks:m,messageType:u,filename:h,channelLabel:n,timestamp:k.getTime()}))}if(o.signal.aborted)return await oo({transferId:o.transferId}),t.dispatch(ft({roomId:r.id,transferId:o.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};const R=await lu(P,a),M=ca(R);try{const e=Ro(u);for(let t=0;t<m&&!o.signal.aborted;t++){const n=await eo(o.transferId,t);if(!n)throw new Error(`Missing staged outbound chunk ${String(t)}`);const r=Po(new Uint8Array(n.metadata)),a=r.chunkEndIndex-r.chunkStartIndex;a<=0||a>r.totalSize||await to({merkleRoot:M,hash:S,chunkIndex:r.chunkIndex,data:n.data.slice(r.chunkStartIndex,r.chunkEndIndex),mimeType:e})}}catch(e){throw await ro(M),e}if(o.signal.aborted)return await oo({transferId:o.transferId}),await ro(M),t.dispatch(ft({roomId:r.id,transferId:o.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};try{await((e,t,n,r,a,o,i,s,c,l,d)=>Wa("setDBRoomMessageData",e,t,n,r,a,o,i,s,c,l,d))(r.id,M,S,d.peerId,p,p,u,h,n,k.getTime(),o.transferId)}catch(e){throw await ro(M),e}return t.dispatch(ct({roomId:r.id,transferId:o.transferId,merkleRootHex:M,sha512Hex:S,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:m,totalChunks:m,messageType:u,filename:h,channelLabel:n,timestamp:k.getTime()})),{merkleRoot:R,merkleRootHex:M,hash:I,hashHex:S,totalSize:p,totalChunks:m,messageType:u,chunkHashes:P}},pu=async(e,t=3e3,n=25,r)=>{const a=Date.now();for(;"connecting"===e.readyState&&Date.now()-a<t&&!r?.aborted;)await new Promise(e=>setTimeout(e,n));return!r?.aborted&&"open"===e.readyState},mu=(e,t)=>`${e}\0${t}`,yu=async e=>{let t=e.inFlight(),n=Date.now();for(;e.isOpen()&&e.inFlight()>=e.windowSize;){Cd(e.signal);const r=e.inFlight();if(r<t&&(t=r,n=Date.now()),Date.now()-n>=e.stallTimeoutMs)return;await new Promise(t=>setTimeout(t,e.pollMs)),Cd(e.signal)}Cd(e.signal)},gu=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f)=>{Cd(u);const{merkleRootHex:p}=await mo(e.label);if(p!==ca(i))throw new Error("Outbound channel label does not match its Merkle root");const m=f?.()??0;let y=0;const g=function(e){const t=e.slice();for(let e=t.length-1;e>0;e--){const n=iu(0,e+1);[t[e],t[n]]=[t[n],t[e]]}return t}(Array.from({length:a},(e,t)=>t));for(let w=0;w<a;w++){Cd(u);const a=g[w],b=await eo(s,a);if(Cd(u),!b)throw new Error(`Missing staged outbound chunk ${String(a)}`);const v=new Uint8Array(b.metadata),k=Po(v);if(k.chunkIndex!==a||b.chunkIndex!==a)throw new Error("Outbound chunk index does not match its staging key");const I=k.chunkEndIndex>k.chunkStartIndex&&k.chunkEndIndex-k.chunkStartIndex<=k.totalSize;if(void 0!==h&&(!I||h.has(k.chunkIndex)))continue;I&&f&&await yu({windowSize:32,stallTimeoutMs:1e4,pollMs:25,isOpen:()=>"open"===e.readyState,inFlight:()=>y-Math.max(0,f()-m),signal:u});const S=new Uint8Array(te);if(0===b.merkleProof.byteLength){const e=await du(o,la(b.leafHash),d,te);Cd(u),S.set(e)}else S.set(new Uint8Array(b.merkleProof));const C=b.receiptToken.length===2*N?b.receiptToken:ca(await _o(i,k.chunkIndex,la(b.leafHash)));if(Cd(u),0!==b.merkleProof.byteLength&&b.merkleRoot===p&&b.receiptToken===C||await ao({transferId:s,hash:c,merkleRoot:p,leafHash:b.leafHash,receiptToken:C,chunkIndex:a,data:b.data,metadata:b.metadata,merkleProof:S.buffer}),ae!==v.length+S.length+new Uint8Array(b.data).length)throw new Error("Outbound staged chunk has invalid cell length");const A=await ia([v,S,new Uint8Array(b.data)]);for(Cd(u);"open"===e.readyState&&e.bufferedAmount>=Z;)await new Promise(e=>setTimeout(e,25)),Cd(u);if("open"!==e.readyState){St("Cannot send message because channel is "+e.readyState+" and bufferedAmount is "+String(e.bufferedAmount));break}let E;try{E=Ii(t,n,A,i,l,r??void 0)}catch(e){throw new Error("Could not seal outbound message chunk",{cause:e})}Cd(u);try{e.send(E.buffer),I&&y++}catch(t){if("open"!==e.readyState)break;throw t}}},wu=async(e,t,n,r,a,o,i,s)=>{const c=Date.now()+i;for(;Date.now()<c;){Cd(s);const i=a.find(e=>e.roomId===t&&e.withPeerId===n&&"connected"===e.connectionState);if(i)try{await io(mu(t,r),n);const a=await Ld({channel:r,epc:i,roomId:t,dataChannels:o},e);if(await pu(a,c-Date.now(),void 0,s))return{epc:i,channel:a};try{bu(a)}catch(e){console.error(e)}Cd(s)}catch(e){console.error(e)}else await new Promise(e=>setTimeout(e,500)),Cd(s)}return null},bu=e=>{e.releaseProtocolResources?.(),"closed"!==e.readyState&&e.close()},vu=async(e,t)=>{if(!e.pqHealingState)return;const n=Date.now()+6e4;for(;Tl(e);){if(Cd(t),Date.now()>n)throw new Error("v4 send: sparse-PQ healing did not settle before the send timeout");await new Promise(e=>setTimeout(e,25))}},ku=async(e,t,n,r,a=Xi,o=Oi,i)=>{if(Cd(i),e.epc===t)return e;if(await Ad(a(n,t.withPeerId),i),!t.ratchetState)throw new Error("v3 send: replacement connection has no ratchet state");const s=await o(t,n,r);return i?.aborted&&(s.messageKey.fill(0),s.pqContext?.rootKey.fill(0),Cd(i)),e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),{epc:t,messageKey:s.messageKey,header:s.header,pqContext:s.pqContext}},Iu=(e,t,n,r)=>"connected"===e.connectionState&&t.some(t=>t===e&&t.roomId===n&&t.withPeerId===r);class Su extends AggregateError{result;constructor(e,t){super(e.outcomes.filter(e=>"failed"===e.status).map(e=>e.reason),t),this.name="MessageDeliveryError",this.result=e}}const Cu=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f,p)=>{Cd(p),So(n,l,s),await io(mu(n,e.label),l),Cd(p);try{await Ad(Xi(n,l),p)}catch(e){throw new Error("v3 send: ratchet gate rejected",{cause:e})}if(!r.ratchetState)throw new Error("v3 send: no ratchet state for peer");let m,y,g;await vu(r,p);try{const e=await Oi(r,n,d);p?.aborted&&(e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),Cd(p)),m=e.messageKey,y=e.header,g=e.pqContext}catch(e){throw new Error("v3 send: durable ratchet advance failed",{cause:e})}let w=e,b=r;const v=async()=>{const r=e.label;if(!await pu(w,void 0,void 0,p))throw new Error("Message DataChannel did not open before send timeout");Cd(p),await gu(w,m,y,g,a,o,i,s,c,d,u,p,void 0,()=>vo(n,l,s));let v=0,k=0,I=!1;for(;v<5;){const e=await Co(n,l,s,2e3*(v+1),p);if(Cd(p),e){I=!0;break}if("closed"===w.readyState||"closing"===w.readyState){if(Iu(b,h,n,l))throw new Error("Message transfer cancelled by peer");if(k>=3)break;k++;const e=await wu(t,n,l,r,h,f,3e4,p);if(!e)break;const a=await ku({epc:b,messageKey:m,header:y},e.epc,n,d,Xi,Oi,p);b=a.epc,m=a.messageKey,y=a.header,g=a.pqContext??null,w=e.channel,v=0,t.dispatch(dt({roomId:n,sha512Hex:c,retransmit:!0}));continue}await gu(w,m,y,g,a,o,i,s,c,d,u,p,bo(n,l,s),()=>vo(n,l,s)),v++,t.dispatch(dt({roomId:n,sha512Hex:c,retransmit:!0}))}if(!I)throw new Error("Message transfer ended without receiver confirmation")};try{await(async(e,t)=>{try{return await t()}finally{bu(e())}})(()=>w,v)}finally{m.fill(0),g?.rootKey.fill(0),So(n,l,s)}},Au=(e,t,n,r,a,o,i,s,c,l)=>async d=>{const u=await eo(e,d);if(!u)return null;const h=new Uint8Array(u.metadata),f=Po(h),p=new Uint8Array(te);0===u.merkleProof.byteLength?p.set(await du(n,la(u.leafHash),l,te)):p.set(new Uint8Array(u.merkleProof));const m=u.receiptToken.length===2*N?u.receiptToken:ca(await _o(r,f.chunkIndex,la(u.leafHash)));0!==u.merkleProof.byteLength&&u.merkleRoot===a&&u.receiptToken===m||await ao({transferId:e,hash:t,merkleRoot:a,leafHash:u.leafHash,receiptToken:m,chunkIndex:d,data:u.data,metadata:u.metadata,merkleProof:p.buffer});const y=await ia([h,p,new Uint8Array(u.data)]);return Ii(o,i,y,r,c,s??void 0)},Eu=12e4,Pu=async(e,t,n,r,a,o,i,s,c,l=1,d=ne,u=.9,h=1)=>{const f=((e,t)=>{const n=[...md.get(e)??[]].find(e=>e.transferId===t);return n?{transferId:t,signal:n.controller.signal,bindHash(e){n.hashHex=e},bindMerkleRoot(e){n.merkleRootHex=e},finish(){n.finished||(n.finished=!0,yd(e,n))}}:vd(e,t)})(r,c);let p="",m=!1,y=!1;try{Cd(f.signal);const{rooms:c}=t.getState(),g=c.findIndex(e=>e.id===r);if(-1===g)throw new Error("No room with id "+r);if(g>-1){const w=c[g].channels.findIndex(e=>e.label===n);if(-1===w)throw new Error("No channel with label "+n);const{merkleRoot:b,merkleRootHex:v,hashHex:k,totalChunks:I,chunkHashes:S}=await fu(e,t,n,c[g],s,f,l,d,u,h);if(f.bindMerkleRoot(v),p=v,Cd(f.signal),0===b.length||0===k.length||0===I||0===S.length)return;m=!0;const C=await po(n,v),A=c[g].channels[w].peerIds.map(e=>({peerId:e,epc:a.find(t=>t.roomId===r&&t.withPeerId===e)})),E="scheduled"===c[g].policy.coverMode?await(async(e,t,n,r,a,o,i,s,c,l,d,u,h)=>{const f=[];let p=0;for(const m of n){if(u?.aborted){f.push({peerId:m.peerId,status:"skipped",reason:"cancelled"});continue}const n=m.epc;if(n&&"connected"===n.connectionState&&n.coverRuntime)try{if(await Ad(Xi(e,m.peerId),u),!n.ratchetState)throw new Error("v4 scheduled send: no ratchet state");await vu(n,u);const y=await Oi(n,e,l),g=await po(t,i),w=Au(s,c,a,o,i,y.messageKey,y.header,y.pqContext,l,d);if(!pd({epc:n,channelMessageLabel:g,totalChunks:r,sealSlotCell:w,getAckedChunks:()=>bo(e,m.peerId,s)}))throw new Error("v4 scheduled send: edge has no cover runtime");fd(n,e,m.peerId,i,s),p+=1,h?.();const b=await Co(e,m.peerId,s,Eu,u);y.messageKey.fill(0),y.pqContext?.rootKey.fill(0),f.push(b?{peerId:m.peerId,status:"delivered"}:{peerId:m.peerId,status:"failed",phase:"transfer",reason:new Error("scheduled delivery not confirmed")})}catch(e){f.push({peerId:m.peerId,status:"failed",phase:"transfer",reason:e})}else f.push({peerId:m.peerId,status:"skipped",reason:"not-connected"})}return{outcomes:f,startedTransfers:p}})(r,n,A,I,S,b,v,f.transferId,k,i,s,f.signal,()=>{y=!0}):await(async(e,t,n,r,a)=>{const o=[];let i=0;for(const s of e){if(r?.aborted){o.push({peerId:s.peerId,status:"skipped",reason:"cancelled"});continue}if(!s.epc||"connected"!==s.epc.connectionState){o.push({peerId:s.peerId,status:"skipped",reason:"not-connected"});continue}if(s.epc.withPeerPublicKey.length!==2*L){o.push({peerId:s.peerId,status:"skipped",reason:"unauthenticated"});continue}const e=s;let c;try{c=await t(e)}catch(e){o.push({peerId:s.peerId,status:"failed",phase:"setup",reason:e});continue}if(r?.aborted)bu(c),o.push({peerId:s.peerId,status:"skipped",reason:"cancelled"});else{i++,a?.();try{const t=n(e,c);o.push(Promise.resolve(t).then(()=>({peerId:s.peerId,status:"delivered"}),e=>({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})))}catch(e){bu(c),o.push({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})}}}return{outcomes:await Promise.all(o),startedTransfers:i}})(A,({epc:e})=>Ld({channel:C,epc:e,roomId:r,dataChannels:o},t),({peerId:e,epc:n},c)=>Cu(c,t,r,n,I,S,b,f.transferId,k,e,i,s,a,o,f.signal),f.signal,()=>{y=!0}),P={transferId:f.transferId,merkleRootHex:v,...E};Cd(f.signal);const x=P.outcomes.filter(e=>"delivered"===e.status).length;if(0===P.startedTransfers)throw new Su(P,"No authenticated connected peers accepted the send");if(0===x)throw new Su(P,"Message was not delivered to any peer");return P}return}catch(e){if(((e,t,n)=>n||!e&&!t)(m,y,f.signal.aborted)&&(p.length>0&&await ro(p),t.dispatch(ft({roomId:r,transferId:f.transferId}))),f.signal.aborted)throw f.signal.reason instanceof Error?f.signal.reason:new Error("Message transfer cancelled");throw console.trace(e),e}finally{await oo({transferId:f.transferId}),f.finish()}},xu=async({alsoDeleteDB:e,peerConnections:t,dataChannels:n},r)=>{for(let e=n.length-1;e>=0;e--){const t=n[e];t.releaseProtocolResources?.(),t.onopen=null,t.onclose=null,t.onerror=null,t.onclosing=null,t.onmessage=null,t.onbufferedamountlow=null,"closed"!==t.readyState&&t.close(),n.splice(e,1)}const a=[...new Set(t.map(e=>e.withPeerId))];for(const e of a)await r.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:e}));return e&&await Wa("deleteDB"),{data:void 0}},Ku=async({roomId:e,deleteMessages:t,peerConnections:n,dataChannels:r},a)=>{for(let t=r.length-1;t>=0;t--){const n=r[t];n.roomIds.includes(e)&&(n.releaseProtocolResources?.(),n.onopen=null,n.onclose=null,n.onerror=null,n.onclosing=null,n.onmessage=null,n.onbufferedamountlow=null,"closed"!==n.readyState&&n.close(),r.splice(t,1))}const o=n.filter(t=>t.roomId===e).map(e=>e.withPeerId);for(const t of o)await a.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:e})),a.dispatch(ut({peerId:t,roomId:e}));if(t){if((await Ja()).findIndex(t=>t.roomId===e)>-1){await(e=>Wa("deleteDBUniqueRoom",e))(e);const t=await Za(e),n=t.length;for(let r=0;r<n;r++)a.dispatch(ft({roomId:e,merkleRootHex:t[r].merkleRoot}))}}return{data:void 0}},Ru=async(e,t=5e3,n=25)=>{if("open"!==e.readyState){try{e.close()}catch{}return}const r=Date.now();for(;"open"===e.readyState&&e.bufferedAmount>0&&Date.now()-r<t;)await new Promise(e=>setTimeout(e,n));try{"open"===e.readyState&&e.close()}catch{}},Mu=[],_u=[],Uu=[],Du=na({reducerPath:"webrtcApi",baseQuery:async({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:a,dataChannels:o},i)=>Yd(n,e).runExclusive(async()=>{const{keyPair:s}=i.getState();if(e===s.peerId)throw new Error("Cannot create a connection with oneself.");const c=Fa(s.publicKey,t);if(await Ga(e))return{data:void 0};const l=$d(a,n,e);if(l>-1){const e=a[l];if("closed"!==e.connectionState&&"failed"!==e.connectionState)return!c||e.mainChannel&&"closing"!==e.mainChannel.readyState&&"closed"!==e.mainChannel.readyState||await tu(e,o,i),{data:void 0};hd(e),(e=>{e.ontrack=null,e.ondatachannel=null,e.onicecandidate=null,e.onicecandidateerror=null,e.onnegotiationneeded=null,e.onsignalingstatechange=null,e.onconnectionstatechange=null,e.onicegatheringstatechange=null,e.oniceconnectionstatechange=null})(e),"closed"!==e.connectionState&&e.close(),a.splice(l,1)}const d=await eu({peerId:e,peerPublicKey:t,roomId:n,peerConnections:a,rtcConfig:r},i);return((e,t,n)=>{e.ondatachannel=async r=>{try{const a=await Ld({channel:r.channel,epc:e,roomId:e.roomId,dataChannels:t,incoming:!0},n);"main"===a.label&&(e.mainChannel=a)}catch(e){console.error("Rejected incoming DataChannel:",e)}}})(d,o,i),a.includes(d)||a.push(d),c&&await tu(d,o,i),{data:void 0}}),endpoints:e=>({connectWithPeer:e.mutation({query:({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceCandidatePoolSize:2}})=>({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:Mu,dataChannels:Uu})}),setDescription:e.mutation({queryFn:(e,t,n)=>ru({...e,peerConnections:Mu,iceCandidates:_u,dataChannels:Uu},t)}),setCandidate:e.mutation({queryFn:(e,t,n)=>(async({peerId:e,roomId:t,candidate:n,peerConnections:r,iceCandidates:a},o)=>Yd(t,e).runExclusive(async()=>{const{keyPair:i}=o.getState(),s=(e=>{if("function"==typeof e.toJSON)return e.toJSON();const t=e;return{candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,usernameFragment:t.usernameFragment}})(n),c=$d(r,t,e);if(c>-1){const e=r[c];if(e.ignoreOffer)return{data:void 0};if(e.remoteDescription&&"stable"===e.signalingState){if(jd(s,e.remoteDescription))try{await e.addIceCandidate(s)}catch{const t=e.makingOffer||"stable"!==e.signalingState;!(i.peerId<e.withPeerId)&&t||await Hd(e,async()=>{e.iceCandidates.length=0,await o.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:e.withPeerId,roomId:e.roomId}))})}}else((e,t)=>{for(;e.length>=64;)e.shift();e.push(t)})(e.iceCandidates,s)}else((e,t,n,r)=>{let a=0;for(let r=e.length-1;r>=0;r--)if(e[r].roomId===t&&e[r].withPeerId===n&&(a+=1,a>=64)){e.splice(r,1);break}for(;e.length>=1024;)e.shift();e.push({...r,roomId:t,withPeerId:n})})(a,t,e,s);return{data:void 0}}))({...e,peerConnections:Mu,iceCandidates:_u},t)}),openChannel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,channel:t,withPeers:n,peerConnections:r,dataChannels:a},o)=>{const{keyPair:i}=o.getState(),s=async e=>{if("string"!=typeof t){const n=await Ld({channel:t,epc:e,roomId:e.roomId,dataChannels:a},o);return void("main"===n.label&&(e.mainChannel=n))}if(a.find(n=>n.withPeerId===e.withPeerId&&n.roomIds.includes(e.roomId)&&n.label===t&&"closing"!==n.readyState&&"closed"!==n.readyState))return;if("main"===t&&!Fa(i.publicKey,e.withPeerPublicKey))return;const n=e.createDataChannel(t,{ordered:"main"===t,protocol:"raw"}),r=await Ld({channel:n,epc:e,roomId:e.roomId,dataChannels:a},o);"main"===r.label&&(e.mainChannel=r)};if(n&&n.length>0){const t=n.length;for(let a=0;a<t;a++){if(i.peerId===n[a].peerId)continue;const t=Vd(r,e,n[a].peerId);t&&await s(t)}}else{const t=r.filter(t=>t.roomId===e),n=t.length;for(let e=0;e<n;e++){const n=t[e];await s(n)}}return{data:void 0}})({...e,peerConnections:Mu,dataChannels:Uu},t)}),sendMessage:e.mutation({queryFn:(e,t,n)=>(async({data:e,transferId:t,label:n,roomId:r,peerConnections:a,dataChannels:o,minChunks:i,chunkSize:s,percentageFilledChunk:c,metadataSchemaVersion:l},d)=>{const u=i??1,h=s??ne,f=c??.9,p="string"==typeof e?(new TextEncoder).encode(e).length:e.size,m=hu(p,u,h,f),y=await Ua(ya()),g=await Ua(wa(m));try{return{data:await async function(){return await Pu(e,d,n,r,a,o,y,g,t,u,h,f,l)}()}}catch(e){if(e instanceof Su)return{error:e};throw e}})({...e,peerConnections:Mu,dataChannels:Uu},t)}),disconnect:e.mutation({queryFn:(e,t,n)=>xu({...e,peerConnections:Mu,dataChannels:Uu},t)}),disconnectFromRoom:e.mutation({queryFn:(e,t,n)=>Ku({...e,peerConnections:Mu,dataChannels:Uu},t)}),disconnectFromAllRooms:e.mutation({queryFn:(e,t,n)=>(async({deleteMessages:e,exceptionRoomIds:t,peerConnections:n,dataChannels:r},a)=>{const o=new Set(t??[]);for(let e=r.length-1;e>=0;e--){const t=r[e];t.roomIds.some(e=>o.has(e))||(t.releaseProtocolResources?.(),t.onopen=null,t.onclose=null,t.onerror=null,t.onclosing=null,t.onmessage=null,t.onbufferedamountlow=null,"closed"!==t.readyState&&t.close(),r.splice(e,1))}const i=n.filter(e=>!o.has(e.roomId)).map(e=>({roomId:e.roomId,peerId:e.withPeerId}));for(const e of i)await a.dispatch(Du.endpoints.disconnectFromPeer.initiate(e)),a.dispatch(ut(e));if(e){const{rooms:e}=a.getState(),n=e.length;for(let r=0;r<n;r++){if(t?.includes(e[r].id))continue;const n=e[r].messages.length;for(let t=0;t<n;t++)a.dispatch(ft({roomId:e[r].id,merkleRootHex:e[r].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:Mu,dataChannels:Uu},t)}),disconnectFromPeer:e.mutation({queryFn:(e,t,n)=>(({peerId:e,roomId:t,alsoDeleteData:n,peerConnections:r,dataChannels:a,iceCandidates:o},i)=>{const s=new Set;for(let n=r.length-1;n>=0;n--){const a=r[n];if(a.withPeerId!==e||void 0!==t&&a.roomId!==t)continue;s.add(a.roomId);const o=new Error(`Room/peer transport closed (${a.roomId}, ${a.withPeerId})`);if(xl(a.roomId,a.withPeerId,o),Yi(a.roomId,a.withPeerId,o),a.ratchetState&&(ti(a.ratchetState),a.ratchetState=void 0),hd(a),os(a),Ol(a),a.pqHealingState&&(a.pqHealingState.destroy(),a.pqHealingState=void 0),a.serializeEdgeCryptoState=void 0,a.messageKeyCache){for(const e of a.messageKeyCache.values())e.fill(0);a.messageKeyCache.clear(),a.messageKeyCache=void 0}a.messageKeyByMerkleRoot?.clear(),a.messageKeyByMerkleRoot=void 0,a.messageChannels?.clear(),a.messageChannels=void 0,a.mainChannel=void 0,a.ontrack=null,a.ondatachannel=null,a.onicecandidate=null,a.onicecandidateerror=null,a.onnegotiationneeded=null,a.onsignalingstatechange=null,a.onconnectionstatechange=null,a.onicegatheringstatechange=null,a.oniceconnectionstatechange=null,"closed"!==a.connectionState&&a.close(),r.splice(n,1)}void 0!==t&&s.add(t);for(const t of s)nu(o,t,e),Zd(t,e);i.dispatch(ut({peerId:e,roomId:t})),i.dispatch(ht({peerId:e,roomId:t}));for(let n=a.length-1;n>=0;n--){const r=a[n];r.withPeerId!==e||void 0!==t&&!r.roomIds.includes(t)||(r.releaseProtocolResources?.(),r.onopen=null,r.onclose=null,r.onerror=null,r.onclosing=null,r.onmessage=null,r.onbufferedamountlow=null,"closed"!==r.readyState&&r.close(),a.splice(n,1))}if(n){const{rooms:n}=i.getState(),r=n.length;for(let a=0;a<r;a++){if(void 0!==t&&n[a].id!==t)continue;const r=n[a].messages.length;for(let t=0;t<r;t++)n[a].messages[t].fromPeerId===e&&i.dispatch(ft({roomId:n[a].id,merkleRootHex:n[a].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:Mu,dataChannels:Uu,iceCandidates:_u},t)}),disconnectFromChannelLabel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,label:t,messageHash:n,alsoDeleteData:r,alsoSendFinishedMessage:a,dataChannels:o},i)=>{const s=o.length;if(0===s)return{data:void 0};for(let c=0;c<s;c++){if(o[c]?.label!==t||!o[c].roomIds.includes(e)||"open"!==o[c].readyState)continue;const s=o[c];if(r&&s.cancelReceiveTransfer?await s.cancelReceiveTransfer():s.releaseProtocolResources?.(),n&&a&&n.length===N&&es(o[c],n),await Ru(o[c]),r){const{merkleRootHex:n}=await mo(t);i.dispatch(ft({roomId:e,merkleRootHex:n}))}}return{data:void 0}})({...e,dataChannels:Uu},t)}),disconnectFromPeerChannelLabel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,peerId:t,label:n,messageHash:r,alsoDeleteData:a,alsoSendFinishedMessage:o,channel:i,peerConnections:s,dataChannels:c},l)=>{const{rooms:d,signalingServer:u}=l.getState(),h=c.findIndex(r=>i?r===i:r.label===n&&r.withPeerId===t&&r.roomIds.includes(e));h>-1&&c[h]&&(a&&c[h].cancelReceiveTransfer?await c[h].cancelReceiveTransfer():c[h].releaseProtocolResources?.(),r&&o&&r.length===N&&es(c[h],r),c[h].onopen=null,c[h].onclose=null,c[h].onerror=null,c[h].onclosing=null,c[h].onmessage=null,c[h].onbufferedamountlow=null,"open"===c[h].readyState&&await Ru(c[h]),c.splice(h,1),await io(mu(e,n),t));const{merkleRootHex:f}=await mo(n);f.length>0?a&&l.dispatch(ft({roomId:e,merkleRootHex:f})):u.isConnected&&!a||l.dispatch(ht({roomId:e,peerId:t,label:n}));const p=d.find(t=>t.id===e);if(!p?.channels.some(e=>e.peerIds.includes(t))){const n=$d(s,e,t);n>-1&&await l.dispatch(Du.endpoints.disconnectFromPeer.initiate({peerId:s[n].withPeerId,roomId:e}))}return{data:void 0}})({...e,peerConnections:Mu,dataChannels:Uu},t)})})}),Tu=e=>"number"==typeof e&&Number.isInteger(e)&&4===e,Nu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),qu=(e,t)=>{const n=Object.keys(e);return n.length===t.length&&n.every(e=>t.includes(e))},Ou=new Map,Bu=async(n,r,a)=>{try{if("PING"===n.data)return void r.send("PONG");const c=String(n.data);if(c.length>524288)return void console.error("Rejecting oversized signaling message");const l=JSON.parse(c);switch(l.type){case"ping":{const{keyPair:e}=a.getState();await a.dispatch($u.endpoints.sendMessage.initiate({content:{type:"pong",fromPeerId:e.peerId}}));break}case"peerId":{if(!(Nu(s=l)&&qu(s,["type","peerId","challenge","protocolVersion","message"])&&"peerId"===s.type&&"string"==typeof s.peerId&&e(s.peerId)&&"string"==typeof s.challenge&&/^[0-9a-f]{64}$/.test(s.challenge)&&"number"==typeof s.protocolVersion&&Tu(s.protocolVersion)&&"string"==typeof s.message)){console.error("Rejecting malformed or incompatible auth challenge"),r.close(1002,"protocol-v4 auth required");break}const{keyPair:t}=a.getState();await(async(e,t,n,r)=>{const a=la(e.secretKey),o=n.match(/.{1,2}/g);if(!o)throw new Error("Invalid challenge format");const i=Uint8Array.from(o.map(e=>parseInt(e,16))),s=await Na(i,a),c=[...new Uint8Array(s)].map(e=>e.toString(16).padStart(2,"0")).join("");r.dispatch(M({peerId:t,challenge:n,signature:c}))})(t,l.peerId,l.challenge,a);break}case"roomId":{if(!Tu(l.protocolVersion)||!e(l.roomId)||!/^[0-9a-f]{64}$/.test(l.roomUrl)){console.error("Rejecting incompatible or malformed room response");break}let t;l.turnCredentials&&(t={...We,iceServers:[...We.iceServers??[],{urls:l.turnCredentials.urls,username:l.turnCredentials.username,credential:l.turnCredentials.credential}]}),a.dispatch(Je({id:l.roomId,url:l.roomUrl,rtcConfig:t}));break}case"challenge":if(!(t=>{if(!Nu(t))return!1;const n=Object.hasOwn(t,"username");return n===Object.hasOwn(t,"credential")&&qu(t,n?["type","challengeId","protocolVersion","username","credential"]:["type","challengeId","protocolVersion"])&&"challenge"===t.type&&"string"==typeof t.challengeId&&e(t.challengeId)&&"number"==typeof t.protocolVersion&&Tu(t.protocolVersion)&&(!n||"string"==typeof t.username&&t.username.length>0&&"string"==typeof t.credential&&t.credential.length>0)})(l)){console.error("Rejecting malformed or incompatible auth success"),r.close(1002,"protocol-v4 auth required");break}a.dispatch(_(l));break;case"peerConnection":{if(!Tu(l.protocolVersion)||!e(l.peer.id)||!Ba(l.peer.publicKey))break;if(await Ga(l.peer.id,l.peer.publicKey))break;const{keyPair:t,rooms:n}=a.getState(),r=n.findIndex(e=>e.id===l.roomId);if(r>-1&&n[r].onlyConnectWithKnownAddresses){if(!await Xa(l.peer.id,l.peer.publicKey))break}await a.dispatch($u.endpoints.sendMessage.initiate({content:{type:"peerConnection",roomId:l.roomId,fromPeerId:t.peerId,toPeerId:l.peer.id,protocolVersion:4}}));break}case"peers":{if(!Tu(l.protocolVersion)||!e(l.roomId)||!Array.isArray(l.peers)){console.error("Rejecting incompatible or malformed peer roster");break}St("[handleWebSocketMessage] Received peers response:",{roomId:l.roomId,peersCount:l.peers.length,peers:l.peers});const{keyPair:t,rooms:n}=a.getState(),r=n.findIndex(e=>e.id===l.roomId);if(r>-1){const o=((t,n,r)=>{const a=t.map(e=>({...e})),o=new Map(a.map(e=>[e.peerId,e])),i=new Map(a.map(e=>[e.peerPublicKey,e]));for(const t of n){if(!e(t.id)||!Ba(t.publicKey)||t.id===r.peerId||t.publicKey===r.publicKey)continue;if(o.has(t.id))continue;if(i.get(t.publicKey))continue;const n={peerId:t.id,peerPublicKey:t.publicKey};a.push(n),o.set(n.peerId,n),i.set(n.peerPublicKey,n)}return a})(n[r].peers,l.peers,t);for(const e of o)a.dispatch(rt({roomId:l.roomId,...e}));const i=l.peers.length;if(0===i){const{signalingServer:n}=a.getState(),r=Date.now(),o=Ou.get(l.roomId)??0;n.isConnected&&n.isVerified&&e(t.peerId)&&r-o>5e3&&(Ou.set(l.roomId,r),await a.dispatch($u.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:t.peerId,roomId:l.roomId,protocolVersion:4}})));break}const s=n[r].onlyConnectWithKnownAddresses;for(let c=0;c<i;c++){if(l.peers[c].publicKey===t.publicKey||l.peers[c].id===t.peerId||!e(l.peers[c].id)||!Ba(l.peers[c].publicKey))continue;if(!o.some(e=>e.peerId===l.peers[c].id&&e.peerPublicKey===l.peers[c].publicKey))continue;if(!await Ga(l.peers[c].id,l.peers[c].publicKey)){if(s){if(!await Xa(l.peers[c].id,l.peers[c].publicKey))continue}await a.dispatch(Du.endpoints.connectWithPeer.initiate({roomId:l.roomId,peerId:l.peers[c].id,peerPublicKey:l.peers[c].publicKey,rtcConfig:n[r].rtcConfig}))}}}break}case"description":if(!(Tu(l.protocolVersion)&&e(l.fromPeerId)&&Ba(l.fromPeerPublicKey)&&e(l.roomId)&&(i=l.description,("offer"===i.type||"answer"===i.type||"pranswer"===i.type||"rollback"===i.type)&&"string"==typeof i.sdp&&i.sdp.length<=262144))){Tu(l.protocolVersion)||console.error(`Rejecting SDP from ${l.fromPeerId}: incompatible protocol version ${String(l.protocolVersion)} (expected v4). No fallback.`);break}if(!await Ga(l.fromPeerId,l.fromPeerPublicKey)){const{rooms:e}=a.getState(),t=e.findIndex(e=>e.id===l.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses){if(!await Xa(l.fromPeerId,l.fromPeerPublicKey))break}await a.dispatch(Du.endpoints.setDescription.initiate({peerId:l.fromPeerId,peerPublicKey:l.fromPeerPublicKey,roomId:l.roomId,description:l.description,rtcConfig:e[t].rtcConfig}))}break;case"candidate":if(!(Tu(l.protocolVersion)&&e(l.fromPeerId)&&e(l.roomId)&&(e=>{const t=e;return"string"==typeof t.candidate&&t.candidate.length<=4096&&(null==t.sdpMid||"string"==typeof t.sdpMid&&t.sdpMid.length<=256)&&(null==t.usernameFragment||"string"==typeof t.usernameFragment&&t.usernameFragment.length<=256)})(l.candidate))){console.error(`Rejecting ICE from ${l.fromPeerId}: incompatible protocol version ${String(l.protocolVersion)} (expected v4). No fallback.`);break}if(!await Ga(l.fromPeerId)){const{rooms:e}=a.getState(),t=e.findIndex(e=>e.id===l.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses){if(!await Xa(l.fromPeerId))break}await a.dispatch(Du.endpoints.setCandidate.initiate({peerId:l.fromPeerId,roomId:l.roomId,candidate:l.candidate}))}break;case"connection":{const{keyPair:n,rooms:r}=a.getState(),i=r.findIndex(e=>e.id===l.roomId);if(Tu(l.protocolVersion)&&e(n.peerId)&&t(n.challenge)&&t(n.signature)&&128===n.signature.length&&64===n.challenge.length&&e(l.fromPeerId)&&Ba(l.fromPeerPublicKey)&&l.fromPeerId!==n.peerId&&l.fromPeerPublicKey!==n.publicKey&&e(l.roomId)&&i>-1&&(o=l.labels,Array.isArray(o)&&o.length<=64&&o.every(e=>"string"==typeof e&&e.length>0&&e.length<=193))){if(await Ga(l.fromPeerId,l.fromPeerPublicKey))break;if(r[i].onlyConnectWithKnownAddresses){if(!await Xa(l.fromPeerId,l.fromPeerPublicKey))break}await(async(e,t,n)=>{n.recordPeer({roomId:e.roomId,peerId:e.fromPeerId,peerPublicKey:e.fromPeerPublicKey});for(const t of e.labels)n.recordChannel({roomId:e.roomId,peerId:e.fromPeerId,label:t});await n.ensureConnection({roomId:e.roomId,peerId:e.fromPeerId,peerPublicKey:e.fromPeerPublicKey,rtcConfig:t})})(l,r[i].rtcConfig,{recordPeer:e=>{a.dispatch(rt(e))},recordChannel:e=>{a.dispatch(it(e)),St(`Connected with ${n.peerId} on websocket channel ${e.label}`)},ensureConnection:async e=>{await a.dispatch(Du.endpoints.connectWithPeer.initiate(e))}})}else Tu(l.protocolVersion)||console.error(`Rejecting peer ${l.fromPeerId}: incompatible protocol version ${String(l.protocolVersion)} (expected v4). No fallback.`);break}case"error":console.error(l);break;default:console.error("Unknown message type "+JSON.stringify(l))}}catch(e){return void console.error("[p2party] WebSocket message handling error:",e)}var o,i,s},Lu=(e,t,n=10,r=20)=>{let a=0;const o=setInterval(()=>{e.readyState===WebSocket.OPEN?(clearInterval(o),t()):(a+=1,St(`Waiting for connection... Attempt ${String(a)}`),a>=n&&(clearInterval(o),St("WebSocket failed to connect after multiple attempts, closing..."),e.removeEventListener("message",()=>{}),e.removeEventListener("open",()=>{}),e.removeEventListener("close",()=>{}),e.close()))},r)};let Fu=null;const zu=(e,t)=>(Fu&&(Fu.removeEventListener("message",()=>{}),Fu.removeEventListener("open",()=>{}),Fu.removeEventListener("close",()=>{}),Fu.close(),Fu=null,St("WebSocket manually disconnected")),t.dispatch(bt.disconnect()),{data:void 0}),ju=(n,r)=>{if(Fu?.readyState===WebSocket.OPEN){const{keyPair:a}=r.getState();return e(a.peerId)&&t(a.challenge)&&t(a.signature)&&128===a.signature.length&&64===a.challenge.length&&Lu(Fu,()=>{Fu?.send(JSON.stringify(n.content))}),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},Hu=({peerId:n,peerPublicKey:r,roomId:a},o)=>{if(Fu?.readyState===WebSocket.OPEN){const{keyPair:i}=o.getState();return e(i.peerId)&&t(i.challenge)&&t(i.signature)&&128===i.signature.length&&64===i.challenge.length&&Ba(r)&&(o.dispatch(rt({roomId:a,peerId:n,peerPublicKey:r})),o.dispatch(it({roomId:a,label:"main",peerId:n})),St(`Connected with ${i.peerId} on channel main`),Lu(Fu,()=>{Fu?.send(JSON.stringify({type:"connection",roomId:a,fromPeerId:i.peerId,toPeerId:n,labels:["main"],protocolVersion:4}))})),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},$u=na({reducerPath:"signalingServerApi",baseQuery:async({signalingServerUrl:e},t)=>{const{keyPair:n,signalingServer:r}=t.getState();if(Fu||r.isConnected||r.isEstablishingConnection)return St("WebSocket already connected"),{data:void 0};t.dispatch(bt.startConnecting(e));try{const r=e=>{const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t};let o=n.publicKey,i=n.secretKey;const s=await Wa("getIdentityEd25519"),c=s?ca(new Uint8Array(s.pub)):"",l=s?new Uint8Array(s.secret):void 0,d=l?ca(l):"";l?.fill(0);const u=/^[0-9a-f]{128}$/;if(Ba(o)&&u.test(i)){if(!s||c!==o||d!==i){const e=la(i);await ho({pub:r(la(o)),secret:r(e)}),e.fill(0)}}else{if(s)o=c,i=d;else{const e=localStorage.getItem("publicKey")??"",t=localStorage.getItem("secretKey")??"";if(Ba(e)&&u.test(t)){o=e,i=t;const n=la(i);await ho({pub:r(la(o)),secret:r(n)}),n.fill(0)}else{const e=await Ta();o=ca(e.publicKey),i=ca(e.secretKey),await ho({pub:r(e.publicKey),secret:r(e.secretKey)}),e.secretKey.fill(0)}}t.dispatch(K({publicKey:o,secretKey:i}))}La(o,"Self Ed25519 identity"),localStorage.removeItem("secretKey");const h=i.length>0?i:n.secretKey,f=o.length>0?o:n.publicKey;if(h.length>0&&f.length>0){const e=await lo();if(!(null!=e&&await il(new Uint8Array(e.pub),new Uint8Array(e.crossSig),la(f)))){const e=await Do(),t=await ol(e.publicKey,la(h));await(a={pub:r(e.publicKey),secret:r(e.secretKey),crossSig:r(t)},Wa("setIdentityX25519",a))}}const p=e+"?publickey="+o;return Fu=new WebSocket(p),Fu.binaryType="arraybuffer",await new Promise((e,n)=>{if(!Fu)return void n(new Error("WebSocket is null"));const r=Fu;try{r.onopen=()=>{St("WebSocket connected to:",p),t.dispatch(bt.connectionEstablished()),e({data:void 0})},r.onerror=e=>{console.error("WebSocket error:",e),Fu&&(Fu.removeEventListener("message",()=>{}),Fu.removeEventListener("open",()=>{}),Fu.removeEventListener("close",()=>{}),Fu.close(),Fu=null),t.dispatch(bt.disconnect()),n(new Error("WebSocket connection failed"))},r.onmessage=async e=>{await Bu(e,r,t)},r.onclose=()=>{Fu&&(Fu.removeEventListener("message",()=>{}),Fu.removeEventListener("open",()=>{}),Fu.removeEventListener("close",()=>{}),Fu.close(),Fu=null),t.dispatch(bt.disconnect()),St("WebSocket disconnected"),e({data:void 0})}}catch(e){n(e instanceof Error?e:new Error(String(e)))}return()=>{Fu&&(St("Cleaning up WebSocket connection..."),Fu.removeEventListener("message",()=>{}),Fu.removeEventListener("open",()=>{}),Fu.removeEventListener("close",()=>{}),Fu.close(),Fu=null)}})}catch(e){return Fu&&(Fu.removeEventListener("message",()=>{}),Fu.removeEventListener("open",()=>{}),Fu.removeEventListener("close",()=>{}),Fu.close(),Fu=null),t.dispatch(bt.disconnect()),console.error("Error during WebSocket setup:",e),{error:"WebSocket connection failed"}}var a},endpoints:e=>({connectWebSocket:e.mutation({query:e=>({signalingServerUrl:e})}),disconnectWebSocket:e.mutation({queryFn:zu}),sendMessage:e.mutation({queryFn:ju}),connectWithPeer:e.mutation({queryFn:Hu})})}),Vu=new Map,Qu=k();Qu.startListening({matcher:l(Ze,Je,ct,ft,pt),effect:async(t,n)=>{try{if(Ze.match(t)){const{roomId:r,connectingToPeers:a}=t.payload;if(St("[roomListenerMiddleware] setConnectingToPeers:",{roomId:r,connectingToPeers:a}),a){const{signalingServer:t,keyPair:a,rooms:o}=n.getState(),i=o.findIndex(e=>e.id===r);if(St("[roomListenerMiddleware] setConnectingToPeers check:",{isConnected:t.isConnected,peerId:a.peerId,isPeerIdUUID:e(a.peerId),roomIndex:i,roomId:i>-1?o[i].id:"N/A"}),t.isConnected&&t.isVerified&&e(a.peerId)&&i>-1&&e(o[i].id)){const e=Date.now();e-(Vu.get(r)??0)<2e3?St("[roomListenerMiddleware] Skipping peers request - debounced"):(Vu.set(r,e),St("[roomListenerMiddleware] Sending peers request from setConnectingToPeers"),await n.dispatch($u.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:a.peerId,roomId:r,protocolVersion:4}})))}n.dispatch(Ze({roomId:r,connectingToPeers:!1}))}}else if(Je.match(t)){const{signalingServer:i,keyPair:s,rooms:c}=n.getState(),{url:l,id:d,onlyConnectWithKnownPeers:u}=t.payload;if(St("[roomListenerMiddleware] setRoom:",{url:l,id:d,onlyConnectWithKnownPeers:u}),64===l.length&&null!=u&&localStorage.setItem(l+"-onlyConnectWithKnownPeers",String(u)),64===l.length&&e(d)){St("[roomListenerMiddleware] setRoom processed:",{url:l,id:d,isConnected:i.isConnected,peerId:s.peerId,roomsLen:c.length});const t=c.findIndex(e=>e.id===d);if(-1===t)return;const u=ze(c[t].policy).slice().buffer;await(r=l,a=d,o=u,Wa("setDBUniqueRoom",r,a,o));const h=await Za(d),f=h.length;for(let e=0;e<f;e++)n.dispatch(ct({roomId:h[e].roomId,transferId:h[e].transferId,merkleRootHex:h[e].merkleRoot,sha512Hex:h[e].hash,fromPeerId:h[e].fromPeerId,filename:h[e].filename,messageType:h[e].messageType,chunkSize:h[e].savedSize,totalSize:h[e].totalSize,channelLabel:h[e].channelLabel,timestamp:h[e].timestamp}));St("[roomListenerMiddleware] Checking peers request conditions:",{isConnected:i.isConnected,isPeerIdUUID:e(s.peerId),peerId:s.peerId,roomIndex:t,roomId:t>-1?c[t].id:"N/A"}),i.isConnected&&i.isVerified&&e(s.peerId)&&t>-1&&e(c[t].id)&&(St("[roomListenerMiddleware] Sending peers request for room:",c[t].id),await n.dispatch($u.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:s.peerId,roomId:c[t].id,protocolVersion:4}})))}}else if(ct.match(t)){const{roomId:e,merkleRootHex:r,sha512Hex:a,chunkSize:o,totalSize:i}=t.payload,{rooms:s,keyPair:c}=n.getOriginalState(),l=s.findIndex(t=>t.id===e);if(l>-1){const t=s[l].messages.findLastIndex(e=>e.merkleRootHex===r&&e.fromPeerId!==c.peerId&&e.savedSize+o===i);if(t>-1){const r=await po(s[l].messages[t].channelLabel,s[l].messages[t].merkleRootHex),o=la(a);await n.dispatch(Du.endpoints.disconnectFromChannelLabel.initiate({roomId:e,label:r,messageHash:o,alsoDeleteData:!1,alsoSendFinishedMessage:!0}))}}}else if(ft.match(t)){const{merkleRootHex:e,hashHex:n}=t.payload;if(!e&&!n)return;if(e&&e.length!==2*N)return;if(n&&n.length!==2*N)return;e?(await ro(e),await oo({merkleRootHex:e})):n&&await oo({hashHex:n})}else if(pt.match(t)){const e=t.payload;await n.dispatch(Du.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:!0}))}}catch(e){console.error("p2party: room listener effect failed",e)}var r,a,o}});const Wu=k();Wu.startListening({matcher:l(K,R,M,_,U),effect:async(n,r)=>{if(K.match(n)){const{publicKey:e,secretKey:t}=n.payload;64===e.length&&128===t.length&&(localStorage.setItem("publicKey",n.payload.publicKey),localStorage.removeItem("secretKey"))}else if(R.match(n)){const{peerId:a,challenge:o,signature:i,challengeId:s,username:c,credential:l}=n.payload;if(e(a)&&e(s)&&t(o)&&t(i)&&64===o.length&&128===i.length){r.dispatch(bt.connectionVerified()),localStorage.setItem("peerId",a),localStorage.setItem("challenge",o),localStorage.setItem("signature",i),localStorage.setItem("challengeId",s);const{keyPair:t,rooms:d,commonState:u}=r.getState(),h=64===u.currentRoomUrl.length?d.findIndex(e=>e.url===u.currentRoomUrl):-1;h>-1?(n.payload.username&&n.payload.credential&&r.dispatch(st({roomId:d[h].id,iceServers:[{urls:["turn:turn.p2party.com:3478?transport=udp","turn:turn.p2party.com:3478?transport=tcp","turns:turn.p2party.com:443?transport=tcp"],username:c,credential:l}]})),e(d[h].id)&&r.dispatch(Ze({roomId:d[h].id,connectingToPeers:!0}))):e(t.peerId)&&64===u.currentRoomUrl.length&&await r.dispatch($u.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:t.peerId,roomUrl:u.currentRoomUrl,protocolVersion:4}}))}}else if(M.match(n)){const{peerId:a,challenge:o,signature:i}=n.payload;e(a)&&t(o)&&t(i)&&64===o.length&&128===i.length&&(localStorage.setItem("peerId",a),localStorage.setItem("challenge",o),localStorage.setItem("signature",i),await r.dispatch($u.endpoints.sendMessage.initiate({content:{type:"challenge",fromPeerId:a,challenge:o,signature:i,protocolVersion:4}})))}else if(_.match(n)){const{challengeId:t}=n.payload;if(e(t)){r.dispatch(bt.connectionVerified()),localStorage.setItem("challengeId",t);const{keyPair:a,rooms:o,commonState:i}=r.getState(),s=64===i.currentRoomUrl.length?o.findIndex(e=>e.url===i.currentRoomUrl):-1;s>-1?(n.payload.username&&n.payload.credential&&r.dispatch(st({roomId:o[s].id,iceServers:[{urls:["turn:turn.p2party.com:3478?transport=udp","turn:turn.p2party.com:3478?transport=tcp","turns:turn.p2party.com:443?transport=tcp"],username:n.payload.username,credential:n.payload.credential}]})),e(o[s].id)?r.dispatch(Ze({roomId:o[s].id,connectingToPeers:!0})):e(a.peerId)&&64===i.currentRoomUrl.length&&await r.dispatch($u.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:a.peerId,roomUrl:i.currentRoomUrl,protocolVersion:4}}))):e(a.peerId)&&64===i.currentRoomUrl.length&&await r.dispatch($u.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:a.peerId,roomUrl:i.currentRoomUrl,protocolVersion:4}}))}}else U.match(n)&&(console.trace("[keyPairListenerMiddleware] resetIdentity dispatched"),localStorage.setItem("peerId",""),localStorage.setItem("challengeId",""),localStorage.setItem("publicKey",""),localStorage.removeItem("secretKey"),localStorage.setItem("challenge",""),localStorage.setItem("signature",""))}});const Xu=I({reducer:{commonState:E,keyPair:D,rooms:yt,signalingServer:vt,[$u.reducerPath]:$u.reducer,[Du.reducerPath]:Du.reducer},middleware:e=>e({serializableCheck:{ignoredPaths:[`${Du.reducerPath}.mutations`,`${Du.reducerPath}.queries`,`${$u.reducerPath}.mutations`,`${$u.reducerPath}.queries`],ignoredActionPaths:["payload","error","meta.arg.originalArgs","meta.baseQueryMeta"]}}).concat([$u.middleware,Du.middleware,Qu.middleware,Wu.middleware])}),Gu=Xu.dispatch,Ju=new Uint8Array([80,50,80,83,69,83,83,0]),Yu=262144,Zu=Ju.length+4+24+32+32+32+2,eh="p2party-session",th=e=>Uint8Array.from(e);function nh(e,t,n){if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(void 0!==n&&e.length!==n)throw new RangeError(`${t} must be ${String(n)} bytes`)}const rh=(e,t)=>{if(!Number.isSafeInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new RangeError(`${t} must be a non-negative safe integer`)},ah=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n},oh=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),ih=async e=>new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",e.slice().buffer)),sh=async e=>{const t=new WebAssembly.Memory({initial:32,maximum:32});return e?.wasmBinary?await Ca({wasmBinary:(n=e.wasmBinary,n instanceof Uint8Array?n.slice().buffer:n.slice(0)),wasmMemory:t,getRandomValue:Ea}):await Ua(t);var n},ch=async(e={})=>{const t=await sh(e);let n=null,r=null,a=null;try{if(e.ed25519KeyPair)nh(e.ed25519KeyPair.publicKey,"ed25519KeyPair.publicKey",L),nh(e.ed25519KeyPair.secretKey,"ed25519KeyPair.secretKey",F),n=th(e.ed25519KeyPair.publicKey),r=th(e.ed25519KeyPair.secretKey);else{const e=await Ta(t);n=e.publicKey,r=e.secretKey}const o=await Do(t);a=o.secretKey;const i=await ol(o.publicKey,r,t);if(!await il(o.publicKey,i,n,t))throw new Error("ed25519KeyPair public and secret keys do not match");const s={ed25519PublicKey:n,ed25519SecretKey:r,x25519PublicKey:o.publicKey,x25519SecretKey:a,x25519CrossSignature:i};return n=null,r=null,a=null,s}finally{n?.fill(0),r?.fill(0),a?.fill(0)}},lh=(e,t)=>e.N===t.N&&e.PN===t.PN&&ah(e.dhPub,t.dhPub);class dh{protocolVersion=4;#e;#ge=new Qd;#we;#be;#ve;#p=!1;constructor(e,t,n,r){this.#be=e,this.#e=t,this.#ve=n,this.#we=r}get pqMode(){return Ie(this.#be.rootSuite)}get canEncrypt(){return!this.#p&&null!==this.#be.sendingChainKey&&!this.#ve.trafficBlocked}get pqEpoch(){return this.#j(),this.#ve.epoch}get healingInProgress(){return!this.#p&&this.#ve.trafficBlocked}#j(){if(this.#p)throw new Error("session: session is destroyed")}async encrypt(e){nh(e,"plaintext");const t=th(e);return this.#ge.runExclusive(async()=>{let e=null,n=null,r=null,a=null,o=!1;try{if(this.#j(),this.#ve.trafficBlocked)throw new Error("session: sparse-PQ healing is in progress");if(!this.#be.sendingChainKey)throw new Error("ratchet: no sending chain");e=await(async(e,t)=>{const n=e.length,r=Math.max(1,Math.ceil(n/ne)),a=[],o=[];try{for(let t=0;t<r;t++){const r=t*ne,o=Math.min(ne,Math.max(0,n-r)),i=globalThis.crypto.getRandomValues(new Uint8Array(ne));i.set(e.subarray(r,r+o),0),a.push(i)}const i=await ih(e),s=new Uint8Array(r*N);for(let e=0;e<a.length;e++)s.set(su(a[e],t),e*N);const c=Uint8Array.from(await lu(s,t));for(let e=0;e<a.length;e++){const r=await du(s,su(a[e],t),t,te),c=Math.min(ne,Math.max(0,n-e*ne)),l=Eo({schemaVersion:1,messageType:xo.Unknown,hash:i,totalSize:n,date:new Date(0),name:eh,chunkStartIndex:0,chunkEndIndex:c,chunkIndex:e}),d=new Uint8Array(ae);d.set(l,0),d.set(r,ee),d.set(a[e],ee+te),o.push(d)}return i.fill(0),s.fill(0),{root:c,chunks:a,plaintexts:o}}catch(e){for(const e of a)e.fill(0);for(const e of o)e.fill(0);throw e}})(t,this.#e),n=ei(this.#be);const i=Vo(n,this.#e);r=i.messageKey,a=this.#ve.currentMessageContext();const s=e.plaintexts.map(t=>Ii(r,i.header,t,e.root,this.#e,a));return ni(this.#be,n),this.#ve.noteApplicationMessage(),o=!0,{protocolVersion:4,root:th(e.root),frames:s}}finally{t.fill(0),r?.fill(0),n&&!o&&ti(n),e&&(e=>{for(const t of e.chunks)t.fill(0);for(const t of e.plaintexts)t.fill(0)})(e)}})}async decrypt(e){if(!e||"object"!=typeof e)throw new TypeError("message is required");if(4!==e.protocolVersion)throw new Error("session: unsupported protocol version");if(nh(e.root,"message.root",N),!Array.isArray(e.frames)||0===e.frames.length)throw new Error("session: encrypted message has no frames");for(const t of e.frames)if(nh(t,"message frame"),t.length!==de)throw new Error("session: invalid encrypted frame length");const t=th(e.root),n=e.frames.map(th);return this.#ge.runExclusive(async()=>{this.#j();const e=n.map(e=>si(e));for(let t=1;t<e.length;t++)if(!lh(e[0].header,e[t].header))throw new Error("session: mixed ratchet headers");const r=new Set;for(const t of e){const e=oh(t.nonce);if(r.has(e))throw new Error("session: duplicate chunk nonce");r.add(e)}const a=ei(this.#be),o=new Map(this.#ve.activeReceiveKeys),i=[];let s=!1;try{const e=[];for(const r of n){const n=Si(a,r,o,t,this.#e,e=>this.#ve.resolveMessageContext(e));if(!n.ok||!n.decrypted)throw new Error("session: encrypted frame authentication failed");i.push(n.decrypted);const s=Po(n.decrypted.subarray(0,ee));e.push({metadata:s,chunk:n.decrypted.subarray(ee+te)})}const r=await(async e=>{if(0===e.length)throw new Error("session: encrypted message has no frames");const t=e[0].metadata;rh(t.totalSize,"metadata.totalSize");const n=Math.max(1,Math.ceil(t.totalSize/ne));if(e.length!==n)throw new Error("session: incomplete or excessive frame set");const r=new Map;for(const a of e){const e=a.metadata;if(rh(e.chunkIndex,"metadata.chunkIndex"),rh(e.chunkStartIndex,"metadata.chunkStartIndex"),rh(e.chunkEndIndex,"metadata.chunkEndIndex"),rh(e.totalSize,"metadata.totalSize"),1!==e.schemaVersion||e.messageType!==xo.Unknown||e.name!==eh||0!==e.date.getTime())throw new Error("session: unsupported encrypted metadata");if(e.totalSize!==t.totalSize||!ah(e.hash,t.hash))throw new Error("session: inconsistent encrypted metadata");if(e.chunkIndex>=n||0!==e.chunkStartIndex)throw new Error("session: invalid encrypted chunk range");const o=Math.min(ne,Math.max(0,t.totalSize-e.chunkIndex*ne));if(e.chunkEndIndex!==o)throw new Error("session: invalid encrypted chunk length");if(r.has(e.chunkIndex))throw new Error("session: duplicate encrypted chunk");r.set(e.chunkIndex,a)}const a=new Uint8Array(t.totalSize);for(let e=0;e<n;e++){const t=r.get(e);if(!t)throw new Error("session: missing encrypted chunk");const n=t.metadata.chunkEndIndex;a.set(t.chunk.subarray(0,n),e*ne)}const o=await ih(a),i=ah(o,t.hash);if(o.fill(0),!i)throw a.fill(0),new Error("session: plaintext hash mismatch");return a})(e);return ni(this.#be,a),this.#ke(o),this.#ve.noteApplicationMessage(),s=!0,r}finally{t.fill(0);for(const e of i)e.fill(0);if(!s){for(const[e,t]of o)this.#ve.activeReceiveKeys.has(e)||t.fill(0);ti(a)}}})}#ke(e){const t=this.#ve.activeReceiveKeys;for(const[n,r]of e)t.has(n)||t.set(n,r)}async prepareHealing(){return this.#ge.runExclusive(async()=>{if(this.#j(),!this.#ve.healingDue())return uh;const e=await this.#ve.prepareHealingOffer();return this.#ve.markPendingDispatched(),{frame:e,requiresPersistBeforeSend:!0}})}async acceptControlFrame(e){nh(e,"control frame",de);const t=th(e);return this.#ge.runExclusive(async()=>{this.#j();const e=await this.#ve.acceptControlFrame(t);return e.changed&&e.dispatch&&null!==this.#ve.pendingRetryAt&&this.#ve.markPendingDispatched(),{frame:e.dispatch,requiresPersistBeforeSend:e.changed}})}async pendingControl(){return this.#ge.runExclusive(async()=>(this.#j(),this.#ve.copyPendingFrame()))}async serialize(){return this.#ge.runExclusive(async()=>(this.#j(),fh(this.#be,this.#ve,this.#we)))}async destroy(){await this.#ge.runExclusive(async()=>{this.#p||(ti(this.#be),this.#ve.destroy(),this.#p=!0)})}}const uh={frame:null,requiresPersistBeforeSend:!1},hh=(e,t,n)=>(rh(n,"snapshot counter"),e.setBigUint64(t,BigInt(n),!1),t+8),fh=(e,t,n)=>{(e=>{if(nh(e.rootKey,"snapshot.rootKey",32),nh(e.dhSelfPub,"snapshot.dhSelfPub",32),nh(e.dhSelfSec,"snapshot.dhSelfSec",32),e.sendingChainKey&&nh(e.sendingChainKey,"snapshot.sendingChainKey",32),e.receivingChainKey&&nh(e.receivingChainKey,"snapshot.receivingChainKey",32),e.dhRemotePub&&nh(e.dhRemotePub,"snapshot.dhRemotePub",32),rh(e.Ns,"snapshot.Ns"),rh(e.Nr,"snapshot.Nr"),rh(e.PN,"snapshot.PN"),(e.sendingChainKey||e.receivingChainKey||e.skipped.size>0)&&!e.dhRemotePub)throw new Error("snapshot: chain state requires a remote DH key");if(e.skipped.size>ge)throw new Error("snapshot: too many skipped message keys")})(e);const r=Yo(e),a=t.serialize();if(0===a.length||a.length>Yu)throw a.fill(0),new Error("snapshot: PQ checkpoint length is invalid");try{const e=(r.sendingChainKey?1:0)|(r.receivingChainKey?2:0)|(r.dhRemotePub?4:0)|(n?8:0),t=Number(Boolean(r.sendingChainKey))+Number(Boolean(r.receivingChainKey))+Number(Boolean(r.dhRemotePub)),o=new Uint8Array(Zu+32*t+72*r.skippedMessageKeys.length+4+a.length),i=new DataView(o.buffer);let s=0;o.set(Ju,s),s+=Ju.length,o[s++]=4,o[s++]=4,o[s++]=e,o[s++]=(e=>{if(e===fe)return 3;if(e===he)return 4;if(e===pe)return 5;throw new Error("snapshot: unsupported root suite")})(r.rootSuite),s=hh(i,s,r.Ns),s=hh(i,s,r.Nr),s=hh(i,s,r.PN),o.set(new Uint8Array(r.rootKey),s),s+=32,r.sendingChainKey&&(o.set(new Uint8Array(r.sendingChainKey),s),s+=32),r.receivingChainKey&&(o.set(new Uint8Array(r.receivingChainKey),s),s+=32),o.set(new Uint8Array(r.dhSelfPub),s),s+=32,o.set(new Uint8Array(r.dhSelfSec),s),s+=32,r.dhRemotePub&&(o.set(new Uint8Array(r.dhRemotePub),s),s+=32),i.setUint16(s,r.skippedMessageKeys.length,!1),s+=2;for(const e of r.skippedMessageKeys)nh(new Uint8Array(e.dhPub),"snapshot.skipped.dhPub",32),nh(new Uint8Array(e.messageKey),"snapshot.skipped.messageKey",32),o.set(new Uint8Array(e.dhPub),s),s+=32,s=hh(i,s,e.n),o.set(new Uint8Array(e.messageKey),s),s+=32;return i.setUint32(s,a.length,!1),s+=4,o.set(a,s),s+=a.length,o}finally{a.fill(0),new Uint8Array(r.rootKey).fill(0),r.sendingChainKey&&new Uint8Array(r.sendingChainKey).fill(0),r.receivingChainKey&&new Uint8Array(r.receivingChainKey).fill(0),new Uint8Array(r.dhSelfSec).fill(0);for(const e of r.skippedMessageKeys)new Uint8Array(e.messageKey).fill(0)}},ph=e=>{nh(e,"snapshot");const t=th(e);let n=0,r=!1;const a=[],o=e=>{if(!Number.isSafeInteger(e)||e<0||n+e>t.length)throw new Error("snapshot: truncated input");const r=t.subarray(n,n+e);return n+=e,r},i=(e,t=!1)=>{const n=o(e).slice().buffer;return t&&a.push(new Uint8Array(n)),n},s=()=>{if(n+8>t.length)throw new Error("snapshot: truncated counter");const e=new DataView(t.buffer,t.byteOffset+n,8).getBigUint64(0,!1);if(n+=8,e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("snapshot: counter exceeds safe-integer range");return Number(e)};try{if(!ah(o(Ju.length),Ju))throw new Error("snapshot: invalid magic");if(4!==o(1)[0])throw new Error("snapshot: unsupported snapshot version");if(4!==o(1)[0])throw new Error("snapshot: unsupported protocol version");const e=o(1)[0];if(-16&e)throw new Error("snapshot: unknown flags");const c=(e=>{if(3===e)return fe;if(4===e)return he;if(5===e)return pe;throw new Error("snapshot: unsupported root suite")})(o(1)[0]),l=s(),d=s(),u=s(),h=i(32,!0),f=1&e?i(32,!0):null,p=2&e?i(32,!0):null,m=i(32),y=i(32,!0),g=4&e?i(32):null;if((f||p)&&null===g)throw new Error("snapshot: chain state requires a remote DH key");if(n+2>t.length)throw new Error("snapshot: missing skipped-key count");const w=new DataView(t.buffer,t.byteOffset+n,2).getUint16(0,!1);if(n+=2,w>ge)throw new Error("snapshot: too many skipped message keys");if(null===g&&w>0)throw new Error("snapshot: skipped keys require a remote DH key");const b=72*w;if(t.length-n<b+4)throw new Error("snapshot: truncated input");const v=[],k=new Set;for(let e=0;e<w;e++){const e=o(32),t=s(),n=o(32),r=`${oh(e)}:${String(t)}`;if(k.has(r))throw new Error("snapshot: duplicate skipped message key");k.add(r),v.push({dhPub:e.slice().buffer,n:t,messageKey:(()=>{const e=n.slice().buffer;return a.push(new Uint8Array(e)),e})()})}const I=new DataView(t.buffer,t.byteOffset+n,4).getUint32(0,!1);if(n+=4,0===I||I>Yu)throw new Error("snapshot: PQ checkpoint length is invalid");if(t.length-n!==I)throw new Error("snapshot: truncated input or trailing bytes");const S=o(I).slice();a.push(S);const C=Zo({rootSuite:c,rootKey:h,sendingChainKey:f,receivingChainKey:p,dhSelfPub:m,dhSelfSec:y,dhRemotePub:g,Ns:l,Nr:d,PN:u,skippedMessageKeys:v});return r=!0,{state:C,pqCheckpoint:S,amInitiator:!!(8&e)}}finally{if(t.fill(0),!r)for(const e of a)e.fill(0)}},mh=async e=>{if(!e||"object"!=typeof e)throw new TypeError("session options are required");if("initiator"!==e.role&&"responder"!==e.role)throw new Error("role must be initiator or responder");if(!e.transport||"function"!=typeof e.transport.send||"function"!=typeof e.transport.recv)throw new TypeError("transport must provide send() and recv()");if((e=>{if(!e||"object"!=typeof e)throw new TypeError("identity is required");nh(e.ed25519PublicKey,"identity.ed25519PublicKey",L),nh(e.x25519PublicKey,"identity.x25519PublicKey",X),nh(e.x25519SecretKey,"identity.x25519SecretKey",G),nh(e.x25519CrossSignature,"identity.x25519CrossSignature",O)})(e.identity),nh(e.peerIdentityEd25519PublicKey,"peerIdentityEd25519PublicKey",L),!e.channel||"object"!=typeof e.channel)throw new TypeError("channel binding is required");if(nh(e.channel.channelId,"channel.channelId"),0===e.channel.channelId.length)throw new RangeError("channel.channelId must not be empty");nh(e.channel.localFingerprint,"channel.localFingerprint",32),nh(e.channel.remoteFingerprint,"channel.remoteFingerprint",32);const t=e;if("pin"!==t.mode&&"nopin"!==t.mode)throw new Error("mode must be pin or nopin");const n=t.mode,r=t.pqMode??"hybrid-mlkem768";if("hybrid-mlkem512"!==r&&"hybrid-mlkem768"!==r&&"hybrid-mlkem1024"!==r)throw new Error("pqMode must select ML-KEM-512, ML-KEM-768, or ML-KEM-1024");let a=null;if("pin"===n){if(nh(t.pin,"pin"),0===t.pin.length)throw new RangeError("pin must not be empty");a=th(t.pin)}else if(void 0!==t.pin)throw new Error("pin must not be provided in nopin mode");const o=th(e.identity.x25519SecretKey),i=th(e.identity.ed25519PublicKey),s=th(e.identity.x25519PublicKey),c=th(e.identity.x25519CrossSignature),l=th(e.peerIdentityEd25519PublicKey),d=th(e.channel.channelId),u=th(e.channel.localFingerprint),h=th(e.channel.remoteFingerprint);let f=null,p=null,m=null,y=null,g=null;try{const t=await sh(e.crypto);await(async(e,t)=>{const n=new Uint8Array(X);n[0]=9;const r=To(e.x25519SecretKey,n,t);try{if(!ah(r,e.x25519PublicKey))throw new Error("identity X25519 public and secret keys do not match")}finally{r.fill(0)}if(!await il(e.x25519PublicKey,e.x25519CrossSignature,e.ed25519PublicKey,t))throw new Error("identity X25519 cross-signature is invalid")})({ed25519PublicKey:i,x25519PublicKey:s,x25519SecretKey:o,x25519CrossSignature:c},t);const w="initiator"===e.role,b=sl({channelId:d,ikInitiator:w?i:l,ikResponder:w?l:i,fpInitiator:w?u:h,fpResponder:w?h:u,pqMode:r}),v=await Il(e.transport,{mode:n,pqMode:r,pin:a,channelInput:b,amInitiator:w,idSelfSec:o,selfIdentityX25519Pub:s,selfIdentityCrossSignature:c,peerIdentityEd25519Pub:l},t);y=v.state,f=v.secret,p=v.pqHealing.rootKey,m=v.pqHealing.binding,g=new Vc({module:t,pqMode:r,rootSuite:y.rootSuite,binding:m,rootKey:p,nextOfferer:v.pqHealing.nextOfferer,amInitiator:w});const k=new dh(y,t,g,w);return y=null,g=null,k}finally{o.fill(0),a?.fill(0),f?.fill(0),p?.fill(0),m?.fill(0),y&&ti(y),g?.destroy()}},yh=async(e,t)=>{const n=ph(e);let r=null;try{const e=await sh(t),a=Vc.readCheckpointBinding(n.pqCheckpoint);try{r=Vc.restore(n.pqCheckpoint,{module:e,pqMode:Ie(n.state.rootSuite),rootSuite:n.state.rootSuite,binding:a,amInitiator:n.amInitiator})}finally{a.fill(0)}const o=new dh(n.state,e,r,n.amInitiator);return r=null,o}catch(e){throw ti(n.state),r?.destroy(),e}finally{n.pqCheckpoint.fill(0)}};var gh=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];const wh=e=>e.normalize("NFKD"),bh=async e=>{try{return await(async e=>{const t=wh(e).split(" ");if(t.length%3!=0)throw new Error("Number of words in mnemonic must be multiple of three.");const n=t.map(e=>{const t=gh.indexOf(e);if(-1===t)throw new Error("Could not find word in wordlist.");return t.toString(2).padStart(11,"0")}).join(""),r=32*Math.floor(n.length/33),a=n.slice(0,r),o=n.slice(r),i=a.match(/(.{1,8})/g).map(e=>parseInt(e,2));if(i.length<16)throw new Error("Entropy length too small (less than 128 bits).");if(i.length>64)throw new Error("Entropy length too large (more than 512 bits).");const s=i.length/4,c=Uint8Array.from(i),l=await window.crypto.subtle.digest("SHA-512",c);if(new Uint8Array(l).reduce((e,t)=>e+t.toString(2).padStart(8,"0"),"").slice(0,s)!==o)throw new Error("Invalid checksum.");return!0})(e)}catch{return!1}},vh=32,kh=`v${String(1)}.`,Ih="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Sh=/^[0-9a-fA-F]{64}$/u,Ch=/^[A-Za-z0-9_-]{43}$/u,Ah=(new TextEncoder).encode("p2party/room-invite/checksum/v1\0");if(2048!==gh.length||2048!==new Set(gh).size)throw new Error("Room invite word list must contain 2,048 unique words");const Eh=new Map(gh.map((e,t)=>[e,t])),Ph=e=>{if(!(e instanceof Uint8Array))throw new TypeError("Room capability must be a Uint8Array");if(e.length!==vh)throw new Error("Room capability must be exactly 32 bytes");return e},xh=()=>globalThis.crypto.getRandomValues(new Uint8Array(vh)),Kh=e=>{const t=Ph(e);let n="";for(let e=0;e<t.length;e+=3){const r=t.length-e,a=t[e]<<16|(r>1?t[e+1]:0)<<8|(r>2?t[e+2]:0);n+=Ih[a>>>18&63],n+=Ih[a>>>12&63],r>1&&(n+=Ih[a>>>6&63]),r>2&&(n+=Ih[63&a])}return n},Rh=e=>{if("string"!=typeof e||!Ch.test(e))throw new Error("Room capability must be exactly 43 unpadded base64url characters");if(3&Ih.indexOf(e.at(-1)??""))throw new Error("Room capability base64url encoding is not canonical");const t=new Uint8Array(vh);let n=0,r=0,a=0;for(const o of e)for(n=n<<6|Ih.indexOf(o),r+=6;r>=8;)r-=8,t[a]=n>>>r&255,a+=1,n&=(1<<r)-1;if(a!==vh||Kh(t)!==e)throw new Error("Room capability base64url encoding is not canonical");return t},Mh=e=>{if("string"!=typeof e)throw new TypeError("Room capability must be a string");return e.startsWith(kh)||e.startsWith(`#${kh}`)?Dh(e):64===e.length?(e=>{if(!Sh.test(e))throw new Error("Room capability hex must contain exactly 64 hex digits");const t=new Uint8Array(vh);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(2*n,2*n+2),16);return t})(e):Rh(e)},_h=e=>(e=>{let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t})(Mh(e)),Uh=e=>`${kh}${Kh(e)}`,Dh=e=>{if("string"!=typeof e)throw new TypeError("Room invite fragment must be a string");const t=e.startsWith("#")?e.slice(1):e;if(!t.startsWith(kh))throw new Error("Unsupported room invite version");return Rh(t.slice(kh.length))},Th=async e=>{const t=await globalThis.crypto.subtle.digest("SHA-256",((e,t)=>{const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n})(Ah,e));return new Uint8Array(t)[0]},Nh=async(t,n="wss://signaling.p2party.com/ws",r={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},a={})=>{if(t=_h(t),null===a||"object"!=typeof a||Array.isArray(a))throw new Error("Invalid room connection options");const{keyPair:o,signalingServer:i,rooms:s,commonState:c}=Xu.getState(),l=s.findIndex(e=>e.url===t);let d;if(-1===l){const e=(await Ja()).find(e=>e.roomUrl===t);e?.roomPolicy&&(d=je(new Uint8Array(e.roomPolicy)))}if(d&&a.policy&&!$e(d,a.policy))throw new Error("Persisted room policy is immutable");const u=He(a.policy??(l>-1?s[l].policy:d??Qe));if("legacy-signaling"!==u.rendezvousMode)throw new Error("Private rendezvous room connections are not wired yet");if("pin"===u.authMode){if(void 0!==a.pin){h=t,f=a.pin,xd.put(h,f);const e=l>-1?s[l].id:"";e&&await Nd(e)}else if(!(e=>xd.has(e))(t))throw new Error("PIN room connection requires a PIN")}else{if(void 0!==a.pin)throw new Error("PIN must not be provided for a no-PIN room");Kd(t)}var h,f;Gu(-1===l?Je({url:t,id:"",rtcConfig:r,policy:u}):Ye({roomContext:t,policy:u})),c.currentRoomUrl!==t&&Gu(A(t)),i.isConnected&&i.isVerified&&e(o.peerId)?-1===l?await Gu($u.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:o.peerId,roomUrl:t,protocolVersion:4}})):Gu(Ze({roomId:s[l].id,connectingToPeers:!0})):await Gu($u.endpoints.connectWebSocket.initiate(n))},qh=3e4,Oh=async(e,t={})=>{const n=_h(e),{timeoutMs:r=qh,signal:a}=t,o=()=>{const e=mt(Xu.getState()).find(e=>e.url===n);return e?.id?e:void 0},i=o();if(i)return i;if(a?.aborted)throw new Error("Waiting for the room was aborted before it started");return await new Promise((e,t)=>{let n=!1,i=()=>{};const s=setTimeout(()=>{l(()=>{t(new Error(`The signaling service did not assign a room id within ${String(r)}ms. The socket may be connected but not yet verified, or the room may be unreachable.`))})},r),c=()=>{l(()=>{t(new Error("Waiting for the room was aborted"))})};function l(e){n||(n=!0,clearTimeout(s),a?.removeEventListener("abort",c),i(),e())}const d=()=>{const t=o();t&&l(()=>{e(t)})};a?.addEventListener("abort",c,{once:!0}),i=Xu.subscribe(d),d()})},Bh=async(e,t,n,r={})=>{const{timeoutMs:a,signal:o,...i}=r;return await Nh(e,t,n,i),await Oh(e,{timeoutMs:a,signal:o})},Lh=async(e,t={})=>{const{count:n=1,timeoutMs:r=qh,signal:a}=t,o=()=>{const t=mt(Xu.getState()).find(t=>t.id===e);if(!t)return;const r=t.handshakeStatusByPeer,a=r?t.peers.filter(e=>"authenticated"===r[e.peerId]?.status):t.peers;return a.length>=n?a:void 0},i=o();if(i)return i;if(a?.aborted)throw new Error("Waiting for peers was aborted before it started");return await new Promise((e,t)=>{let i=!1,s=()=>{};const c=setTimeout(()=>{d(()=>{t(new Error(`Only ${String(o()?.length??0)} of ${String(n)} peer(s) authenticated within ${String(r)}ms`))})},r),l=()=>{d(()=>{t(new Error("Waiting for peers was aborted"))})};function d(e){i||(i=!0,clearTimeout(c),a?.removeEventListener("abort",l),s(),e())}const u=()=>{const t=o();t&&d(()=>{e(t)})};a?.addEventListener("abort",l,{once:!0}),s=Xu.subscribe(u),u()})},Fh=(e,t)=>{const n=new Set,r=()=>{const r=mt(Xu.getState()).find(t=>t.id===e);if(r)for(const a of r.messages){const r=a.merkleRootHex;r&&!n.has(r)&&(a.totalSize>0&&a.savedSize>=a.totalSize&&(n.add(r),zh(r,a.sha512Hex).then(n=>{try{t({roomId:e,fromPeerId:a.fromPeerId,merkleRootHex:r,filename:n.filename,size:n.size,message:n.message})}catch(e){console.error("p2party: onMessage handler threw",e)}}).catch(e=>{n.delete(r),console.error("p2party: could not read message",r,e)})))}},a=Xu.subscribe(r);return r(),a},zh=async(e,t,n=!0)=>{if(!e&&!t)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"txt",category:Ko.Text};try{const{keyPair:r,rooms:a}=Xu.getState(),o=a.length;let i=-1,s=-1;for(let n=0;n<o;n++)if(s=a[n].messages.findLastIndex(n=>n.merkleRootHex===e||r.peerId===n.fromPeerId&&n.sha512Hex===t&&""===n.merkleRootHex),s>-1){i=n;break}if(-1===i||-1===s)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"",category:Ko.Text};const c=a[i].messages[s].messageType,l=Ro(c),d=(e=>{switch(e){case xo.ImagePNG:return"png";case xo.ImageJPEG:return"jpeg";case xo.ImageJPG:return"jpg";case xo.ImageGIF:return"gif";case xo.ImageBMP:return"bmp";case xo.ImageTIFF:return"tiff";case xo.ImageSVG:return"svg";case xo.ImageWEBP:return"webp";case xo.ImageHEIC:return"heic";case xo.DocumentPDF:return"pdf";case xo.DocumentDOC:return"doc";case xo.DocumentDOCX:return"docx";case xo.DocumentXLS:return"xls";case xo.DocumentXLSX:return"xlsx";case xo.DocumentPPT:return"ppt";case xo.DocumentPPTX:return"pptx";case xo.DocumentTXT:return"txt";case xo.DocumentRTF:return"rtf";case xo.DocumentODT:return"odt";case xo.AudioMP3:return"mp3";case xo.AudioWAV:return"wav";case xo.AudioAAC:return"aac";case xo.AudioFLAC:return"flac";case xo.AudioOGG:return"ogg";case xo.AudioM4A:return"m4a";case xo.VideoMP4:return"mp4";case xo.VideoAVI:return"avi";case xo.VideoMKV:return"mkv";case xo.VideoMOV:return"mov";case xo.VideoWMV:return"wmv";case xo.VideoFLV:return"flv";case xo.VideoWEBM:return"webm";case xo.CompressedZIP:return"zip";case xo.CompressedRAR:return"rar";case xo.Compressed7Z:return"7z";case xo.CompressedTAR:return"tar";case xo.CompressedGZ:return"gz";case xo.CodeHTML:return"html";case xo.CodeCSS:return"css";case xo.CodeJS:return"js";case xo.CodeTS:return"ts";case xo.CodeJSX:return"jsx";case xo.CodeTSX:return"tsx";case xo.CodeJSON:return"json";case xo.CodeXML:return"xml";case xo.CodePY:return"py";case xo.CodeJAVA:return"java";case xo.CodeC:return"c";case xo.CodeCPP:return"cpp";case xo.CodeCS:return"cs";case xo.CodeRB:return"rb";case xo.CodePHP:return"php";case xo.CodeSQL:return"sql";case xo.EbookEPUB:return"epub";case xo.EbookMOBI:return"mobi";case xo.EbookAZW:return"azw";case xo.FontTTF:return"ttf";case xo.FontOTF:return"otf";case xo.ImageICO:return"ico";case xo.ExecutableEXE:return"exe";case xo.ExecutableDMG:return"dmg";case xo.ExecutableAPK:return"apk";default:return""}})(c),u=(e=>{switch(e){case xo.Text:return Ko.Text;case xo.ImagePNG:case xo.ImageJPEG:case xo.ImageJPG:case xo.ImageGIF:case xo.ImageBMP:case xo.ImageTIFF:case xo.ImageSVG:case xo.ImageWEBP:case xo.ImageHEIC:case xo.ImageICO:return Ko.Image;case xo.DocumentPDF:case xo.DocumentDOC:case xo.DocumentDOCX:case xo.DocumentXLS:case xo.DocumentXLSX:case xo.DocumentPPT:case xo.DocumentPPTX:case xo.DocumentTXT:case xo.DocumentRTF:case xo.DocumentODT:return Ko.Document;case xo.AudioMP3:case xo.AudioWAV:case xo.AudioAAC:case xo.AudioFLAC:case xo.AudioOGG:case xo.AudioM4A:return Ko.Audio;case xo.VideoMP4:case xo.VideoAVI:case xo.VideoMKV:case xo.VideoMOV:case xo.VideoWMV:case xo.VideoFLV:case xo.VideoWEBM:return Ko.Video;case xo.CompressedZIP:case xo.CompressedRAR:case xo.Compressed7Z:case xo.CompressedTAR:case xo.CompressedGZ:return Ko.Compressed;case xo.CodeHTML:case xo.CodeCSS:case xo.CodeJS:case xo.CodeJSX:case xo.CodeTS:case xo.CodeTSX:case xo.CodeJSON:case xo.CodeXML:case xo.CodePY:case xo.CodeJAVA:case xo.CodeC:case xo.CodeCPP:case xo.CodeCS:case xo.CodeRB:case xo.CodePHP:case xo.CodeSQL:return Ko.Code;case xo.EbookEPUB:case xo.EbookMOBI:case xo.EbookAZW:return Ko.Ebook;case xo.FontTTF:case xo.FontOTF:return Ko.Font;case xo.ExecutableEXE:case xo.ExecutableDMG:case xo.ExecutableAPK:return Ko.Executable;default:return Ko.Unknown}})(c),h=a[i].messages[s].fromPeerId===r.peerId?100:Math.floor(a[i].messages[s].savedSize/a[i].messages[s].totalSize*100),f={chunksReceivedTotal:a[i].messages[s].chunksReceivedTotal??0,chunksReceivedReal:a[i].messages[s].chunksReceivedReal??0,retransmits:a[i].messages[s].retransmits??0};if(c!==xo.Text&&!n)return{message:"",percentage:h,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u,...f};if(c!==xo.Text&&100===h){const e=a[i].messages[s].filename,t=a[i].messages[s].fromPeerId===r.peerId?await((e,t,n,r)=>Wa("assembleToOPFS",e,t,n,r))(a[i].messages[s].merkleRootHex,a[i].messages[s].totalSize,e,l):await((e,t,n,r)=>Wa("getReceiveFile",e,t,n,r))(a[i].messages[s].merkleRootHex,a[i].messages[s].totalSize,e,l);if(t)return{message:t,percentage:h,size:a[i].messages[s].totalSize,filename:e,mimeType:l,extension:d,category:u,...f}}const p=100===h?await((e,t)=>Wa("getDBAllChunks",e,t))(a[i].messages[s].merkleRootHex,a[i].messages[s].sha512Hex):[],m=p.map(e=>e.data).filter(e=>null!=e);try{const e=new Blob(m,{type:l});return c===xo.Text?{message:m.length>0?await e.text():a[i].messages[s].fromPeerId===r.peerId?"Outgoing message...":"Incoming message...",percentage:h,size:a[i].messages[s].totalSize,filename:"",mimeType:l,extension:d,category:u,...f}:100===h&&e.size!==a[i].messages[s].totalSize?{message:"Irretrievable message",percentage:0,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u}:{message:e,percentage:h,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u,...f}}catch{return{message:"Invalid message",percentage:0,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u}}}catch(e){return console.error(e),{message:"Irretrievable message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"",category:Ko.Text}}},jh=async(e,t,n,r,a)=>{if(!a&&!n&&!r)throw new Error("Need to provide a transfer ID, Merkle root, or hash");if(a&&!/^[0-9a-f]{64}$/.test(a))throw new Error("Invalid transfer ID");if(n&&"string"==typeof n&&n.length!==2*N)throw new Error("Invalid Merkle root length");if(n&&"string"!=typeof n&&n.length!==N)throw new Error("Invalid Merkle root length");if(r&&"string"==typeof r&&r.length!==2*N)throw new Error("Invalid hash length");if(r&&"string"!=typeof r&&r.length!==N)throw new Error("Invalid hash length");const o=n&&"string"==typeof n?n:n&&"string"!=typeof n?ca(n):"",i=r&&"string"==typeof r?r:r&&"string"!=typeof r?ca(r):"";kd(e,{transferId:a,merkleRootHex:o||void 0,hashHex:i||void 0});const{rooms:s}=Xu.getState(),c=s.findIndex(t=>t.id===e),l=c>-1?a?s[c].messages.findIndex(e=>e.transferId===a):n?s[c].messages.findIndex(e=>e.merkleRootHex===o):s[c].messages.findIndex(e=>e.sha512Hex===i):-1;if(c>-1&&l>-1&&s[c].messages[l].merkleRootHex.length===2*N){const n=await po(t,s[c].messages[l].merkleRootHex);await Xu.dispatch(Du.endpoints.disconnectFromChannelLabel.initiate({roomId:s[c].id,label:n,alsoDeleteData:!0})),Xu.dispatch(ft({roomId:e,merkleRootHex:s[c].messages[l].merkleRootHex}))}},Hh={store:Xu,commonStateSelector:e=>e.commonState,signalingServerSelector:e=>e.signalingServer,roomSelector:mt,keyPairSelector:e=>e.keyPair,connect:Nh,connectToSignalingServer:async(e,t="wss://signaling.p2party.com/ws")=>{e=_h(e);const{signalingServer:n,rooms:r,commonState:a}=Xu.getState();-1===r.findIndex(t=>t.url===e)&&Gu(Je({url:e,id:""})),a.currentRoomUrl!==e&&Gu(A(e)),n.serverUrl===t&&(n.isConnected||n.isEstablishingConnection)||await Gu($u.endpoints.connectWebSocket.initiate(t))},disconnectFromSignalingServer:async()=>{await Gu($u.endpoints.disconnectWebSocket.initiate(void 0))},disconnectFromRoom:async(e,t=!1)=>{await Gu(Du.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:t}))},disconnectFromAllRooms:async(e=!1,t=[])=>{await Gu(Du.endpoints.disconnectFromAllRooms.initiate({deleteMessages:e,exceptionRoomIds:t}))},disconnectFromPeer:async e=>{await Gu(Du.endpoints.disconnectFromPeer.initiate({peerId:e}))},allowConnectionRelay:(e,t=!0)=>{const{rooms:n}=Xu.getState(),r=n.findIndex(t=>t.id===e);r>-1&&Gu(tt({roomId:n[r].id,canBeConnectionRelay:t}))},onlyAllowConnectionsFromAddressBook:async(e,t)=>{let n;try{n=_h(e)}catch{return}e=n;const{rooms:r}=Xu.getState(),a=r.findIndex(t=>t.url===e);if(a>-1&&!r[a].onlyConnectWithKnownAddresses&&t&&r[a].peers.length>0){const e=r[a].peers.length;for(let t=0;t<e;t++){await Xa(r[a].peers[t].peerId,r[a].peers[t].peerPublicKey)||await Gu(Du.endpoints.disconnectFromPeer.initiate({peerId:r[a].peers[t].peerId,roomId:r[a].id,alsoDeleteData:!1}))}}Gu(Je({url:a>-1?r[a].url:e,id:a>-1?r[a].id:"",onlyConnectWithKnownPeers:t}))},addPeerToAddressBook:(e,t,n)=>Wa("setDBAddressBookEntry",e,t,n),getPeerAddressBookEntry:Xa,getAllPeersInAddressBook:()=>Wa("getAllDBAddressBookEntries"),getAllPeersInBlacklist:()=>Wa("getAllDBBlacklisted"),deletePeerFromAddressBook:async(t,n,r)=>{const a=await((e,t,n)=>Wa("deleteDBAddressBookEntry",e,t,n))(t,n,r);e(a)&&await Gu(Du.endpoints.disconnectFromPeer.initiate({peerId:a,alsoDeleteData:!1}))},blacklistPeer:async(e,t)=>{await((e,t)=>Wa("setDBPeerInBlacklist",e,t))(e,t),await Gu(Du.endpoints.disconnectFromPeer.initiate({peerId:e,alsoDeleteData:!0}))},getPeerIsBlacklisted:Ga,removePeerFromBlacklist:(e,t)=>Wa("deleteDBPeerFromBlacklist",e,t),getAllExistingRooms:Ja,getRoomStats:e=>Wa("getDBRoomStats",e),sendMessage:(e,t,n,r=.9,a=3,o=ne,i=1,s=wd())=>{if(!/^[0-9a-f]{64}$/.test(s))throw new Error("Invalid transfer ID");const c=vd(n,s),l=Gu(Du.endpoints.sendMessage.initiate({transferId:s,data:e,label:t,roomId:n,minChunks:a,chunkSize:o,percentageFilledChunk:r,metadataSchemaVersion:i})).unwrap().finally(()=>c.finish());return{transferId:s,done:l,cancel:()=>jh(n,t,void 0,void 0,s)}},readMessage:zh,getTransferAcks:(e,t)=>{const n=`${e}\0`,r=`\0${t}`,a=[];for(const[e,t]of yo)e.startsWith(n)&&e.endsWith(r)&&a.push({peerId:e.slice(n.length,e.length-r.length),ackedChunks:t.acked.size,complete:t.complete});return a},getSendChunksCount:e=>Wa("getDBAllNewChunksCount",e),cancelMessage:jh,createTransferId:wd,deleteMessage:async(e,t,n)=>{if(!t&&!n)throw new Error("Need to provide either merkle root or hash");if(t&&"string"==typeof t&&t.length!==2*N)throw new Error("Invalid Merkle root length");if(t&&"string"!=typeof t&&t.length!==N)throw new Error("Invalid Merkle root length");if(n&&"string"==typeof n&&n.length!==2*N)throw new Error("Invalid hash length");if(n&&"string"!=typeof n&&n.length!==N)throw new Error("Invalid hash length");const r=t&&"string"==typeof t?t:t&&"string"!=typeof t?ca(t):"",a=n&&"string"==typeof n?n:n&&"string"!=typeof n?ca(n):"";kd(e,{merkleRootHex:r||void 0,hashHex:a||void 0});const{rooms:o}=Xu.getState(),i=o.findIndex(t=>t.id===e),s=i>-1?t?o[i].messages.findIndex(e=>e.merkleRootHex===r):n?o[i].messages.findIndex(e=>e.sha512Hex===a):-1:-1;if(i>-1&&s>-1&&o[i].messages[s].merkleRootHex.length===2*N){const t=await po(o[i].messages[s].channelLabel,o[i].messages[s].merkleRootHex);await Xu.dispatch(Du.endpoints.disconnectFromChannelLabel.initiate({roomId:o[i].id,label:t,alsoDeleteData:!0})),Xu.dispatch(ft({roomId:e,merkleRootHex:o[i].messages[s].merkleRootHex}))}},purgeIdentity:async()=>{Sd(),Rd(),Gu(U()),await uo(),await fo();const{rooms:e}=Xu.getState(),t=e.length;for(let n=0;n<t;n++)await Gu(Du.endpoints.disconnectFromRoom.initiate({roomId:e[n].id}));await Gu($u.endpoints.disconnectWebSocket.initiate(void 0))},purgeRoom:async e=>{e=_h(e),Kd(e);const{rooms:t}=Xu.getState(),n=t.findIndex(t=>t.url===e);n>-1&&(Id(t[n].id),t[n].id&&await Nd(t[n].id),Gu(pt(t[n].id))),await Gu($u.endpoints.disconnectWebSocket.initiate(void 0))},purge:async()=>{Sd(),Rd(),Gu(U()),await uo(),await fo(),await Gu($u.endpoints.disconnectWebSocket.initiate(void 0));const e=await Ja(),t=e.length;for(let n=0;n<t;n++)Gu(pt(e[n].roomId))},generateRandomRoomUrl:async()=>Kh(xh()),generateRoomInvite:()=>Uh(xh()),generateRoomCapability:xh,encodeRoomCapabilityBase64Url:Kh,decodeRoomCapabilityBase64Url:Rh,decodeRoomCapability:Mh,normalizeRoomCapability:_h,encodeRoomInviteFragment:Uh,decodeRoomInviteFragment:Dh,encodeRoomCapabilityWords:async e=>{const t=Ph(e),n=new Uint8Array(33);n.set(t),n[32]=await Th(t);const r=(e=>{const t=[];let n=0,r=0;for(const a of e)for(n=n<<8|a,r+=8;r>=11;)r-=11,t.push(n>>>r&2047),n&=(1<<r)-1;if(0!==r)throw new Error("Room invite word encoding is not byte-aligned");return t})(n);if(24!==r.length)throw new Error("Room invite word encoding has an unexpected length");return r.map(e=>gh[e]).join(" ")},decodeRoomCapabilityWords:async e=>{if("string"!=typeof e)throw new TypeError("Room invite words must be a string");const t=e.normalize("NFKD").trim().toLowerCase(),n=0===t.length?[]:t.split(/\s+/u);if(24!==n.length)throw new Error("Room invite must contain exactly 24 words");const r=(e=>{const t=new Uint8Array(33);let n=0,r=0,a=0;for(const o of e)for(n=n<<11|o,r+=11;r>=8;)r-=8,t[a]=n>>>r&255,a+=1,n&=(1<<r)-1;if(0!==r||a!==t.length)throw new Error("Room invite word encoding is not canonical");return t})(n.map(e=>{const t=Eh.get(e);if(void 0===t)throw new Error(`Unknown room invite word: ${e}`);return t})),a=r.slice(0,vh),o=await Th(a);if(r[32]!==o)throw new Error("Room invite checksum is invalid");return a},ROOM_INVITE_WORDLIST_ID:"p2party-invite-en-v1",sign:Na,verify:qa,createSession:mh,restoreSession:yh,generateSessionIdentity:ch,setWasmSourceUrl:_a,DEFAULT_ROOM_POLICY_V1:Qe,encodeRoomPolicyV1:ze,decodeRoomPolicyV1:je,hashRoomPolicyV1:Ve,roomPoliciesEqualV1:$e,generateKeyPair:Ta,newKeyPair:Ta,generateMnemonic:async(e=128)=>{if(e%32!=0)throw new TypeError("Mnemonic strength needs to be multiple of 32.");if(![128,160,192,224,256,288,320,352,384,416,448,480,512].includes(e))throw new Error("Wrong mnemonic strength");const t=window.crypto.getRandomValues(new Uint8Array(e/8)),n=t.reduce((e,t)=>e+t.toString(2).padStart(8,"0"),""),r=e/32,a=Uint8Array.from(t),o=await window.crypto.subtle.digest("SHA-512",a);return(n+new Uint8Array(o).reduce((e,t)=>e+t.toString(2).padStart(8,"0"),"").slice(0,r)).match(/(.{1,11})/g).map(e=>{const t=parseInt(e,2);return gh[t]}).join(" ")},keyPairFromMnemonic:async(e,t)=>{if(!await bh(e))throw new Error("Invalid mnemonic.");const n=new Uint8Array($),r=new TextEncoder;r.encodeInto("password12345678",n);const a=new Uint8Array($);if(t){const e=r.encode(t),n=await window.crypto.subtle.digest("SHA-512",e);a.set(new Uint8Array(n).slice(N-$,N))}else a.set(n);const o=await(async(e,t,n)=>{const r=wh(e),a=(new TextEncoder).encode(r).buffer,o=new Int8Array(a),i=o.length;t=t??window.crypto.getRandomValues(new Uint8Array($));const s=n?.wasmMemory??ba(i),c=(n=n??await Ua(s))._malloc(B),l=new Uint8Array(s.buffer,c,B),d=n._malloc(i*Uint8Array.BYTES_PER_ELEMENT),u=new Int8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT),h=n._malloc($),f=new Uint8Array(s.buffer,h,$);try{if(Pa(l),u.set(o),f.set(t),0!==n._argon2(i,l.byteOffset,u.byteOffset,f.byteOffset))throw new Error("Could not generate argon2id for mnemonic.");return Uint8Array.from(l)}finally{Da(n,l),Da(n,new Uint8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT)),n._free(h),o.fill(0)}})(e,a);return await(async e=>{const t=fa(),n=await Ua(t),r=n._malloc(L),a=new Uint8Array(t.buffer,r,L),o=n._malloc(F),i=new Uint8Array(t.buffer,o,F),s=n._malloc(B),c=new Uint8Array(t.buffer,s,B);c.set(e);const l=n._keypair_from_seed(a.byteOffset,i.byteOffset,c.byteOffset);if(Da(n,c),0===l){const e={publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(i)};return n._free(r),Da(n,i),e}throw n._free(r),Da(n,i),new Error("An unexpected error occured.")})(o)},MIN_CHUNKS:1,MIN_CHUNK_SIZE:re+1,MAX_CHUNK_SIZE:ne,WIRE_CHUNK_FRAME_LEN:de,MIN_COVER_CADENCE_MS:Se,MAX_COVER_CADENCE_MS:Ce,MAX_COVER_LANES:16,MAX_COVER_FRAMES_PER_CELL:Ee,MIN_COVER_SLOT_MS:25,validateRoomPolicyV1:Fe,MessageDeliveryError:Su,joinRoom:Bh,waitForRoom:Oh,waitForPeers:Lh,onMessage:Fh,setDebugLogging:It,MIN_PERCENTAGE_FILLED_CHUNK:.1,MAX_PERCENTAGE_FILLED_CHUNK:.99,ROOM_URL_LENGTH:64,MessageType:xo,MessageCategory:Ko,VERSION:S};"undefined"!=typeof window&&(window.p2party=Hh);export{Qe as DEFAULT_ROOM_POLICY_V1,Ce as MAX_COVER_CADENCE_MS,Ee as MAX_COVER_FRAMES_PER_CELL,Ae as MAX_COVER_LANES,Se as MIN_COVER_CADENCE_MS,Pe as MIN_COVER_SLOT_MS,Su as MessageDeliveryError,de as WIRE_CHUNK_FRAME_LEN,He as canonicalizeRoomPolicyV1,mh as createSession,je as decodeRoomPolicyV1,Hh as default,ze as encodeRoomPolicyV1,ch as generateSessionIdentity,Ve as hashRoomPolicyV1,Bh as joinRoom,Fh as onMessage,Hh as p2party,yh as restoreSession,$e as roomPoliciesEqualV1,It as setDebugLogging,_a as setWasmSourceUrl,Fe as validateRoomPolicyV1,Lh as waitForPeers,Oh as waitForRoom};