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/README.md +10 -10
- package/docs/references.md +1 -1
- package/lib/handlers/reconcile.d.ts +24 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +1 -1
- package/lib/index.min.js +1 -1
- package/lib/index.mjs +1 -1
- package/lib/session.js +1 -1
- package/lib/session.mjs +1 -1
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("class-validator"),t=require("@reduxjs/toolkit");var n="0.14.2";const r=t.createSlice({name:"commonState",initialState:{currentRoomUrl:""},reducers:{setCurrentRoomUrl:(e,t)=>{e.currentRoomUrl=t.payload}}}),{setCurrentRoomUrl:a}=r.actions;var o=r.reducer;const i={peerId:localStorage.getItem("peerId")??"",challengeId:localStorage.getItem("challengeId")??"",publicKey:localStorage.getItem("publicKey")??"",secretKey:"",challenge:localStorage.getItem("challenge")??"",signature:localStorage.getItem("signature")??""},s=t.createSlice({name:"keyPair",initialState:i,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:(t,n)=>{const{peerId:r,challenge:a,signature:o,challengeId:i}=n.payload;e.isUUID(r,4)&&e.isUUID(i)&&e.isHexadecimal(a)&&e.isHexadecimal(o)&&64===a.length&&128===o.length&&(t.peerId=r,t.challenge=a,t.signature=o,t.challengeId=i)},setPeerData:(t,n)=>{const{peerId:r,challenge:a,signature:o}=n.payload;e.isUUID(r,4)&&e.isHexadecimal(a)&&e.isHexadecimal(o)&&64===a.length&&128===o.length&&(t.peerId=r,t.challenge=a,t.signature=o)},setChallengeId:(t,n)=>{const{challengeId:r}=n.payload;e.isUUID(r)&&(t.challengeId=r)},resetIdentity:()=>({peerId:"",challengeId:"",publicKey:"",secretKey:"",challenge:"",signature:""})}}),{setKeyPair:c,setReconnectData:l,setPeerData:d,setChallengeId:u,resetIdentity:h}=s.actions;var f=s.reducer;const p=64*Uint8Array.BYTES_PER_ELEMENT,m=64*Uint8Array.BYTES_PER_ELEMENT,y=208,g=64*Uint8Array.BYTES_PER_ELEMENT,w=32*Uint8Array.BYTES_PER_ELEMENT,b=32*Uint8Array.BYTES_PER_ELEMENT,v=64*Uint8Array.BYTES_PER_ELEMENT,k=32*Uint8Array.BYTES_PER_ELEMENT,I=12*Uint8Array.BYTES_PER_ELEMENT,S=16*Uint8Array.BYTES_PER_ELEMENT,A=16*Uint8Array.BYTES_PER_ELEMENT,C=32*Uint8Array.BYTES_PER_ELEMENT,E=64*Uint8Array.BYTES_PER_ELEMENT,P=32*Uint8Array.BYTES_PER_ELEMENT,x=32*Uint8Array.BYTES_PER_ELEMENT,R=32*Uint8Array.BYTES_PER_ELEMENT,M=65536,K=10737418240,U=1048576,_=9+m+8+8+256+8+8+8,D=4+48*(m+1),T=65405-(_+D),O=M-T,N=65405,B=m,q=1+B,L=new Uint8Array([1]),F=32,z=12,j=65474+S,H=(new TextEncoder).encode("p2party-x25519-idsig-v1"),V="hybrid-3dh-mlkem512-cpace21-v4",$="hybrid-3dh-mlkem768-cpace21-v4",Q="hybrid-3dh-mlkem1024-cpace21-v4",W=[V,$,Q],X=$,G=2e3,J=1048576,Y=65536,Z=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")},ee=e=>{if("hybrid-mlkem512"===e)return V;if("hybrid-mlkem768"===e)return $;if("hybrid-mlkem1024"===e)return Q;throw new Error("roomPolicy: unsupported PQ mode")},te=e=>{if(e===V)return"hybrid-mlkem512";if(e===$)return"hybrid-mlkem768";if(e===Q)return"hybrid-mlkem1024";throw new Error("roomPolicy: unsupported ratchet root suite")},ne=1e3,re=36e5,ae=1024,oe=new Uint8Array([80,50,82,80]),ie=(new TextEncoder).encode("p2party/room-policy/v1\0"),se=new Set(["version","revision","wireVersion","authMode","pqMode","rendezvousMode","coverMode","coverCadenceMs","coverLanes","coverFramesPerCell","coverDurationEpochs"]),ce={nopin:0,pin:1},le={"hybrid-mlkem768":1,"hybrid-mlkem512":2,"hybrid-mlkem1024":3},de={"legacy-signaling":0,"opaque-token":1,"blind-meeting-point":2},ue={immediate:0,scheduled:1},he=e=>{if(0===e)return"nopin";if(1===e)return"pin";throw new Error("roomPolicy: unsupported auth mode")},fe=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")},pe=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")},me=e=>{if(0===e)return"immediate";if(1===e)return"scheduled";throw new Error("roomPolicy: unsupported cover mode")},ye=(e,t,n)=>{if(!Number.isSafeInteger(t)||t<0||t>n)throw new Error(`roomPolicy: ${e} is out of range`)};function ge(e,t,n){if("string"!=typeof t||!Object.hasOwn(n,t))throw new Error(`roomPolicy: unsupported ${e}`)}const we=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!==se.size||n.some(e=>"string"!=typeof e||!se.has(e)))throw new Error("roomPolicy: policy has missing or unexpected fields (PIN bytes are never policy fields)");for(const t of se){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(ye("revision",e.revision,4294967295),ge("auth mode",e.authMode,ce),ge("PQ mode",e.pqMode,le),ge("rendezvous mode",e.rendezvousMode,de),ge("cover mode",e.coverMode,ue),ye("cover cadence",e.coverCadenceMs,4294967295),ye("cover lanes",e.coverLanes,65535),ye("cover frames per cell",e.coverFramesPerCell,65535),ye("cover duration epochs",e.coverDurationEpochs,65535),"immediate"!==e.coverMode){if(e.coverCadenceMs<ne||e.coverCadenceMs>re)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>ae)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")},be=e=>{we(e);const t=new Uint8Array(32);t.set(oe,0),t[4]=1,t[5]=e.wireVersion,t[6]=ce[e.authMode],t[7]=le[e.pqMode],t[8]=de[e.rendezvousMode],t[9]=ue[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},ve=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<oe.length;t++)if(e[t]!==oe[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:he(e[6]),pqMode:fe(e[7]),rendezvousMode:pe(e[8]),coverMode:me(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 we(n),n},ke=e=>ve(be(e)),Ie=(e,t)=>{const n=be(e),r=be(t);let a=0;for(let e=0;e<n.length;e++)a|=n[e]^r[e];return 0===a},Se=async e=>{const t=be(e),n=new Uint8Array(ie.length+t.length);n.set(ie,0),n.set(t,ie.length);const r=await globalThis.crypto.subtle.digest("SHA-256",n);return new Uint8Array(r)},Ae=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}),Ce={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},Ee=(e,t)=>{const n=ke(t);if(!Ie(e,n))throw new Error("roomSlice: room policy is immutable after creation")},Pe=t.createSlice({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.isUUID(a)){const e=t.findIndex(e=>e.url===r||e.id===a);e>-1?(c&&Ee(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??Ce,policy:ke(c??Ae),peers:[],channels:[],messages:[]})}else if(64===r.length){const e=t.findIndex(e=>e.url===r);e>-1?(c&&Ee(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??Ce,policy:ke(c??Ae),peers:[],channels:[],messages:[]})}},setRoomPolicy:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload.roomContext||e.id===t.payload.roomContext);n>-1&&Ee(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:y}=n.payload,g=t.findIndex(e=>e.id===r);if(g>-1){const n=t[g].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.isUUID(l)&&d&&h&&t[g].messages.push({transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:c,filename:s.length>0?s:"txt",messageType:d,fromPeerId:l,timestamp:y??Date.now(),savedSize:u>0?u:0,totalSize:h,chunksCreated:f??0,totalChunks:p??0}):t[g].messages[n].timestamp!==y&&t[g].messages[n].sha512Hex===i&&t[g].messages[n].savedSize===t[g].messages[n].totalSize?t[g].messages.push({transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:c,filename:s.length>0?s:"txt",messageType:d,fromPeerId:l,timestamp:y??Date.now(),savedSize:u,totalSize:h,chunksCreated:f??0,totalChunks:p??0}):(o.length===2*m&&""===t[g].messages[n].merkleRootHex&&(t[g].messages[n].merkleRootHex=o),h>0&&t[g].messages[n].totalSize!==h&&(t[g].messages[n].totalSize=h),u>0&&t[g].messages[n].totalSize>=t[g].messages[n].savedSize+u&&(t[g].messages[n].savedSize+=u),f&&f<=t[g].messages[n].totalChunks&&(t[g].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.isUUID(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*m)return;if(o&&o.length!==2*m)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:Ce,policy:ke(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:xe,setRoomPolicy:Re,setConnectingToPeers:Me,setConnectedToPeers:Ke,setConnectionRelay:Ue,setOnlyConnectWithKnownPeers:_e,setPeer:De,setPeerCoverStatus:Te,setPeerHandshakeStatus:Oe,setChannel:Ne,setIceServers:Be,setMessage:qe,setMessageAllChunks:Le,incrementMessageStats:Fe,deletePeer:ze,deleteChannel:je,deleteMessage:He,deleteRoom:Ve}=Pe.actions,$e=e=>e.rooms;var Qe=Pe.reducer;const We="wss://signaling.p2party.com/ws",Xe={isEstablishingConnection:!1,isConnected:!1,isVerified:!1,serverUrl:We},Ge=t.createSlice({name:"signalingServer",initialState:Xe,reducers:{startConnecting:(e,t)=>{e.isEstablishingConnection=!0,e.serverUrl=t.payload??We},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}}}),Je=Ge.actions;var Ye=Ge.reducer;let Ze=!1;Ze=(()=>{try{return"1"===globalThis.localStorage?.getItem("p2party:debug")}catch{return!1}})();const et=e=>{Ze=e},tt=(...e)=>{Ze&&console.log(...e)};var nt=Symbol.for("immer-nothing"),rt=Symbol.for("immer-draftable"),at=Symbol.for("immer-state");function ot(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var it=Object,st=it.getPrototypeOf,ct="constructor",lt="prototype",dt="configurable",ut="enumerable",ht="writable",ft="value",pt=e=>!!e&&!!e[at];function mt(e){return!!e&&(wt(e)||At(e)||!!e[rt]||!!e[ct]?.[rt]||Ct(e)||Et(e))}var yt=it[lt][ct].toString(),gt=new WeakMap;function wt(e){if(!e||!Pt(e))return!1;const t=st(e);if(null===t||t===it[lt])return!0;const n=it.hasOwnProperty.call(t,ct)&&t[ct];if(n===Object)return!0;if(!xt(n))return!1;let r=gt.get(n);return void 0===r&&(r=Function.toString.call(n),gt.set(n,r)),r===yt}function bt(e,t,n=!0){if(0===vt(e)){(n?Reflect.ownKeys(e):it.keys(e)).forEach(n=>{t(n,e[n],e)})}else e.forEach((n,r)=>t(r,n,e))}function vt(e){const t=e[at];return t?t.type_:At(e)?1:Ct(e)?2:Et(e)?3:0}var kt=(e,t,n=vt(e))=>2===n?e.has(t):it[lt].hasOwnProperty.call(e,t),It=(e,t,n=vt(e))=>2===n?e.get(t):e[t],St=(e,t,n,r=vt(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n};var At=Array.isArray,Ct=e=>e instanceof Map,Et=e=>e instanceof Set,Pt=e=>"object"==typeof e,xt=e=>"function"==typeof e,Rt=e=>"boolean"==typeof e;var Mt=e=>e.copy_||e.base_,Kt=e=>e.modified_?e.copy_:e.base_;function Ut(e,t){if(Ct(e))return new Map(e);if(Et(e))return new Set(e);if(At(e))return Array[lt].slice.call(e);const n=wt(e);if(!0===t||"class_only"===t&&!n){const t=it.getOwnPropertyDescriptors(e);delete t[at];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const a=n[r],o=t[a];!1===o[ht]&&(o[ht]=!0,o[dt]=!0),(o.get||o.set)&&(t[a]={[dt]:!0,[ht]:!0,[ut]:o[ut],[ft]:e[a]})}return it.create(st(e),t)}{const t=st(e);if(null!==t&&n)return{...e};const r=it.create(t);return it.assign(r,e)}}function _t(e,t=!1){return Tt(e)||pt(e)||!mt(e)||(vt(e)>1&&it.defineProperties(e,{set:Dt,add:Dt,clear:Dt,delete:Dt}),it.freeze(e),t&&bt(e,(e,t)=>{_t(t,!0)},!1)),e}var Dt={[ft]:function(){ot(2)}};function Tt(e){return null===e||!Pt(e)||it.isFrozen(e)}var Ot="MapSet",Nt="Patches",Bt="ArrayMethods",qt={};function Lt(e){const t=qt[e];return t||ot(0),t}var Ft,zt=e=>!!qt[e];var jt=()=>Ft;function Ht(e,t){t&&(e.patchPlugin_=Lt(Nt),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Vt(e){$t(e),e.drafts_.forEach(Wt),e.drafts_=null}function $t(e){e===Ft&&(Ft=e.parent_)}var Qt=e=>Ft={drafts_:[],parent_:Ft,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:zt(Ot)?Lt(Ot):void 0,arrayMethodsPlugin_:zt(Bt)?Lt(Bt):void 0};function Wt(e){const t=e[at];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function Xt(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[at].modified_&&(Vt(t),ot(4)),mt(e)&&(e=Gt(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[at].base_,e,t)}else e=Gt(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&_t(t,n)}(t,e,!0),Vt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==nt?e:void 0}function Gt(e,t){if(Tt(t))return t;const n=t[at];if(!n){return nn(t,e.handledSet_,e)}if(!Yt(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)}tn(n,e)}return n.copy_}function Jt(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var Yt=(e,t)=>e.scope_===t,Zt=[];function en(e,t,n,r){const a=Mt(e),o=e.type_;if(void 0!==r){if(It(a,r,o)===t)return void St(a,r,n,o)}if(!e.draftLocations_){const t=e.draftLocations_=new Map;bt(a,(e,n)=>{if(pt(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const i=e.draftLocations_.get(t)??Zt;for(const e of i)St(a,e,n,o)}function tn(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)}Jt(e)}}function nn(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||pt(e)||t.has(e)||!mt(e)||Tt(e)||(t.add(e),bt(e,(r,a)=>{if(pt(a)){const t=a[at];if(Yt(t,n)){const n=Kt(t);St(e,r,n,e.type_),Jt(t)}}else mt(a)&&nn(a,t,n)})),e}var rn={get(e,t){if(t===at)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=Mt(e);if(!kt(a,t,e.type_))return function(e,t,n){const r=sn(t,n);return r?ft in r?r[ft]:r.get?.call(e.draft_):void 0}(e,a,t);const o=a[t];if(e.finalized_||!mt(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===on(e.base_,t)||function(e,t,n){if(1!==e.type_||!e.allIndicesReassigned_||e.assigned_?.get(t)||!mt(n)||n[at])return!1;return e.baseRefs_.has(n)}(e,t,o)){ln(e);const n=1===e.type_?+t:t,r=dn(e.scope_,o,e,n);return e.copy_[n]=r}return o},has:(e,t)=>t in Mt(e),ownKeys:e=>Reflect.ownKeys(Mt(e)),set(e,t,n){const r=sn(Mt(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=on(Mt(e),t),i=r?.[at];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||kt(e.base_,t,e.type_)))return!0;ln(e),cn(e)}var a,o;return e.copy_[t]===n&&(void 0!==n||kt(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(pt(n)){const a=n[at];Yt(a,r)&&a.callbacks_.push(function(){ln(e);const r=Kt(a);en(e,n,r,t)})}else mt(n)&&e.callbacks_.push(function(){const a=Mt(e);3===e.type_?a.has(n)&&nn(n,r.handledSet_,r):It(a,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&nn(It(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(ln(e),void 0!==on(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),cn(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Mt(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[ht]:!0,[dt]:1!==e.type_||"length"!==t,[ut]:r[ut],[ft]:n[t]}:r},defineProperty(){ot(11)},getPrototypeOf:e=>st(e.base_),setPrototypeOf(){ot(12)}},an={};for(let e in rn){let t=rn[e];an[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function on(e,t){const n=e[at];return(n?Mt(n):e)[t]}function sn(e,t){if(!(t in e))return;let n=st(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=st(n)}}function cn(e){e.modified_||(e.modified_=!0,e.parent_&&cn(e.parent_))}function ln(e){e.copy_||(e.assigned_=new Map,e.copy_=Ut(e.base_,e.scope_.immer_.useStrictShallowCopy_))}an.deleteProperty=function(e,t){return an.set.call(this,e,t,void 0)},an.set=function(e,t,n){return rn.set.call(this,e[0],t,n,e[0])};function dn(e,t,n,r){const[a,o]=Ct(t)?Lt(Ot).proxyMap_(t,n):Et(t)?Lt(Ot).proxySet_(t,n):function(e,t){const n=At(e),r={type_:n?1:0,scope_:t?t.scope_:jt(),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=rn;n&&(a=[r],o=an);const{revoke:i,proxy:s}=Proxy.revocable(a,o);return r.draft_=s,r.revoke_=i,[s,r]}(t,n);return(n?.scope_??jt()).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||!Yt(a,r))return;r.mapSetPlugin_?.fixSetContents(a);const o=Kt(a);en(e,a.draft_??a,o,n),tn(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 pt(e)||ot(10),hn(e)}function hn(e){if(!mt(e)||Tt(e))return e;const t=e[at];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Ut(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=Ut(e,!0);return bt(n,(e,t)=>{St(n,e,hn(t))},r),t&&(t.finalized_=!1),n}function fn(){const e="replace",t="add",n="remove";function r(e){if(!mt(e))return e;if(At(e))return e.map(r);if(Ct(e))return new Map(Array.from(e.entries()).map(([e,t])=>[e,r(t)]));if(Et(e))return new Set(Array.from(e).map(r));const t=Object.create(st(e));for(const n in e)t[n]=r(e[n]);return kt(e,rt)&&(t[rt]=e[rt]),t}function a(e){return pt(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=vt(c);let n=i[e];"string"!=typeof n&&"number"!=typeof n&&(n=""+n),0!==t&&1!==t||"__proto__"!==n&&n!==ct||ot(19),xt(c)&&n===lt&&ot(19),c=It(c,n),null!==c&&Pt(c)||ot(18,i.join("/"))}const l=vt(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:ot(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:ot(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;bt(r.assigned_,(r,u)=>{const h=It(c,r,d),f=It(l,r,d),p=u?kt(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?.[at];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===nt?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=It(e,t.key_),Pt(r)?r?.[at]:null),o=It(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||kt(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=It(n,r),!Pt(n)||null===n)throw new Error(`Cannot resolve path at '${t.join("/")}'`)}}(t.copy_,n)}catch(e){return null}return n}},qt[o=Nt]||(qt[o]=i)}var pn=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(xt(e)&&!xt(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(xt(t)||ot(6),void 0===n||xt(n)||ot(7),mt(e)){const a=Qt(this),o=dn(a,e,void 0);let i=!0;try{r=t(o),i=!1}finally{i?Vt(a):$t(a)}return Ht(a,n),Xt(r,a)}if(!e||!Pt(e)){if(r=t(e),void 0===r&&(r=e),r===nt&&(r=void 0),this.autoFreeze_&&_t(r,!0),n){const t=[],a=[];Lt(Nt).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:a}),n(t,a)}return r}ot(1)},this.produceWithPatches=(e,t)=>{if(xt(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]},Rt(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),Rt(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),Rt(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){mt(e)||ot(8),pt(e)&&(e=un(e));const t=Qt(this),n=dn(t,e,void 0);return n[at].isManual_=!0,$t(t),n}finishDraft(e,t){const n=e&&e[at];n&&n.isManual_||ot(9);const{scope_:r}=n;return Ht(r,t),Xt(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=Lt(Nt).applyPatches_;return pt(e)?r(e,t):this.produce(e,e=>r(e,t))}};pn.produce;var mn=pn.produceWithPatches.bind(pn),yn=pn.applyPatches.bind(pn),gn=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}};var wn=e=>Array.isArray(e)?e:[e];function bn(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 vn="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function kn(){return{s:0,v:void 0,o:null,p:null}}function In(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=kn(),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=kn(),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 vn(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 Sn(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=In,argsMemoizeOptions:u=[]}=s,h=wn(l),f=wn(u),p=bn(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 An=Sn(In),Cn=Object.assign((e,t=An)=>{!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:()=>Cn}),En="uninitialized",Pn="pending",xn="fulfilled",Rn="rejected";function Mn(e){return{status:e,isUninitialized:e===En,isLoading:e===Pn,isSuccess:e===xn,isError:e===Rn}}var Kn=t.isPlainObject;function Un(e,t){if(e===t||!(Kn(e)&&Kn(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]=Un(e[r],t[r]),a&&(a=e[r]===o[r]);return a?e:o}function _n(e,t,n){return e.reduce((e,r,a)=>(t(r,a)&&e.push(n(r,a)),e),[]).flat()}function Dn(e){return null!=e}function Tn(e){return[...e?.values()??[]].filter(Dn)}function On(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var Nn=()=>new Map,Bn=class{constructor(e,t=void 0){this.value=e,this.meta=t}value;meta},qn="__rtkq/",Ln="focused",Fn=t.createAction(`${qn}${Ln}`),zn=t.createAction(`${qn}un${Ln}`),jn=t.createAction(`${qn}online`),Hn=t.createAction(`${qn}offline`),Vn="query",$n="mutation",Qn="infinitequery";function Wn(e){return e.type===Vn}function Xn(e){return e.type===Qn}function Gn(e){return Wn(e)||Xn(e)}function Jn(e,t,n,r,a,o){const i="function"==typeof e?e(t,n,r,a):e;return i?_n(i,Dn,e=>o(Yn(e))):[]}function Yn(e){return"string"==typeof e?{type:e}:e}var Zn=(e,t)=>e.endpointDefinitions[t],er=Symbol("forceQueryFn"),tr=e=>"function"==typeof e[er];var nr=class extends gn{constructor(e,t,n,r){super(e),this.value=t,this.schemaName=n,this._bqMeta=r}value;schemaName;_bqMeta},rr=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function ar(e,t,n,r){const a=await e["~standard"].validate(t);if(a.issues)throw new nr(a.issues,t,n,r);return a.value}function or(e){return e}var ir=(e={})=>({...e,[t.SHOULD_AUTOBATCH]:!0});function sr(e,{pages:t,pageParams:n},r){const a=t.length-1;return e.getNextPageParam(t[a],t,n[a],n,r)}function cr(e,{pages:t,pageParams:n},r){return e.getPreviousPageParam?.(t[0],t,n[0],n,r)}function lr(e,n,r,a){return Jn(r[e.meta.arg.endpointName][n],t.isFulfilled(e)?e.payload:void 0,t.isRejectedWithValue(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,a)}function dr(e){return pt(e)?un(e):e}function ur(e,t,n){const r=e[t];r&&n(r)}function hr(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function fr(e,t,n){const r=e[hr(t)];r&&n(r)}var pr={};function mr({reducerPath:e,queryThunk:n,mutationThunk:r,serializeQueryArgs:a,context:{endpointDefinitions:o,apiUid:i,extractRehydrationInfo:s,hasRehydrationInfo:c},assertTagType:l,config:d}){const u=t.createAction(`${e}/resetApiState`);function h(e,t,n,r){e[t.queryCacheKey]??={status:En,endpointName:t.endpointName},ur(e,t.queryCacheKey,e=>{e.status=Pn,e.requestId=n&&e.requestId?e.requestId:r.requestId,void 0!==t.originalArgs&&(e.originalArgs=t.originalArgs),e.startedTimeStamp=r.startedTimeStamp;Xn(o[r.arg.endpointName])&&"direction"in t&&(e.direction=t.direction)})}function f(e,n,r,a){ur(e,n.arg.queryCacheKey,e=>{if(e.requestId!==n.requestId&&!a)return;const{merge:i}=o[n.arg.endpointName];if(e.status=xn,i)if(void 0!==e.data){const{fulfilledTimeStamp:a,arg:o,baseQueryMeta:s,requestId:c}=n;let l=t.createNextState(e.data,e=>i(e,r,{arg:o.originalArgs,baseQueryMeta:s,fulfilledTimeStamp:a,requestId:c}));e.data=l}else e.data=r;else e.data=o[n.arg.endpointName].structuralSharing??1?Un(pt(e.data)?(s=e.data,pt(s)||ot(15),s[at].base_):e.data,r):r;var s;delete e.error,e.fulfilledTimeStamp=n.fulfilledTimeStamp})}const p=t.createSlice({name:`${e}/queries`,initialState:pr,reducers:{removeQueryResult:{reducer(e,{payload:{queryCacheKey:t}}){delete e[t]},prepare:t.prepareAutoBatched()},cacheEntriesUpserted:{reducer(e,t){for(const n of t.payload){const{queryDescription:r,value:a}=n;h(e,r,!0,{arg:r,requestId:t.meta.requestId,startedTimeStamp:t.meta.timestamp}),f(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,i=o[t];return{queryDescription:{type:Vn,endpointName:t,originalArgs:e.arg,queryCacheKey:a({queryArgs:n,endpointDefinition:i,endpointName:t})},value:r}}),meta:{[t.SHOULD_AUTOBATCH]:!0,requestId:t.nanoid(),timestamp:Date.now()}})},queryResultPatched:{reducer(e,{payload:{queryCacheKey:t,patches:n}}){ur(e,t,e=>{e.data=yn(e.data,n.concat())})},prepare:t.prepareAutoBatched()}},extraReducers(e){e.addCase(n.pending,(e,{meta:t,meta:{arg:n}})=>{h(e,n,tr(n),t)}).addCase(n.fulfilled,(e,{meta:t,payload:n})=>{f(e,t,n,tr(t.arg))}).addCase(n.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=Rn,e.error=o??a}})}).addMatcher(c,(e,t)=>{const{queries:n}=s(t);for(const[t,r]of Object.entries(n))r?.status!==xn&&r?.status!==Rn||(e[t]=r)})}}),m=t.createSlice({name:`${e}/mutations`,initialState:pr,reducers:{removeMutationResult:{reducer(e,{payload:t}){const n=hr(t);n in e&&delete e[n]},prepare:t.prepareAutoBatched()}},extraReducers(e){e.addCase(r.pending,(e,{meta:t,meta:{requestId:n,arg:r,startedTimeStamp:a}})=>{r.track&&(e[hr(t)]={requestId:n,status:Pn,endpointName:r.endpointName,startedTimeStamp:a})}).addCase(r.fulfilled,(e,{payload:t,meta:n})=>{n.arg.track&&fr(e,n,e=>{e.requestId===n.requestId&&(e.status=xn,e.data=t,e.fulfilledTimeStamp=n.fulfilledTimeStamp)})}).addCase(r.rejected,(e,{payload:t,error:n,meta:r})=>{r.arg.track&&fr(e,r,e=>{e.requestId===r.requestId&&(e.status=Rn,e.error=t??n)})}).addMatcher(c,(e,t)=>{const{mutations:n}=s(t);for(const[t,r]of Object.entries(n))r?.status!==xn&&r?.status!==Rn||t===r?.requestId||(e[t]=r)})}}),y=t.createSlice({name:`${e}/invalidation`,initialState:{tags:{},keys:{}},reducers:{updateProvidedBy:{reducer(e,t){for(const{queryCacheKey:n,providedTags:r}of t.payload){g(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:t.prepareAutoBatched()}},extraReducers(e){e.addCase(p.actions.removeQueryResult,(e,{payload:{queryCacheKey:t}})=>{g(e,t)}).addMatcher(c,(e,t)=>{const{provided:n}=s(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(t.isAnyOf(t.isFulfilled(n),t.isRejectedWithValue(n)),(e,t)=>{w(e,[t])}).addMatcher(p.actions.cacheEntriesUpserted.match,(e,t)=>{w(e,t.payload.map(({queryDescription:e,value:t})=>({type:"UNKNOWN",payload:t,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:e}})))})}});function g(e,t){const n=dr(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]=dr(o).filter(e=>e!==t))}delete e.keys[t]}function w(e,t){const n=t.map(e=>{const t=lr(e,"providesTags",o,l),{queryCacheKey:n}=e.meta.arg;return{queryCacheKey:n,providedTags:t}});y.caseReducers.updateProvidedBy(e,y.actions.updateProvidedBy(n))}const b=t.createSlice({name:`${e}/subscriptions`,initialState:pr,reducers:{updateSubscriptionOptions(e,t){},unsubscribeQueryResult(e,t){},internal_getRTKQSubscriptions(){}}}),v=t.createSlice({name:`${e}/internalSubscriptions`,initialState:pr,reducers:{subscriptionsUpdated:{reducer:(e,t)=>yn(e,t.payload),prepare:t.prepareAutoBatched()}}}),k=t.createSlice({name:`${e}/config`,initialState:{online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine,focused:"undefined"==typeof document||"hidden"!==document.visibilityState,middlewareRegistered:!1,...d},reducers:{middlewareRegistered(e,{payload:t}){e.middlewareRegistered="conflict"!==e.middlewareRegistered&&i===t||"conflict"}},extraReducers:e=>{e.addCase(jn,e=>{e.online=!0}).addCase(Hn,e=>{e.online=!1}).addCase(Fn,e=>{e.focused=!0}).addCase(zn,e=>{e.focused=!1}).addMatcher(c,e=>({...e}))}}),I=t.combineReducers({queries:p.reducer,mutations:m.reducer,provided:y.reducer,subscriptions:v.reducer,config:k.reducer});return{reducer:(e,t)=>I(u.match(t)?void 0:e,t),actions:{...k.actions,...p.actions,...b.actions,...v.actions,...m.actions,...y.actions,resetApiState:u}}}var yr=Symbol.for("RTKQ/skipToken"),gr={status:En},wr=t.createNextState(gr,()=>{}),br=t.createNextState(gr,()=>{});var vr=WeakMap?new WeakMap:void 0,kr=({endpointName:e,queryArgs:n})=>{let r="";const a=vr?.get(n);if("string"==typeof a)r=a;else{const e=JSON.stringify(n,(e,n)=>(n="bigint"==typeof n?{$bigint:n.toString()}:n,n=t.isPlainObject(n)?Object.keys(n).sort().reduce((e,t)=>(e[t]=n[t],e),{}):n));t.isPlainObject(n)&&vr?.set(n,e),r=e}return`${e}(${r})`};function Ir(...e){return function(n){const r=In(e=>n.extractRehydrationInfo?.(e,{reducerPath:n.reducerPath??"api"})),a={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...n,extractRehydrationInfo:r,serializeQueryArgs(e){let t=kr;if("serializeQueryArgs"in e.endpointDefinition){const n=e.endpointDefinition.serializeQueryArgs;t=e=>{const t=n(e);return"string"==typeof t?t:kr({...e,queryArgs:t})}}else n.serializeQueryArgs&&(t=n.serializeQueryArgs);return t(e)},tagTypes:[...n.tagTypes||[]]},o={endpointDefinitions:{},batch(e){e()},apiUid:t.nanoid(),extractRehydrationInfo:r,hasRehydrationInfo:In(e=>null!=r(e))},i={injectEndpoints:function(e){const n=e.endpoints({query:e=>({...e,type:Vn}),mutation:e=>({...e,type:$n}),infiniteQuery:e=>({...e,type:Qn})});for(const[r,a]of Object.entries(n))if(!0!==e.overrideExisting&&r in o.endpointDefinitions){if("throw"===e.overrideExisting)throw new Error(t.formatProdErrorMessage(39))}else{o.endpointDefinitions[r]=a;for(const e of s)e.injectEndpoint(r,a)}return i},enhanceEndpoints({addTagTypes:e,endpoints:t}){if(e)for(const t of e)a.tagTypes.includes(t)||a.tagTypes.push(t);if(t)for(const[e,n]of Object.entries(t))"function"==typeof n?n(Zn(o,e)):Object.assign(Zn(o,e)||{},n);return i}},s=e.map(e=>e.init(i,a,o));return i.injectEndpoints({endpoints:n.endpoints})}}function Sr(e,...t){return Object.assign(e,...t)}var Ar=({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=On(n,e.queryCacheKey,Nn);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=On(n,t.queryCacheKey,Nn);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]=mn(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]}},Cr=({reducerPath:e,api:n,queryThunk:r,context:a,internalState:o,selectors:{selectQueryEntry:i,selectConfig:s},getRunningQueryThunk:c,mwApi:l})=>{const{removeQueryResult:d,unsubscribeQueryResult:u,cacheEntriesUpserted:h}=n.internalActions,f=t.isAnyOf(u.match,r.fulfilled,r.rejected,h.match);function p(e){const t=o.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=i(r,a);e?.endpointName&&w(a,e.endpointName,t,n)}}function w(e,t,n,r){const o=Zn(a,t),s=o?.keepUnusedDataFor??r.keepUnusedDataFor;if(s===1/0)return;const l=Math.max(0,Math.min(s,2147482.647));if(!p(e)){const t=m[e];t&&clearTimeout(t),m[e]=setTimeout(()=>{if(!p(e)){const t=i(n.getState(),e);if(t?.endpointName){const e=n.dispatch(c(t.endpointName,t.originalArgs));e?.abort()}n.dispatch(d({queryCacheKey:e}))}delete m[e]},1e3*l)}}return(e,t)=>{const r=t.getState(),i=s(r);if(f(e)){let n;if(h.match(e))n=e.payload.map(e=>e.queryDescription.queryCacheKey);else{const{queryCacheKey:t}=u.match(e)?e.payload:e.meta.arg;n=[t]}g(n,t,i)}if(n.util.resetApiState.match(e)){for(const[e,t]of Object.entries(m))t&&clearTimeout(t),delete m[e];y(o.runningQueries),y(o.runningMutations)}if(a.hasRehydrationInfo(e)){const{queries:n}=a.extractRehydrationInfo(e);g(Object.keys(n),t,i)}}},Er=new Error("Promise never resolved before cacheEntryRemoved."),Pr=({api:e,reducerPath:n,context:r,queryThunk:a,mutationThunk:o,internalState:i,selectors:{selectQueryEntry:s,selectApiState:c}})=>{const l=t.isAsyncThunkAction(a),d=t.isAsyncThunkAction(o),u=t.isFulfilled(a,o),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,n,a,o,i){const s=Zn(r,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 Er})]);u.catch(()=>{}),h[a]=l;const f=e.endpoints[t].select(Gn(s)?n:a),p=o.dispatch((e,t,n)=>n),m={...o,getCacheEntry:()=>f(o.getState()),requestId:i,extra:p,updateCachedData:Gn(s)?r=>o.dispatch(e.util.updateQueryData(t,n,r)):void 0,cacheDataLoaded:u,cacheEntryRemoved:d},y=c(n,m);Promise.resolve(y).catch(e=>{if(e!==Er)throw e})}return(t,r,i)=>{const c=function(e){if(l(e))return e.meta.arg.queryCacheKey;if(d(e))return e.meta.arg.fixedCacheKey??e.meta.requestId;return f.match(e)?e.payload.queryCacheKey:p.match(e)?hr(e.payload):""}(t);function v(e,t,n,a){const o=s(i,t),c=s(r.getState(),t);!o&&c&&b(e,a,t,r,n)}if(a.pending.match(t)){const[e,n,r]=w(t);v(e,c,r,n)}else if(m.match(t))for(const{queryDescription:e,value:n}of t.payload){const{endpointName:r,originalArgs:a,queryCacheKey:o}=e;v(r,o,t.meta.requestId,a),y(o,n,{})}else if(o.pending.match(t)){if(r.getState()[n].mutations[c]){const[e,n,a]=w(t);b(e,n,c,r,a)}}else if(u(t))y(c,t.payload,t.meta.baseQueryMeta);else if(f.match(t)||p.match(t))g(c);else if(e.util.resetApiState.match(t))for(const e of Object.keys(h))g(e)}},xr=({api:e,context:{apiUid:t},reducerPath:n})=>(n,r)=>{e.util.resetApiState.match(n)&&r.dispatch(e.internalActions.middlewareRegistered(t))},Rr=({reducerPath:e,context:n,context:{endpointDefinitions:r},mutationThunk:a,queryThunk:o,api:i,assertTagType:s,refetchQuery:c,internalState:l})=>{const{removeQueryResult:d}=i.internalActions,u=t.isAnyOf(t.isFulfilled(a),t.isRejectedWithValue(a)),h=t.isAnyOf(t.isFulfilled(o,a),t.isRejected(o,a));let f=[],p=0;function m(t,r){const a=r.getState(),o=a[e];if(f.push(...t),"delayed"===o.config.invalidationBehavior&&p>0)return;const s=f;if(f=[],0===s.length)return;const u=i.util.selectInvalidatedBy(a,s);n.batch(()=>{const e=Array.from(u.values());for(const{queryCacheKey:t}of e){const e=o.queries[t],n=On(l.currentSubscriptions,t,Nn);e&&(0===n.size?r.dispatch(d({queryCacheKey:t})):e.status!==En&&r.dispatch(c(e)))}})}return(e,t)=>{(o.pending.match(e)||a.pending.match(e))&&p++,h(e)&&(p=Math.max(0,p-1)),u(e)?m(lr(e,"invalidatesTags",r,s),t):h(e)?m([],t):i.util.invalidateTags.match(e)&&m(Jn(e.payload,void 0,void 0,void 0,void 0,s),t)}},Mr=({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===En)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===En)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())}},Kr=({api:e,context:n,queryThunk:r,mutationThunk:a})=>{const o=t.isPending(r,a),i=t.isRejected(r,a),s=t.isFulfilled(r,a),c={};return(t,r)=>{if(o(t)){const{requestId:a,arg:{endpointName:o,originalArgs:i}}=t.meta,s=Zn(n,o),l=s?.onQueryStarted;if(l){const t={},n=new Promise((e,n)=>{t.resolve=e,t.reject=n});n.catch(()=>{}),c[a]=t;const d=e.endpoints[o].select(Gn(s)?i:a),u=r.dispatch((e,t,n)=>n),h={...r,getCacheEntry:()=>d(r.getState()),requestId:a,extra:u,updateCachedData:Gn(s)?t=>r.dispatch(e.util.updateQueryData(o,i,t)):void 0,queryFulfilled:n};l(i,h)}}else if(s(t)){const{requestId:e,baseQueryMeta:n}=t.meta;c[e]?.resolve({data:t.payload,meta:n}),delete c[e]}else if(i(t)){const{requestId:e,rejectedWithValue:n,baseQueryMeta:r}=t.meta;c[e]?.reject({error:t.payload??t.error,isUnhandledError:!n,meta:r}),delete c[e]}}};function Ur(e){const{reducerPath:n,queryThunk:r,api:a,context:o,getInternalState:i}=e,{apiUid:s}=o,c={invalidateTags:t.createAction(`${n}/invalidateTags`)},l=e=>e.type.startsWith(`${n}/`),d=[xr,Cr,Rr,Mr,Pr,Kr];return{middleware:r=>{let c=!1;const h=i(r.dispatch),f={...e,internalState:h,refetchQuery:u,isThisApiSliceAction:l,mwApi:r},p=d.map(e=>e(f)),m=Ar(f),y=(({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!==En&&n.dispatch(r(t)))}})}return(e,t)=>{Fn.match(e)&&i(t,"refetchOnFocus"),jn.match(e)&&i(t,"refetchOnReconnect")}})(f);return e=>i=>{if(!t.isAction(i))return e(i);c||(c=!0,r.dispatch(a.internalActions.middlewareRegistered(s)));const d={...r,next:e},u=r.getState(),[h,f]=m(i,d,u);let g;if(g=h?e(i):f,r.getState()[n]&&(y(i,d,u),l(i)||o.hasRehydrationInfo(i)))for(const e of p)e(i,d,u);return g}},actions:c};function u(t){return e.api.endpoints[t.endpointName].initiate(t.originalArgs,{subscribe:!1,forceRefetch:!0})}}var _r=Symbol(),Dr=Ir((({createSelector:e=t.createSelector}={})=>({name:_r,init(n,{baseQuery:r,tagTypes:a,reducerPath:o,serializeQueryArgs:i,keepUnusedDataFor:s,refetchOnMountOrArgChange:c,refetchOnFocus:l,refetchOnReconnect:d,invalidationBehavior:u,onSchemaFailure:h,catchSchemaFailure:f,skipSchemaValidation:p},m){fn();const y=e=>e;Object.assign(n,{reducerPath:o,endpoints:{},internalActions:{onOnline:jn,onOffline:Hn,onFocus:Fn,onFocusLost:zn},util:{}});const g=function({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=e=>wr,a=e=>br;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,...Mn(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?hr(e)??yr:e,n(t===yr?a:e=>i(e)?.mutations?.[t]??br,o)}},selectInvalidatedBy:function(e,n){const r=e[t],a=new Set,o=_n(n,Dn,Yn);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 _n(Object.values(s(e)),e=>e?.endpointName===t&&e.status!==En,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,...Mn(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===yr)return n(r,o);const s=e({queryArgs:i,endpointDefinition:a,endpointName:t});return n(e=>c(e,s)??wr,o)}}function d(e,t,n){return!!t&&null!=sr(e,t,n)}function u(e,t,n){return!(!t||!e.getPreviousPageParam)&&null!=cr(e,t,n)}}({serializeQueryArgs:i,reducerPath:o,createSelector:e}),{selectInvalidatedBy:w,selectCachedArgsForQuery:b,buildQuerySelector:v,buildInfiniteQuerySelector:k,buildMutationSelector:I}=g;Sr(n.util,{selectInvalidatedBy:w,selectCachedArgsForQuery:b});const{queryThunk:S,infiniteQueryThunk:A,mutationThunk:C,patchQueryData:E,updateQueryData:P,upsertQueryData:x,prefetch:R,buildMatchThunkActions:M}=function({reducerPath:e,baseQuery:n,context:{endpointDefinitions:r},serializeQueryArgs:a,api:o,assertTagType:i,selectors:s,onSchemaFailure:c,catchSchemaFailure:l,skipSchemaValidation:d}){function u(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}function h(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}const f=(e,t)=>e.query&&e[t]?e[t]:or,p=async(e,{signal:t,abort:a,rejectWithValue:o,fulfillWithValue:i,dispatch:p,getState:y,extra:g})=>{const w=r[e.endpointName],{metaSchema:b,skipSchemaValidation:v=d}=w,k=e.type===Vn;try{let I=or;const S={signal:t,abort:a,dispatch:p,getState:y,extra:g,endpoint:e.endpointName,type:e.type,forced:k?m(e,y()):void 0,queryCacheKey:k?e.queryCacheKey:void 0},A=k?e[er]:void 0;let C;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?u:h;return{data:{pages:s(t.pages,i.data,r),pageParams:s(t.pageParams,n,r)},meta:i.meta}};async function P(e){let t;const{extraOptions:r,argSchema:a,rawResponseSchema:o,responseSchema:i}=w;if(a&&!rr(v,"arg")&&(e=await ar(a,e,"argSchema",{})),A?t=A():w.query?(I=f(w,"transformResponse"),t=await n(w.query(e),S,r)):t=await w.queryFn(e,S,r,e=>n(e,S,r)),t.error)throw new Bn(t.error,t.meta);let{data:s}=t;o&&!rr(v,"rawResponse")&&(s=await ar(o,t.data,"rawResponseSchema",t.meta));let c=await I(s,t.meta,e);return i&&!rr(v,"response")&&(c=await ar(i,c,"responseSchema",t.meta)),{...t,data:c}}if(k&&"infiniteQueryOptions"in w){const{infiniteQueryOptions:x}=w,{maxPages:R=1/0}=x,M=e.refetchCachedPages??x.refetchCachedPages??!0;let K;const U={pages:[],pageParams:[]},_=s.selectQueryEntry(y(),e.queryCacheKey)?.data,D=m(e,y())&&!e.direction||!_?U:_;if("direction"in e&&e.direction&&D.pages.length){const T="backward"===e.direction,O=(T?cr:sr)(x,D,e.originalArgs);K=await E(D,O,R,T)}else{const{initialPageParam:N=x.initialPageParam}=e,B=_?.pageParams??[],q=B[0]??N,L=B.length;if(K=await E(D,q,R),A&&(K={data:K.data.pages[0]}),M)for(let F=1;F<L;F++){const z=sr(x,K.data,e.originalArgs);K=await E(K.data,z,R)}}C=K}else C=await P(e.originalArgs);return b&&!rr(v,"meta")&&C.meta&&(C.meta=await ar(b,C.meta,"metaSchema",C.meta)),i(C.data,ir({fulfilledTimeStamp:Date.now(),baseQueryMeta:C.meta}))}catch(j){let H=j;if(H instanceof Bn){let V=f(w,"transformErrorResponse");const{rawErrorResponseSchema:$,errorResponseSchema:Q}=w;let{value:W,meta:X}=H;try{$&&!rr(v,"rawErrorResponse")&&(W=await ar($,W,"rawErrorResponseSchema",X)),b&&!rr(v,"meta")&&(X=await ar(b,X,"metaSchema",X));let G=await V(W,X,e.originalArgs);return Q&&!rr(v,"errorResponse")&&(G=await ar(Q,G,"errorResponseSchema",X)),o(G,ir({baseQueryMeta:X}))}catch(J){H=J}}try{if(H instanceof nr){const Y={endpoint:e.endpointName,arg:e.originalArgs,type:e.type,queryCacheKey:k?e.queryCacheKey:void 0};w.onSchemaFailure?.(H,Y),c?.(H,Y);const{catchSchemaFailure:Z=l}=w;if(Z)return o(Z(H,Y),ir({baseQueryMeta:H._bqMeta}))}}catch(ee){H=ee}throw console.error(H),H}};function m(e,t){const n=s.selectQueryEntry(t,e.queryCacheKey),r=s.selectConfig(t).refetchOnMountOrArgChange,a=n?.fulfilledTimeStamp,o=e.forceRefetch??(e.subscribe&&r);return!!o&&(!0===o||(Number(new Date)-Number(a))/1e3>=o)}const y=()=>t.createAsyncThunk(`${e}/executeQuery`,p,{getPendingMeta({arg:e}){const t=r[e.endpointName];return ir({startedTimeStamp:Date.now(),...Xn(t)?{direction:e.direction}:{}})},condition(e,{getState:t}){const n=t(),a=s.selectQueryEntry(n,e.queryCacheKey),o=a?.fulfilledTimeStamp,i=e.originalArgs,c=a?.originalArgs,l=r[e.endpointName],d=e.direction;return!(!tr(e)&&("pending"===a?.status||!m(e,n)&&(!Wn(l)||!l?.forceRefetch?.({currentArg:i,previousArg:c,endpointState:a,state:n}))&&o&&!d))},dispatchConditionRejection:!0}),g=y(),w=y(),b=t.createAsyncThunk(`${e}/executeMutation`,p,{getPendingMeta:()=>ir({startedTimeStamp:Date.now()})});function v(e){return t=>t?.meta?.arg?.endpointName===e}return{queryThunk:g,mutationThunk:b,infiniteQueryThunk:w,prefetch:(e,t,n={})=>(r,a)=>{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 o.endpoints[e].initiate(t,r)},l=o.endpoints[e].select(t)(a());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)=>(a,i)=>{const s=o.endpoints[e].select(t)(i()),c={patches:[],inversePatches:[],undo:()=>a(o.util.patchQueryData(e,t,c.inversePatches,r))};if(s.status===En)return c;let l;if("data"in s)if(mt(s.data)){const[e,t,r]=mn(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||a(o.util.patchQueryData(e,t,c.patches,r)),c},upsertQueryData:(e,t,n)=>r=>r(o.endpoints[e].initiate(t,{subscribe:!1,forceRefetch:!0,[er]:()=>({data:n})})),patchQueryData:(e,t,n,s)=>(c,l)=>{const d=r[e],u=a({queryArgs:t,endpointDefinition:d,endpointName:e});if(c(o.internalActions.queryResultPatched({queryCacheKey:u,patches:n})),!s)return;const h=o.endpoints[e].select(t)(l()),f=Jn(d.providesTags,h.data,void 0,t,{},i);c(o.internalActions.updateProvidedBy([{queryCacheKey:u,providedTags:f}]))},buildMatchThunkActions:function(e,n){return{matchPending:t.isAllOf(t.isPending(e),v(n)),matchFulfilled:t.isAllOf(t.isFulfilled(e),v(n)),matchRejected:t.isAllOf(t.isRejected(e),v(n))}}}}({baseQuery:r,reducerPath:o,context:m,api:n,serializeQueryArgs:i,assertTagType:y,selectors:g,onSchemaFailure:h,catchSchemaFailure:f,skipSchemaValidation:p}),{reducer:K,actions:U}=mr({context:m,queryThunk:S,mutationThunk:C,serializeQueryArgs:i,reducerPath:o,assertTagType:y,config:{refetchOnFocus:l,refetchOnReconnect:d,refetchOnMountOrArgChange:c,keepUnusedDataFor:s,reducerPath:o,invalidationBehavior:u}});Sr(n.util,{patchQueryData:E,updateQueryData:P,upsertQueryData:x,prefetch:R,resetApiState:U.resetApiState,upsertQueryEntries:U.cacheEntriesUpserted}),Sr(n.internalActions,U);const _=new WeakMap,D=e=>On(_,e,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:T,buildInitiateInfiniteQuery:O,buildInitiateMutation:N,getRunningMutationThunk:B,getRunningMutationsThunk:q,getRunningQueriesThunk:L,getRunningQueryThunk:F}=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=Zn(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=>Tn(s(e))},getRunningMutationsThunk:function(){return e=>Tn(c(e))}};function h(r,o){const i=(c,{subscribe:d=!0,forceRefetch:h,subscriptionOptions:f,[er]:p,...m}={})=>(y,g)=>{const w=e({queryArgs:c,endpointDefinition:o,endpointName:r});let b;const v={...m,type:Vn,subscribe:d,forceRefetch:h,subscriptionOptions:f,endpointName:r,originalArgs:c,queryCacheKey:w,[er]:p};if(Wn(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:A,abort:C}=I,E=S.requestId!==A,P=s(y)?.get(w),x=()=>k(g()),R=Object.assign(p?I.then(x):E&&!P?Promise.resolve(S):Promise.all([P,I]).then(x),{arg:c,requestId:A,subscriptionOptions:f,queryCacheKey:w,abort:C,async unwrap(){const e=await R;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:A}))},updateSubscriptionOptions(e){R.subscriptionOptions=e,y(u({endpointName:r,requestId:A,queryCacheKey:w,options:e}))}});if(!P&&!E&&!p){const e=s(y);e.set(w,R),R.then(()=>{e.delete(w)})}return R};return i}}({queryThunk:S,mutationThunk:C,infiniteQueryThunk:A,api:n,serializeQueryArgs:i,context:m,getInternalState:D});Sr(n.util,{getRunningMutationThunk:B,getRunningMutationsThunk:q,getRunningQueryThunk:F,getRunningQueriesThunk:L});const{middleware:z,actions:j}=Ur({reducerPath:o,context:m,queryThunk:S,mutationThunk:C,infiniteQueryThunk:A,api:n,assertTagType:y,selectors:g,getRunningQueryThunk:F,getInternalState:D});return Sr(n.util,j),Sr(n,{reducer:K,middleware:z}),{name:_r,injectEndpoint(e,t){const r=n,a=r.endpoints[e]??={};Wn(t)&&Sr(a,{name:e,select:v(e,t),initiate:T(e,t)},M(S,e)),t.type===$n&&Sr(a,{name:e,select:I(),initiate:N(e)},M(C,e)),Xn(t)&&Sr(a,{name:e,select:k(e,t),initiate:O(e,t)},M(S,e))}}}}))());const Tr="0123456789abcdef",Or=new Array(64),Nr=new Array(128),Br=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)}),qr=(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)}),Lr=e=>{const t=e.length,n=t===m?Nr:32===t?Or:new Array(2*t);let r=0;for(let a=0;a<t;a++){const t=e[a];n[r++]=Tr[t>>4],n[r++]=Tr[15&t]}return n.join("")},Fr=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},zr=(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 jr=()=>{const e=(b+v)*Uint8Array.BYTES_PER_ELEMENT,t=zr(e);return new WebAssembly.Memory({initial:t,maximum:t})},Hr=()=>{const e=(x+R)*Uint8Array.BYTES_PER_ELEMENT,t=zr(e);return new WebAssembly.Memory({initial:t,maximum:t})},Vr=()=>{const e=(b+v+w)*Uint8Array.BYTES_PER_ELEMENT,t=zr(e);return new WebAssembly.Memory({initial:t,maximum:t})},$r=e=>{const t=(e+g+v+m)*Uint8Array.BYTES_PER_ELEMENT,n=zr(t);return new WebAssembly.Memory({initial:n,maximum:n})},Qr=e=>{const t=(e+g+b)*Uint8Array.BYTES_PER_ELEMENT,n=zr(t);return new WebAssembly.Memory({initial:n,maximum:n})},Wr=()=>{const e=zr(0);return new WebAssembly.Memory({initial:e,maximum:e})},Xr=e=>{const t=zr((2*e+3)*m);return new WebAssembly.Memory({initial:t,maximum:t})},Gr=e=>{const t=zr(e*m+e*(m+1)+3*m);return new WebAssembly.Memory({initial:t,maximum:t})},Jr=e=>{const t=(78643200+e+w+A)*Uint8Array.BYTES_PER_ELEMENT,n=zr(t);return new WebAssembly.Memory({initial:n,maximum:n})};function Yr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Zr,ea={exports:{}};var ta=(Zr||(Zr=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=_(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 A(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 C(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 A(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=[],R=(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 O[e](...r)},M=e=>{I("OOM")},K=(e,t)=>Math.ceil(e/t)*t,U=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 _,D,T,O={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"}}}},N={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)=>R(e,t,n),f:e=>{var t=w.length,n=1073741824;(e>>>=0)>n&&M();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,K(Math.max(e,a),65536));if(U(o))return!0}M()},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,_=e.Q,D=e.R,e.__indirect_function_table}(T=e.exports),T}var t={a:N};h??=S();var r=function(t){return e(t.instance)}(await C(c,h,t));return r}(),await async function(){d||(v=!0,T.h())}(),n});e.exports=n,e.exports.default=n}(ea)),ea.exports),na=Yr(ta);const ra=new Uint32Array(1),aa=()=>{const e=globalThis.crypto;if("function"!=typeof e?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");try{return e.getRandomValues(ra),ra[0]>>>0}finally{ra[0]=0}},oa=(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 ia="0.14.2";let sa=new URL(`https://cdn.p2party.com/@${ia}/libcrypto.wasm`),ca=!1;const la={integrity:"sha384-pBMyUqQ3KBztxgeJMgDFZeohfj9QlAFNwt4/gRlqT0vlZ2kbkKxv+q5DwbZOBuUP"},da=e=>{if(ca)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:");sa=t},ua=async e=>{ca=!0;const t=await(async()=>{const e=await fetch(sa,la);if(!e.ok)throw new Error(`Unable to load p2party ${ia} WASM: HTTP ${String(e.status)}`);return await e.arrayBuffer()})();return await na({wasmBinary:t,wasmMemory:e,getRandomValue:aa})},ha=(e,t)=>{t.fill(0),e._free(t.byteOffset)},fa=async e=>{const t=e?.wasmMemory??jr(),n=e??await ua(t),r=n._malloc(b),a=new Uint8Array(t.buffer,r,b),o=n._malloc(v),i=new Uint8Array(t.buffer,o,v),s=n._malloc(w),c=new Uint8Array(t.buffer,s,w);try{oa(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),ha(n,i),ha(n,c)}},pa=async(e,t,n)=>{if(t.length!==v)throw new Error(`Ed25519 secret key must be ${String(v)} bytes`);const r=e.length,a=n?n.wasmMemory:$r(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(g),l=new Uint8Array(a.buffer,c,g),d=o._malloc(v),u=new Uint8Array(a.buffer,d,v);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),ha(o,u)}},ma=async(e,t,n,r)=>{const a=e.length,o=r?r.wasmMemory:Qr(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(g),d=new Uint8Array(o.buffer,l,g);d.set(t);const u=i._malloc(b),h=new Uint8Array(o.buffer,u,b);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},ya=/^[0-9a-f]{64}$/,ga=e=>"string"==typeof e&&ya.test(e),wa=(e,t="Ed25519 identity")=>{if(!ga(e))throw new Error(`${t} must be 32-byte lowercase hexadecimal`)},ba=(e,t)=>{if(wa(e,"Self Ed25519 identity"),wa(t,"Peer Ed25519 identity"),e===t)throw new Error("Cannot assign a protocol role to the same Ed25519 identity");return e<t},va='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',ka=new Blob([va],{type:"application/javascript"}),Ia=new Worker(URL.createObjectURL(ka),{type:"module"});let Sa=0;const Aa=new Map;Ia.onmessage=e=>{const{id:t,result:n,error:r}=e.data,a=Aa.get(t);a&&(Aa.delete(t),r?a.reject(r):a.resolve(n))};const Ca=e=>{const t=[...Aa.values()];Aa.clear();for(const n of t)n.reject(e)};function Ea(e,...t){return new Promise((n,r)=>{const a=++Sa;Aa.set(a,{resolve:n,reject:r}),Ia.postMessage({id:a,method:e,args:t})})}Ia.onerror=e=>{Ca(new Error(`p2party: the database worker failed: ${e.message||"unknown error"}`))},Ia.onmessageerror=()=>{Ca(new Error("p2party: a database worker message could not be deserialized"))};const Pa=(e,t)=>Ea("getDBAddressBookEntry",e,t),xa=async(e,t)=>{try{return await Ea("getDBPeerIsBlacklisted",e,t)}catch(e){return console.error("p2party: blacklist lookup failed; treating this peer as blocked",e),!0}},Ra=()=>Ea("getAllDBUniqueRooms"),Ma=(e,t)=>Ea("getDBMessageData",e,t),Ka=e=>Ea("getDBRoomMessageData",e),Ua=(e,t)=>Ea("getDBNewChunk",e,t),_a=e=>Ea("setDBChunk",e),Da=e=>Ea("storeReceiveChunk",e),Ta=e=>Ea("deleteReceiveTransfer",e),Oa=e=>Ea("setDBNewChunk",e),Na=e=>Ea("deleteDBNewChunk",e),Ba=(e,t,n)=>Ea("deleteDBSendQueue",e,t,n),qa=(e,t)=>Ea("deleteRatchetSession",e,t),La=(e,t)=>Ea("getPinAttemptState",e,t),Fa=()=>Ea("getIdentityX25519"),za=()=>Ea("deleteIdentityX25519"),ja=e=>Ea("setIdentityEd25519",e),Ha=()=>Ea("deleteIdentityEd25519"),Va=(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!==m)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+=Lr(o),a+="~",a+="string"==typeof t?t:Lr(t),n(a)}catch(e){r(e)}}),$a=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=Fr(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=Fr(n[1]);if(i.length!==m)throw new Error("Merkle root has invalid length");t({channelLabel:o,merkleRoot:i,merkleRootHex:n[1]})}catch(e){n(e)}}),Qa=new Map,Wa=(e,t,n)=>`${e}\0${t}\0${n}`,Xa=(e,t,n)=>{const r=Wa(e,t,n);let a=Qa.get(r);return a||(a={acked:new Set,complete:!1},Qa.set(r,a)),a},Ga=(e,t,n)=>new Set(Xa(e,t,n).acked),Ja=(e,t,n)=>Xa(e,t,n).acked.size,Ya=(e,t,n)=>{const r=Xa(e,t,n);return!r.complete&&(r.complete=!0,!0)},Za=(e,t,n)=>Qa.get(Wa(e,t,n))?.complete??!1,eo=(e,t,n)=>{Qa.delete(Wa(e,t,n))},to=async(e,t,n,r,a)=>{const o=Date.now()+r;for(;Date.now()<o&&!Za(e,t,n)&&!a?.aborted;)await new Promise(e=>setTimeout(e,200));return!a?.aborted&&Za(e,t,n)},no=async(e,t,n,r,a)=>{try{const o=Lr(e),{merkleRootHex:i}=await $a(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 Ya(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)=>Ea("getDBNewChunkByReceipt",e,t))(i,o),t=e?.chunkIndex??-1;if(e&&e.transferId===u&&t>-1){const e=((e,t,n,r)=>{const a=Xa(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}},ro=e=>{const t=new Uint8Array(_);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+=m;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},ao=e=>{if(e.length!==_)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+m);t+=m;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 y=new DataView(e.buffer,e.byteOffset+t,8),g=Number(y.getBigUint64(0,!1));t+=8;const w=new DataView(e.buffer,e.byteOffset+t,8);return{schemaVersion:r,messageType:a,hash:o,totalSize:s,date:d,name:h,chunkStartIndex:p,chunkEndIndex:g,chunkIndex:Number(w.getBigUint64(0,!1))}},oo={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},io={Text:"Text",Image:"Image",Document:"Document",Audio:"Audio",Video:"Video",Compressed:"Compressed",Code:"Code",Ebook:"Ebook",Font:"Font",Executable:"Executable",Unknown:"Unknown"},so=e=>{switch(e){case oo.Text:return"text/plain";case oo.ImagePNG:return"image/png";case oo.ImageJPEG:case oo.ImageJPG:return"image/jpeg";case oo.ImageGIF:return"image/gif";case oo.ImageBMP:return"image/bmp";case oo.ImageTIFF:return"image/tiff";case oo.ImageSVG:return"image/svg+xml";case oo.ImageWEBP:return"image/webp";case oo.ImageHEIC:return"image/heic";case oo.ImageICO:return"image/vnd.microsoft.icon";case oo.DocumentPDF:return"application/pdf";case oo.DocumentDOC:return"application/msword";case oo.DocumentDOCX:return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case oo.DocumentXLS:return"application/vnd.ms-excel";case oo.DocumentXLSX:return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case oo.DocumentPPT:return"application/vnd.ms-powerpoint";case oo.DocumentPPTX:return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case oo.DocumentTXT:return"text/plain";case oo.DocumentRTF:return"application/rtf";case oo.DocumentODT:return"application/vnd.oasis.opendocument.text";case oo.AudioMP3:return"audio/mpeg";case oo.AudioWAV:return"audio/wav";case oo.AudioAAC:return"audio/aac";case oo.AudioFLAC:return"audio/flac";case oo.AudioOGG:return"audio/ogg";case oo.AudioM4A:return"audio/mp4";case oo.VideoMP4:return"video/mp4";case oo.VideoAVI:return"video/x-msvideo";case oo.VideoMKV:return"video/x-matroska";case oo.VideoMOV:return"video/quicktime";case oo.VideoWMV:return"video/x-ms-wmv";case oo.VideoFLV:return"video/x-flv";case oo.VideoWEBM:return"video/webm";case oo.CompressedZIP:return"application/zip";case oo.CompressedRAR:return"application/vnd.rar";case oo.Compressed7Z:return"application/x-7z-compressed";case oo.CompressedTAR:return"application/x-tar";case oo.CompressedGZ:return"application/gzip";case oo.CodeHTML:return"text/html";case oo.CodeCSS:return"text/css";case oo.CodeJS:case oo.CodeJSX:return"application/javascript";case oo.CodeTS:case oo.CodeTSX:return"application/typescript";case oo.CodeJSON:return"application/json";case oo.CodeXML:return"application/xml";case oo.CodePY:return"text/x-python";case oo.CodeJAVA:return"text/x-java-source";case oo.CodeC:return"text/x-c";case oo.CodeCPP:return"text/x-c++";case oo.CodeCS:return"text/plain";case oo.CodeRB:return"text/x-ruby";case oo.CodePHP:return"application/x-httpd-php";case oo.CodeSQL:return"application/sql";case oo.EbookEPUB:return"application/epub+zip";case oo.EbookMOBI:return"application/x-mobipocket-ebook";case oo.EbookAZW:return"application/vnd.amazon.ebook";case oo.FontTTF:return"font/ttf";case oo.FontOTF:return"font/otf";case oo.ExecutableEXE:return"application/vnd.microsoft.portable-executable";case oo.ExecutableDMG:return"application/x-apple-diskimage";case oo.ExecutableAPK:return"application/vnd.android.package-archive";default:return"application/octet-stream"}},co=(new TextEncoder).encode("p2party/protocol-v3/chunk-receipt/v1\0"),lo=async(e,t,n)=>{if(e.length!==m)throw new Error("Chunk receipt Merkle root must be 64 bytes");if(n.length!==m)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(co.length+e.length+8+n.length);let a=0;return r.set(co,a),a+=co.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(R);if(0!==e._x25519_keypair(t,n))throw e._free(t),ha(e,new Uint8Array(e.wasmMemory.buffer,n,R)),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,R));return e._free(t),ha(e,new Uint8Array(e.wasmMemory.buffer,n,R)),{publicKey:r,secretKey:a}},ho=async e=>{const t=e?.wasmMemory??Hr(),n=e??await ua(t);return uo(n)},fo=(e,t,n)=>{const r=n._malloc(x),a=n._malloc(R),o=n._malloc(x);new Uint8Array(n.wasmMemory.buffer,a,R).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(ha(n,new Uint8Array(n.wasmMemory.buffer,r,x)),ha(n,new Uint8Array(n.wasmMemory.buffer,a,R)),n._free(o),!i)throw new Error("x25519_dh failed (identity point)");return i},po=(e,t,n)=>{const r=Math.max(e.length,1),a=Math.max(t.length,1),o=n._malloc(p),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,p))}finally{ha(n,new Uint8Array(n.wasmMemory.buffer,o,p)),ha(n,new Uint8Array(n.wasmMemory.buffer,i,r)),ha(n,new Uint8Array(n.wasmMemory.buffer,s,a))}},mo=(e,t,n,r)=>{const a=r._malloc(n),o=r._malloc(p),i=r._malloc(Math.max(t.length,1));try{new Uint8Array(r.wasmMemory.buffer,o,p).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{ha(r,new Uint8Array(r.wasmMemory.buffer,a,n)),ha(r,new Uint8Array(r.wasmMemory.buffer,o,p)),r._free(i)}},yo=(new TextEncoder).encode("p2party-rk-v1"),go=(new TextEncoder).encode("p2party-ck-v1"),wo=(new TextEncoder).encode("p2party-mk-v1"),bo=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),vo=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},ko=(e,t,n)=>{const r=po(e,t,n),a=mo(r,yo,64,n);r.fill(0);const o=a.slice(0,32),i=a.slice(32,64);return a.fill(0),{rootKey:o,chainKey:i}},Io=(e,t)=>{const n=po(e,wo,t),r=po(e,go,t),a=n.slice(0,32),o=r.slice(0,32);return n.fill(0),r.fill(0),{chainKey:o,messageKey:a}},So=(e,t,n,r,a=X)=>{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=fo(i.dhSelfSec,i.dhRemotePub,r),t=ko(i.rootKey,e,r);e.fill(0),i.rootKey.fill(0),i.rootKey=t.rootKey,i.sendingChainKey=t.chainKey}return i},Ao=(e,t)=>{if(!e.sendingChainKey)throw new Error("ratchet: no sending chain");const{chainKey:n,messageKey:r}=Io(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}},Co=(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}=Io(e.receivingChainKey,n);e.receivingChainKey.fill(0),e.receivingChainKey=t,e.skipped.set(`${bo(e.dhRemotePub)}:${e.Nr}`,r),e.Nr+=1}if(e.skipped.size>G)for(const t of e.skipped.keys()){if(e.skipped.size<=G)break;e.skipped.get(t)?.fill(0),e.skipped.delete(t)}}},Eo=(e,t,n)=>{e.PN=e.Ns,e.Ns=0,e.Nr=0,e.dhRemotePub=Uint8Array.from(t.dhPub);let r=fo(e.dhSelfSec,e.dhRemotePub,n),a=ko(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=fo(e.dhSelfSec,e.dhRemotePub,n),a=ko(e.rootKey,r,n),r.fill(0),e.rootKey.fill(0),e.rootKey=a.rootKey,e.sendingChainKey?.fill(0),e.sendingChainKey=a.chainKey},Po=(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=`${bo(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))&&(Co(e,t.PN,n),Eo(e,t,n)),t.N<e.Nr)throw new Error("ratchet: message key already consumed");Co(e,t.N,n);const{chainKey:a,messageKey:o}=Io(e.receivingChainKey,n);return e.receivingChainKey.fill(0),e.receivingChainKey=a,e.Nr+=1,o},xo=e=>e.slice().buffer,Ro=e=>e?e.slice().buffer:null,Mo=e=>({rootSuite:e.rootSuite,rootKey:xo(e.rootKey),sendingChainKey:Ro(e.sendingChainKey),receivingChainKey:Ro(e.receivingChainKey),dhSelfPub:xo(e.dhSelfPub),dhSelfSec:xo(e.dhSelfSec),dhRemotePub:Ro(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:vo(e.slice(0,n)).slice().buffer,n:Number(e.slice(n+1)),messageKey:t.slice().buffer}})}),Ko=e=>{const t=new Map;for(const n of e.skippedMessageKeys){const e=new Uint8Array(n.dhPub);t.set(`${bo(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}},Uo=e=>Ko(Mo(e)),_o=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)},Do=(e,t)=>{if(e.rootSuite!==t.rootSuite)throw new Error("ratchet: cannot adopt a different root suite");_o(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},To=(1n<<64n)-1n,Oo=(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)},No=(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)},Bo=(e,t,n=0n)=>{if(e.dhPub.length!==F)throw new Error("chunkFrame: dhPub must be 32 bytes");if(t.length!==z)throw new Error("chunkFrame: nonce must be 12 bytes");const r=new Uint8Array(69);return r[0]=2,r.set(e.dhPub,1),Oo(r,33,e.N),Oo(r,41,e.PN),((e,t,n)=>{if("bigint"!=typeof n||n<0n||n>To)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},qo=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:No(e,33),PN:No(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},Lo=k,Fo=(1n<<64n)-1n,zo=(new TextEncoder).encode("p2party/pq-message-key/v1\0"),jo=(e,t,n)=>{if(!(e instanceof Uint8Array)||e.length!==n)throw new Error(`pqMessageKey: ${t} must be ${String(n)} bytes`)},Ho=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new Error(`pqMessageKey: ${t} is outside the safe u64 range`)},Vo=(e,t)=>{if("string"!=typeof(n=e.rootSuite)||!W.includes(n))throw new Error("pqMessageKey: unsupported root suite");var n;jo(e.rootKey,"rootKey",32),jo(e.binding,"binding",32),(e=>{if("bigint"!=typeof e||e<0n||e>Fo)throw new Error("pqMessageKey: epoch is outside the u64 range")})(e.epoch),jo(t.dhPub,"header.dhPub",F),Ho(t.N,"header.N"),Ho(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=zo.length+2+r.length+32+8+1+F+8+8,o=new Uint8Array(a);let i=0;o.set(zo,i),i+=zo.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+=F,s.setBigUint64(i,BigInt(t.N),!1),i+=8,s.setBigUint64(i,BigInt(t.PN),!1),o},$o=(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{jo(e,"classicalMessageKey",Lo);const a=Vo(t,n);return i=Uint8Array.from(t.rootKey),s=po(i,e,r),mo(s,a,Lo,r)}finally{e.fill(0),i?.fill(0),s?.fill(0)}},Qo=k,Wo=I,Xo=S,Go=m+57,Jo=(1n<<64n)-1n,Yo=(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>Jo)throw new Error("messageChunkCrypto: PQ epoch out of u64 range");return`${r}:${n.toString(10)}`},Zo=(e,t,n,r)=>{const a=e._malloc(M),o=e._malloc(N),i=e._malloc(m),s=e._malloc(Qo),c=new Uint8Array(e.wasmMemory.buffer,a,M),l=new Uint8Array(e.wasmMemory.buffer,o,N);c.fill(0),l.fill(0),c.set(t.subarray(0,M),0),new Uint8Array(e.wasmMemory.buffer,i,m).set(n),new Uint8Array(e.wasmMemory.buffer,s,Qo).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),ha(e,new Uint8Array(e.wasmMemory.buffer,s,Qo)),ha(e,l),{code:d,decrypted:u}},ei=(e,t,n,r,a,o)=>{if(r.length!==m)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const i=(()=>{const e=new Uint8Array(Wo);return crypto.getRandomValues(e),e})(),s=Bo(t,i,o?.epoch??0n),c=((e,t)=>{if(t.length<57)throw new Error("messageChunkCrypto: incomplete chunk frame header");const n=new Uint8Array(Go);return n.set(e,0),n.set(t.subarray(0,57),m),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+Xo,c=e._malloc(Qo),l=e._malloc(Wo),d=e._malloc(o),u=e._malloc(i),h=e._malloc(s);new Uint8Array(e.wasmMemory.buffer,c,Qo).set(t),new Uint8Array(e.wasmMemory.buffer,l,Wo).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(ha(e,new Uint8Array(e.wasmMemory.buffer,c,Qo)),e._free(l),ha(e,new Uint8Array(e.wasmMemory.buffer,d,o)),e._free(u),ha(e,new Uint8Array(e.wasmMemory.buffer,h,s)),!f)throw new Error("messageChunkCrypto: AEAD encrypt failed");return f})(a,o?l=$o(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)}},ti=(e,t,n,r,a,o)=>{if(r.length!==m)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const{header:i,pqEpoch:s}=qo(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=Yo(i.dhPub,i.N,o?s:void 0),f=n.get(h);if(f){const{code:e,decrypted:n}=Zo(a,t,r,f);return{decrypted:0===e?n:null,ok:0===e,stateAdvanced:!1}}const p=Uo(e);let y;try{y=ni(p,i,a),c&&(y=$o(y,c,i,a))}catch{return _o(p),{decrypted:null,ok:!1,stateAdvanced:!1}}const{code:g,decrypted:w}=Zo(a,t,r,y);return-2===g?(y.fill(0),_o(p),{decrypted:null,ok:!1,stateAdvanced:!1}):(Do(e,p),n.set(h,y),{decrypted:0===g?w:null,ok:0===g,stateAdvanced:!0})},ni=(e,t,n)=>{try{return Po(e,t,n)}catch(t){throw _o(e),t}},ri=(e,t)=>`${e.length}:${e}${t.length}:${t}`,ai=new Map,oi=new Map,ii=new WeakMap,si=async(e,t,n)=>{const r=ri(e,t),a=ai.get(r)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=a.catch(()=>{}).then(()=>i);ai.set(r,s),await a.catch(()=>{});try{return await n()}finally{o(),ai.get(r)===s&&ai.delete(r)}},ci=(e,t)=>{const n=ri(t,e.withPeerPublicKey),r=ii.get(e);if(r){if(oi.get(n)!==r)throw new Error("ratchet persistence: stale connection cannot reclaim edge");return}const a=Symbol(n);ii.set(e,a),oi.set(n,a)},li=(e,t)=>{const n=ri(t,e.withPeerPublicKey),r=ii.get(e);if(!r||oi.get(n)!==r)throw new Error("ratchet persistence: stale connection owner")},di=async(e,t,n,r,a=null)=>{const o=Mo(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=>Ea("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)=>si(t,n,()=>di(e,t,n,r,a)),hi=async(e,t,n,r,a=di,o=qa)=>si(n,e.withPeerPublicKey,async()=>{li(e,n);let i=!1;const s=e.serializeEdgeCryptoState?.()??null;try{i=!0,await a(t,n,e.withPeerPublicKey,e.withPeerId,s),li(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)}}),fi=new WeakMap,pi=async(e,t)=>{const n=fi.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>a);fi.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),fi.get(e)===o&&fi.delete(e)}},mi=async(e,t,n,r)=>pi(e,async()=>{const a=e.ratchetState;if(!a)throw new Error("ratchet persistence: no live ratchet state");const o=Uo(a);let i,s=!1;try{if(i=n(o),i.advanced){const n=i.stageEdgeCryptoState;if(r===ui)await si(t,e.withPeerPublicKey,async()=>{if(li(e,t),e.ratchetState!==a)throw new Error("ratchet persistence: live state changed");const r=n?.()??e.serializeEdgeCryptoState?.()??null;try{await di(o,t,e.withPeerPublicKey,e.withPeerId,r)}finally{r?.fill(0)}li(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");Do(a,o),s=!0}else _o(o);return i.commit?.(),i.value}catch(e){throw s||_o(o),i?.rollback?.(),e}}),yi=async(e,t,n,r=ui)=>mi(e,t,t=>{const r=Ao(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),gi=async(e,t,n,r,a=ui)=>mi(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),wi=new WeakMap,bi=async(e,t,n,r=gi)=>{let a=wi.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),wi.set(e,a);try{return await i}finally{a.get(n)===i&&a.delete(n),0===a.size&&wi.delete(e)}},vi=async(e,t,n,r,a=gi)=>!!(e=>void 0!==e&&Number.isSafeInteger(e.savedSize)&&Number.isSafeInteger(e.totalSize)&&e.savedSize>=0&&e.totalSize>0&&e.savedSize===e.totalSize)(r)&&bi(e,t,n,a),ki=()=>({date:new Date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!1,totalSize:0,messageType:oo.Text,filename:"",chunkHash:new Uint8Array,messageHash:new Uint8Array}),Ii=async(e,t,n=Da)=>{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)}},Si=async(e,t,n,r,a,o,i,s={})=>{if(i?.aborted)return ki();if(!r.ratchetState)return console.error("v3 receive: no ratchet state for peer"),ki();r.messageKeyCache||(r.messageKeyCache=r.pqHealingState?.activeReceiveKeys??new Map);const c=r.messageKeyCache;let l;try{const{header:t,pqEpoch:n}=qo(e);l=Yo(t.dhPub,t.N,r.pqHealingState?n:void 0)}catch{return ki()}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)=>mi(e,t,t=>{const i=e.pqHealingState,{header:s,pqEpoch:c}=qo(n),l=Yo(s.dhPub,s.N,i?c:void 0),d=new Map(r),u=ti(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>G;){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),ki()}if(!u||!d)return console.error("Could not decrypt or verify message"),ki();const h=Lr(a);((e,t,n)=>{e.messageKeyByMerkleRoot??=new Map,e.messageKeyByMerkleRoot.set(t,n)})(r,h,l);try{if(i?.aborted)return ki();const e=d.subarray(0,_),o=d.slice(_,_+m),c=d.subarray(_+D),l=ao(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!==m)throw new Error("Invalid metadata hash");if(!Number.isSafeInteger(e.totalSize)||e.totalSize<1||e.totalSize>K)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>M?0:l.chunkEndIndex-l.chunkStartIndex,g=()=>({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 g();if(f=l.chunkStartIndex,p=l.chunkEndIndex,y=c.length,!(Number.isSafeInteger(f)&&Number.isSafeInteger(p)&&f>=0&&p>=f&&p<=y))return g();const w=await lo(a,l.chunkIndex,o);if(i?.aborted)return w.fill(0),ki();const b=so(l.messageType),v=c.slice(l.chunkStartIndex,l.chunkEndIndex),k=await Ii({schemaVersion:l.schemaVersion,roomId:t,fromPeerId:r.withPeerId,channelLabel:n,timestamp:l.date.getTime(),merkleRoot:h,hash:Lr(l.hash),filename:l.name,messageType:l.messageType,chunkIndex:l.chunkIndex,mimeType:b,leafHash:Lr(o),realLen:u,totalSize:l.totalSize,storage:l.messageType===oo.Text?"indexeddb":"opfs"},v,s.storeReceiveChunk);if(!k)return w.fill(0),ki();if(i?.aborted)return w.fill(0),ki();const I=k.complete;return{date:l.date,chunkIndex:l.chunkIndex,chunkSize:u,receivedFullSize:I,chunkAlreadyExists:!k.stored,totalSize:l.totalSize,messageType:l.messageType,filename:l.name,chunkHash:w,messageHash:l.hash}}catch(e){return console.error("Could not parse or store decrypted message",e),ki()}finally{d.fill(0)}var f,p,y},Ai=new Map,Ci=(e,t)=>`${e}\0${t}`,Ei=(e,t)=>{const n=Ci(e,t);let r=Ai.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")}},Ai.set(n,r)}return r},Pi=(e,t)=>Ei(e,t).promise,xi=(e,t,n)=>Ai.get(Ci(e,t))?.lease===n,Ri=(e,t,n)=>{const r=Ai.get(Ci(e,t));return"open"===r?.outcome&&(void 0===n||r.lease===n)},Mi=(e,t,n,r)=>{const a=Ei(e,t);return(!r||a.lease===r)&&(a.settled||(a.settled=!0,a.outcome="rejected",a.reject(n)),!0)},Ki=e=>{if(e.length!==B)throw new Error("Receipt token must be exactly 64 bytes");const t=new Uint8Array(q);return t[0]=3,t.set(e,1),t},Ui=(e,t)=>"open"===e.readyState&&(e.send(Ki(t).buffer),!0),_i=async(e,t)=>{let n=0;for(const r of t){for(;"open"===e.readyState&&e.bufferedAmount>=U;)await new Promise(e=>setTimeout(e,25));if("open"!==e.readyState)return!1;e.send(Ki(r).buffer),n++,32===n&&(n=0,await new Promise(e=>setTimeout(e,10)))}return"open"===e.readyState},Di=new WeakMap,Ti=(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=Di.get(e);return t||(t={pending:[],drainJobActive:!1,jobSequence:0},Di.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 Oi(e,r,a),!0},Oi=(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,Oi(e,t,n)})},Ni=e=>{const t=Di.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,Di.delete(e)}},Bi=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?.()??qi;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!==j)throw new Error("coverTransfer: sealed transfer cell is not the uniform length");return o}}},qi=new Set,Li=e=>{if(e.byteLength<32)return`${String(e.byteLength)}:${Lr(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")},Fi=new Map,zi=new Map,ji=new WeakMap,Hi=new Map,Vi=(e,t)=>`${String(e.length)}:${e}${t}`,$i=(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()},Qi=(e,t)=>t.value||0!==e.length?new Promise(e=>{t.idleWaiters??=new Set,t.idleWaiters.add(e)}):Promise.resolve(),Wi=(e,t,n,r)=>{const a=Math.max(0,(ji.get(e)??0)+r);0===a?ji.delete(e):ji.set(e,a);const o=Vi(t,n),i=Math.max(0,(zi.get(o)??0)+r);0===i?zi.delete(o):zi.set(o,i)},Xi=async(e,t)=>{const n=Fi.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.then(()=>a);Fi.set(e,o),await n;try{return await t()}finally{r(),Fi.get(e)===o&&Fi.delete(e)}},Gi=(e,t)=>{const n=Vi(e.roomId,e.peerId),r=Math.max(0,(Hi.get(n)??0)+t);0===r?Hi.delete(n):Hi.set(n,r)},Ji=async(e,t)=>{if(e.draining||e.released)return;e.draining=!0;const n=Vi(e.roomId,e.peerId);try{for(;!e.released;){const r=e.pending.shift();if(!r)break;Gi(e,-1);try{await Xi(n,()=>t(r))}finally{e.seen.delete(Li(r))}}}catch(e){console.error(e)}finally{e.draining=!1,!e.released&&e.pending.length>0&&Ji(e,t)}},Yi=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(!xi(n,r,u))return{receivedFullSize:!1};if(await Pi(n,r),d?.aborted)return{receivedFullSize:!1};if(!xi(n,r,u))return{receivedFullSize:!1};const h=await Si(e,n,a,c,i,l,d),{date:f,chunkSize:p,chunkIndex:y,receivedFullSize:g,chunkAlreadyExists:w,totalSize:b,messageType:v,filename:k,messageHash:I}=h;if(d?.aborted)return{receivedFullSize:!1};c?.coverRuntime||((e,t)=>{if(e.totalSize>0&&e.chunkHash.length===m&&e.chunkIndex>-1&&e.chunkSize>0)return!!t&&Ui(t,e.chunkHash);if("open"!==t?.readyState)return!1;const n=new Uint8Array(m);crypto.getRandomValues(n),Ui(t,n)})(h,s);const S=Lr(I);return g&&c?.coverRuntime&&Ti(c,i,i),g?(await(e=>Ea("closeReceiveFile",e))(o),t.dispatch(Le({roomId:n,merkleRootHex:o,sha512Hex:S,fromPeerId:r,totalSize:b,messageType:v,filename:k,channelLabel:a,timestamp:f.getTime(),alsoSendFinishedMessage:!0})),(e=>void 0===e?.coverRuntime)(c)&&s&&Ui(s,I)):p>0&&y>-1&&!w&&t.dispatch(qe({roomId:n,merkleRootHex:o,sha512Hex:S,fromPeerId:r,chunkSize:p,totalSize:b,messageType:v,filename:k,channelLabel:a,timestamp:f.getTime()})),t.dispatch(Fe({roomId:n,merkleRootHex:o,real:p>0&&y>-1&&!w})),{receivedFullSize:g}}catch(e){return console.error(e),{receivedFullSize:!1}}return{receivedFullSize:!1}},Zi=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=Vi(a,o);try{for(;!n.released&&!h?.aborted;){const t=e.pop();if(!t)break;Wi(e,a,o,-t.byteLength),await Xi(f,async()=>Yi(t,r,a,o,i,s,c,l,d,u,h))}}finally{n.value=!1,e.length>0&&!n.released&&!h?.aborted?Zi(e,t,n,r,a,o,i,s,c,l,d,u,h):$i(e,n)}},es=e=>Object.freeze({...e,wasmExports:Object.freeze({...e.wasmExports})}),ts=es({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"}}),ns=es({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"}}),rs=es({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"}}),as=Object.freeze({512:ts,768:ns,1024:rs}),os=e=>{const t=as[e];if(void 0===t)throw new RangeError(`unsupported ML-KEM parameter set: ${String(e)}`);return t},is=(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`)},ss=(e,t,n,r)=>{const a=e._malloc(n);if(0===a)throw new Error(`${t.standardName}: failed to allocate ${r}`);return a},cs=(e,t,n)=>new Uint8Array(e.wasmMemory.buffer,t,n),ls=(e,t)=>{void 0!==t&&e._free(t)},ds=(e,t,n)=>{void 0!==t&&ha(e,cs(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=ss(e,t,t.publicKeyBytes,"public key"),r=ss(e,t,t.secretKeyBytes,"secret key"),a=ss(e,t,t.keyPairRandomBytes,"key-generation randomness");const o=cs(e,a,t.keyPairRandomBytes);oa(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(cs(e,n,t.publicKeyBytes)),Uint8Array.from(cs(e,r,t.secretKeyBytes)))}finally{ls(e,n),ds(e,r,t.secretKeyBytes),ds(e,a,t.keyPairRandomBytes)}}async encapsulate(e){await Promise.resolve();const t=this.#e,n=this.suite;let r,a,o,i;is(e,`${n.standardName} public key`,n.publicKeyBytes);try{r=ss(t,n,n.ciphertextBytes,"ciphertext"),a=ss(t,n,n.sharedSecretBytes,"shared secret"),o=ss(t,n,n.publicKeyBytes,"public key"),i=ss(t,n,n.encapsRandomBytes,"encapsulation randomness"),cs(t,o,n.publicKeyBytes).set(e);const s=cs(t,i,n.encapsRandomBytes);oa(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(cs(t,r,n.ciphertextBytes)),Uint8Array.from(cs(t,a,n.sharedSecretBytes)))}finally{ls(t,r),ds(t,a,n.sharedSecretBytes),ls(t,o),ds(t,i,n.encapsRandomBytes)}}async decapsulate(e,t){await Promise.resolve();const n=this.#e,r=this.suite;let a,o,i;is(e,`${r.standardName} ciphertext`,r.ciphertextBytes),is(t,`${r.standardName} secret key`,r.secretKeyBytes);try{a=ss(n,r,r.sharedSecretBytes,"shared secret"),o=ss(n,r,r.ciphertextBytes,"ciphertext"),i=ss(n,r,r.secretKeyBytes,"secret key"),cs(n,o,r.ciphertextBytes).set(e),cs(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(cs(n,a,r.sharedSecretBytes)))}finally{ds(n,a,r.sharedSecretBytes),ls(n,o),ds(n,i,r.secretKeyBytes)}}}const hs=(e,t)=>{const n=os(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)},fs=32,ps=32,ms=64,ys=new Uint8Array([80,50,81,72]),gs=(new TextEncoder).encode("p2party/pq-healing/root/v1\0"),ws=(1n<<64n)-1n;class bs extends Error{code;constructor(e,t){super(`pqHealing: ${t}`),this.name="PqHealingError",this.code=e}}const vs=(e,t)=>{throw new bs(e,t)},ks=(e,t,n)=>e instanceof Uint8Array?e.length!==n?vs("invalid-record",`${t} must be exactly ${String(n)} bytes`):e:vs("invalid-record",`${t} must be a Uint8Array`),Is=(e,t)=>{("bigint"!=typeof e||e<0n||e>ws)&&vs("overflow",`${t} is outside the unsigned 64-bit range`)},Ss=(e,t)=>{Is(e,t),e===ws&&vs("overflow",`${t} cannot advance beyond uint64`)},As=e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return vs("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")||vs("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 vs("invalid-record","advance acknowledgement fields must be enumerable data properties");const o=r.value,i=a.value;return"bigint"!=typeof o||"bigint"!=typeof i?vs("invalid-record","advance acknowledgement fields must be bigint values"):(Is(o,"advance acknowledgement epoch"),Is(i,"advance acknowledgement counter"),{epoch:o,advanceCounter:i})},Cs=(e,t,n)=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return vs("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 vs("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||vs("invalid-record",`${t}.${e} must be an enumerable data property`)}return r},Es=(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},Ps=e=>768===e?1:512===e?2:1024===e?3:vs("suite-mismatch","unsupported ML-KEM parameter set"),xs=e=>1===e?768:2===e?512:3===e?1024:vs("invalid-record","record has an unknown ML-KEM suite tag"),Rs=(e,t)=>Reflect.get(e,t),Ms=e=>{const t=os(e.parameterSet);e.standardName===t.standardName&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes&&Rs(e,"sharedSecretBytes")===t.sharedSecretBytes&&Rs(e,"keyPairRandomBytes")===t.keyPairRandomBytes&&Rs(e,"encapsRandomBytes")===t.encapsRandomBytes||vs("suite-mismatch","selected suite does not match its canonical FIPS 203 descriptor")},Ks=(e,t)=>{Ms(e),Ms(t),e.parameterSet===t.parameterSet&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes||vs("suite-mismatch","room-selected suite does not exactly match the ML-KEM backend")},Us=e=>ms+e.publicKeyBytes,_s=e=>ms+Us(e)+e.ciphertextBytes,Ds=(e,t,n)=>{Ms(t),ks(n,"binding",fs),ks(e,"ACK",64),Es(e.subarray(0,4),ys)||vs("invalid-record","ACK magic is invalid"),1!==e[4]&&vs("invalid-record","ACK version is unsupported"),3!==e[5]&&vs("invalid-record","ACK type is unexpected"),0!==e[7]&&vs("invalid-record","ACK reserved flags must be zero");xs(e[6])!==t.parameterSet&&vs("suite-mismatch","ACK suite differs from the authenticated room suite"),Es(e.subarray(8,40),n)||vs("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)&&vs("invalid-record","ACK reserved bytes must be zero"),{advanceCounter:r.getBigUint64(40,!1),epoch:r.getBigUint64(48,!1)}},Ts=(e,t,n,r,a,o,i)=>{ks(n,"binding",fs),Is(r,"sender counter"),Is(a,"from epoch"),Is(o,"to epoch"),a!==ws&&o===a+1n||vs("invalid-record","record must advance exactly one PQ epoch");const s=new Uint8Array(i);s.set(ys,0),s[4]=1,s[5]=e,s[6]=Ps(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},Os=(e,t,n,r)=>{e instanceof Uint8Array||vs("invalid-record","record must be a Uint8Array"),e.length<ms&&vs("invalid-record","record is shorter than its canonical header"),Es(e.subarray(0,4),ys)||vs("invalid-record","record magic is invalid"),1!==e[4]&&vs("invalid-record","record version is unsupported"),e[5]!==t&&vs("invalid-record","record type is unexpected"),0!==e[7]&&vs("invalid-record","record reserved flags must be zero");xs(e[6])!==n.parameterSet&&vs("suite-mismatch","record suite differs from the authenticated room suite");const a=e.subarray(8,40);void 0===r||Es(a,r)||vs("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!==ws&&c===s+1n||vs("invalid-record","record must advance exactly one PQ epoch"),{senderCounter:i,fromEpoch:s,toEpoch:c}},Ns=(e,t,n)=>{const r=Os(e,1,t,n);return e.length!==Us(t)&&vs("invalid-record","OFFER length is not canonical for its suite"),{...r,bytes:Uint8Array.from(e),publicKey:e.slice(ms)}},Bs=(e,t,n)=>{const r=Os(e,2,t,n);e.length!==_s(t)&&vs("invalid-record","ADVANCE length is not canonical for its suite");const a=Us(t),o=e.slice(ms,ms+a),i=Ns(o,t,n);return i.fromEpoch===r.fromEpoch&&i.toEpoch===r.toEpoch||vs("fork","ADVANCE epoch does not exactly match its embedded OFFER"),{...r,bytes:Uint8Array.from(e),offer:i,ciphertext:e.slice(ms+a)}},qs=(e,t)=>{if(Ms(t),!(e instanceof Uint8Array))return vs("invalid-record","record must be a Uint8Array");if(e.length<ms)return vs("invalid-record","record is shorter than its canonical header");if(1===e[5]){const n=Ns(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=Bs(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 vs("invalid-record","record type is unknown")},Ls=(e,t,n,r)=>{ks(e,"PQ root",ps);const a=po(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})(gs,n);try{return mo(a,o,ps,r)}finally{a.fill(0)}},Fs=(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)}}},zs=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)}}},js=(e,t)=>"bigint"!=typeof e?vs("invalid-record",`${t} must be a bigint`):(Is(e,t),e),Hs=(e,t,n)=>{const r=(e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return vs("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:vs("invalid-record","snapshot.phase.kind must be an enumerable string data property")})(e);switch(r){case"idle":return Cs(e,"snapshot.phase",["kind"]),{kind:"idle"};case"outbound-offer-prepared":case"outbound-offer-dispatched":{const a=Cs(e,"snapshot.phase",["kind","offer","secretKey"]),o=Ns(ks(a.offer,"snapshot.phase.offer",Us(t)),t,n),i=ks(a.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes);return{kind:"outbound-offer",dispatched:"outbound-offer-dispatched"===r,offer:o,keyPair:Fs(o.publicKey,i)}}case"inbound-offer":{const r=Cs(e,"snapshot.phase",["kind","offer"]);return{kind:"inbound-offer",offer:Ns(ks(r.offer,"snapshot.phase.offer",Us(t)),t,n)}}case"outbound-advance-prepared":{const r=Cs(e,"snapshot.phase",["kind","advance","nextRoot"]),a=Bs(ks(r.advance,"snapshot.phase.advance",_s(t)),t,n);return{kind:"outbound-advance-prepared",offer:a.offer,advance:a,nextRoot:Uint8Array.from(ks(r.nextRoot,"snapshot.phase.nextRoot",ps))}}case"outbound-advance-awaiting-ack":{const r=Cs(e,"snapshot.phase",["kind","advance"]),a=Bs(ks(r.advance,"snapshot.phase.advance",_s(t)),t,n);return{kind:"outbound-advance-awaiting-ack",offer:a.offer,advance:a}}case"inbound-advance-prepared":{const r=Cs(e,"snapshot.phase",["kind","advance","secretKey","nextRoot"]),a=Bs(ks(r.advance,"snapshot.phase.advance",_s(t)),t,n),o=ks(r.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes),i=Uint8Array.from(ks(r.nextRoot,"snapshot.phase.nextRoot",ps));return{kind:"inbound-advance-prepared",offer:a.offer,advance:a,keyPair:Fs(a.offer.publicKey,o),nextRoot:i}}case"inbound-advance-awaiting-ack-dispatch":{const r=Cs(e,"snapshot.phase",["kind","advance"]);return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Bs(ks(r.advance,"snapshot.phase.advance",_s(t)),t,n)}}default:return vs("invalid-record","snapshot phase is unknown")}},Vs=(e,t)=>{e||vs("invalid-record",`snapshot ${t}`)},$s=(e,t)=>{Ks(t.suite,t.backend.suite),ks(t.binding,"binding",fs);const n=Cs(e,"snapshot",["formatVersion","parameterSet","binding","rootKey","epoch","localCounter","remoteCounter","nextOfferer","phase","lastInboundOffer","lastInboundAdvance"]);1!==n.formatVersion&&vs("invalid-record","snapshot format version is unsupported"),n.parameterSet!==t.suite.parameterSet&&vs("suite-mismatch","snapshot suite differs from the authenticated room suite");const r=ks(n.binding,"snapshot.binding",fs);Es(r,t.binding)||vs("binding-mismatch","snapshot belongs to a different authenticated edge");const a=ks(n.rootKey,"snapshot.rootKey",ps),o=js(n.epoch,"snapshot.epoch"),i=js(n.localCounter,"snapshot.localCounter"),s=js(n.remoteCounter,"snapshot.remoteCounter");if("local"!==n.nextOfferer&&"remote"!==n.nextOfferer)return vs("invalid-record","snapshot.nextOfferer must be local or remote");const c=Uint8Array.from(a);let l;try{l=Hs(n.phase,t.suite,t.binding);const e=null===n.lastInboundOffer?null:Ns(ks(n.lastInboundOffer,"snapshot.lastInboundOffer",Us(t.suite)),t.suite,t.binding),r=null===n.lastInboundAdvance?null:Bs(ks(n.lastInboundAdvance,"snapshot.lastInboundAdvance",_s(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&&(Vs(i.toEpoch<=t,"last inbound OFFER is from a future epoch"),Vs(i.senderCounter<r,"last inbound OFFER counter was not consumed")),null!==s&&(Vs(s.toEpoch<=t,"last inbound ADVANCE is from a future epoch"),Vs(s.senderCounter<r,"last inbound ADVANCE counter was not consumed")),o.kind){case"idle":return;case"outbound-offer":return void Vs("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 Vs("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 Vs("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 Vs("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 Vs(null!==i&&Es(i.bytes,o.offer.bytes),"outbound ADVANCE is missing its exact inbound OFFER replay record");case"inbound-advance-prepared":return void Vs("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":Vs("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"),Vs(null!==s&&Es(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 Qs{#e;#n;#r;#a;#o;#i;#s;#c;#l;#d={kind:"idle"};#u=null;#h=null;#f=!1;#p=!1;constructor(e){Ks(e.suite,e.backend.suite),ks(e.binding,"binding",fs),ks(e.rootKey,"PQ root",ps);const t=e.nextOfferer;"local"!==t&&"remote"!==t&&vs("invalid-state","nextOfferer must be local or remote");const n=e.epoch??0n,r=e.localCounter??0n,a=e.remoteCounter??0n;Is(n,"epoch"),Is(r,"local counter"),Is(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=$s(e,t);try{const e=new Qs({...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:zs(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 Qs.restore(e,{module:this.#e,backend:this.#n,suite:this.#r,binding:this.#a})}finally{Ws(e)}}adopt(e){this.#y(),e.#y(),e===this&&vs("invalid-state","cannot adopt a machine into itself"),this.#r.parameterSet===e.#r.parameterSet&&Es(this.#a,e.#a)||vs("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(ps),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):vs("invalid-state","there is no pending outbound record")}async prepareOffer(){let e;this.#w();try{"idle"!==this.#d.kind&&vs("invalid-state","cannot prepare an OFFER while another transition is pending"),"local"!==this.#l&&vs("wrong-turn","the remote peer owns the next OFFER turn"),this.#b(),e=await this.#n.generateKeyPair(),this.#m(),ks(e.publicKey,"ML-KEM public key",this.#r.publicKeyBytes),ks(e.secretKey,"ML-KEM secret key",this.#r.secretKeyBytes);const t=((e,t,n,r,a)=>{ks(a,"ML-KEM public key",e.publicKeyBytes);const o=Ts(1,e,t,n,r,r+1n,Us(e));return o.set(a,ms),o})(this.#r,this.#a,this.#s,this.#i,e.publicKey),n=Ns(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 vs("invalid-state","there is no outbound OFFER to dispatch");e.dispatched&&vs("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 vs("invalid-state","only an undispatched OFFER can be aborted");e.keyPair.destroy(),this.#d={kind:"idle"}}acceptAuthenticatedOffer(e){this.#y();const t=Ns(e,this.#r,this.#a);this.#k(t),"idle"!==this.#d.kind&&vs("invalid-state","another PQ healing transition is pending"),"remote"!==this.#l&&vs("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 vs("invalid-state","an authenticated inbound OFFER is required");Ss(this.#s,"local counter"),e=await this.#n.encapsulate(t.offer.publicKey),this.#m(),ks(e.ciphertext,"ML-KEM ciphertext",this.#r.ciphertextBytes),ks(e.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const n=((e,t,n,r,a)=>{ks(a,"ML-KEM ciphertext",e.ciphertextBytes);const o=Ts(2,e,t,n,r.fromEpoch,r.toEpoch,_s(e));return o.set(r.bytes,ms),o.set(a,ms+r.bytes.length),o})(this.#r,this.#a,this.#s,t.offer,e.ciphertext),r=Bs(n,this.#r,this.#a),a=Ls(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?vs("invalid-state","there is no prepared outbound ADVANCE"):(this.#A(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=As(e),n=this.#d;if("outbound-advance-awaiting-ack"!==n.kind)return vs("invalid-state","no outbound ADVANCE is awaiting acknowledgement");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||vs("invalid-record","advance acknowledgement does not bind the pending transition"),this.#d={kind:"idle"}}async acceptAuthenticatedAdvance(e){let t;this.#w();try{const n=Bs(e,this.#r,this.#a);this.#C(n);const r=this.#d;if("outbound-offer"!==r.kind||!r.dispatched)return vs("invalid-state","a dispatched outbound OFFER is required before ADVANCE");this.#I(n.senderCounter),this.#S(n.fromEpoch),Es(n.offer.bytes,r.offer.bytes)||vs("fork","ADVANCE answers a different OFFER"),t=await this.#n.decapsulate(n.ciphertext,r.keyPair.secretKey),this.#m(),ks(t.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const a=Ls(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?vs("invalid-state","there is no accepted ADVANCE to commit"):(e.keyPair.destroy(),this.#A(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=As(e),n=this.#d;if("inbound-advance-awaiting-ack-dispatch"!==n.kind)return vs("invalid-state","no advance acknowledgement is pending dispatch");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||vs("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&&vs("destroyed","state machine is destroyed")}#y(){this.#m(),this.#f&&vs("invalid-state","another asynchronous transition is in flight")}#w(){this.#y(),this.#f=!0}#v(){this.#f=!1}#b(){Ss(this.#i,"epoch"),Ss(this.#s,"local counter"),Ss(this.#c,"remote counter")}#I(e){e<this.#c&&vs("replay","record sender counter was already consumed"),e>this.#c&&vs("counter-gap","record sender counter skips an expected transition")}#S(e){e<this.#i&&vs("replay","record PQ epoch was already consumed"),e>this.#i&&vs("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))&&(Es(e.bytes,t.bytes)&&vs("replay","OFFER is an exact replay"),vs("fork","different OFFER bytes reuse an authenticated slot"))}#C(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))&&(Es(e.bytes,t.bytes)&&vs("replay","ADVANCE is an exact replay"),vs("fork","different ADVANCE bytes reuse an authenticated slot"))}#A(e){ks(e,"candidate PQ root",ps),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 Ws=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)}},Xs=j-69-S,Gs=(1n<<64n)-1n,Js=(new TextEncoder).encode("p2party/pq-control-frame/key/v1\0");class Ys extends Error{code;constructor(e,t){super(`pqHealingFrame: ${t}`),this.name="PqControlFrameError",this.code=e}}const Zs=(e,t)=>{throw new Ys(e,t)},ec=(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},tc=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&Zs("invalid-frame",`${t} must be exactly ${String(n)} bytes`),e):Zs("invalid-frame",`${t} must be a Uint8Array`),nc=(e,t)=>"bigint"!=typeof e||e<0n||e>Gs?Zs("invalid-frame",`${t} must be an unsigned 64-bit bigint`):e,rc=(e,t,n,r,a,o)=>{tc(n,"PQ root",ps),tc(r,"binding",fs);const i=(e=>{const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t})(nc(o,"keyEpoch")),s=new Uint8Array(Js.length+1+1+r.length+i.length);s.set(Js,0),s[Js.length]=(e=>{const t=os(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?Zs("invalid-frame","ML-KEM suite descriptor is not canonical"):768===e.parameterSet?1:512===e.parameterSet?2:1024===e.parameterSet?3:Zs("invalid-frame","ML-KEM suite is unsupported")})(t),s[Js.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:Zs("invalid-direction","control direction is unknown"))(a),s.set(r,Js.length+2),s.set(i,Js.length+2+r.length);const c=po(n,r,e);try{return mo(c,s,k,e)}finally{c.fill(0),i.fill(0)}},ac=(e,t,n)=>{if(tc(e,"control record"),64===e.length){const r=Ds(e,t,n);return{counter:r.advanceCounter,keyEpoch:r.epoch}}const r=qs(e,t);return ec(r.binding,n)?{counter:r.senderCounter,keyEpoch:r.fromEpoch}:Zs("binding-mismatch","control record belongs to another authenticated edge")},oc=e=>{const t=tc(e.binding,"binding",fs),n=nc(e.keyEpoch,"keyEpoch"),r=ac(e.record,e.suite,t);r.keyEpoch!==n&&Zs("epoch-mismatch","control record is not authenticated under its required epoch"),e.record.length>Xs-4&&Zs("invalid-frame","control record does not fit the uniform cell");const a=(()=>{const e=new Uint8Array(I);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(Xs);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e.record.length,!1),s.set(e.record,4);const c=rc(e.module,e.suite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+S,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)?Zs("invalid-frame","control-frame AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{ha(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),ha(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),ha(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,c,a,s,o),n=new Uint8Array(j);return n.set(o,0),n.set(t,69),n}finally{c.fill(0),s.fill(0)}},ic=e=>{const t=tc(e.frame,"control frame",j),n=tc(e.binding,"binding",fs),r=nc(e.keyEpoch,"keyEpoch");5!==t[0]&&Zs("invalid-frame","frame type is not PQ control"),ec(t.subarray(1,33),n)||Zs("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)&&Zs("invalid-frame","control-frame reserved header must be zero"),o.getBigUint64(49,!1)!==r&&Zs("epoch-mismatch","control-frame epoch is not the expected epoch");const s=t.subarray(57,69),c=t.subarray(69),l=rc(e.module,e.suite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-S,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)?Zs("authentication-failed","control-frame authentication failed"):Uint8Array.from(u)}finally{ha(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),ha(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>Xs-4)&&Zs("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&&Zs("invalid-padding","encrypted control padding must be all zero");const h=d.slice(4,o),f=ac(h,e.suite,n);return f.keyEpoch!==r&&Zs("epoch-mismatch","decrypted control record does not match its frame epoch"),f.counter!==i&&Zs("record-mismatch","decrypted control counter does not match its public header"),h}finally{l.fill(0),d?.fill(0)}},sc=new Uint8Array([80,50,69,68,71,69,52,0]),cc=(1n<<64n)-1n,lc=262144,dc=Math.min(G,256),uc=/^[0-9a-f]{64}:[0-9]+:[0-9]+$/,hc=new TextEncoder,fc=new TextDecoder("utf-8",{fatal:!0}),pc=e=>{throw new Error(`pqHealingRuntime: ${e}`)},mc=(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},yc=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&pc(`${t} must be exactly ${String(n)} bytes`),e):pc(`${t} must be a Uint8Array`),gc=(e,t)=>"number"!=typeof e||!Number.isSafeInteger(e)||e<0?pc(`${t} must be a non-negative safe integer`):e,wc=e=>1===e?"local":2===e?"remote":pc("checkpoint has an invalid next-offerer turn");class bc{#E=[];#P=0;bytes(e){const t=Uint8Array.from(e);this.#E.push(t),this.#P+=t.length,this.#P>lc&&pc("checkpoint exceeds the encrypted edge-state budget")}u8(e){(!Number.isInteger(e)||e<0||e>255)&&pc("u8 value is out of range"),this.bytes(Uint8Array.of(e))}u16(e){(!Number.isInteger(e)||e<0||e>65535)&&pc("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)&&pc("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>cc)&&pc(`${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&&pc("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 vc{#x;#R=0;constructor(e){(0===e.length||e.length>lc)&&pc("checkpoint length is invalid"),this.#x=Uint8Array.from(e)}take(e){if(!Number.isSafeInteger(e)||e<0||this.#R+e>this.#x.length)return pc("checkpoint is truncated");const t=this.#x.slice(this.#R,this.#R+e);return this.#R+=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?pc("checkpoint field exceeds its budget"):this.take(t)}finish(){this.#R!==this.#x.length&&pc("checkpoint contains trailing bytes")}destroy(){this.#x.fill(0),this.#R=this.#x.length}}const kc=(e,t,n)=>e.sized(t)??pc(`${n} is missing`),Ic=(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:kc(e,n,"prepared OFFER"),secretKey:kc(e,t.secretKeyBytes,"prepared OFFER secret key")};case 2:return{kind:"outbound-offer-dispatched",offer:kc(e,n,"dispatched OFFER"),secretKey:kc(e,t.secretKeyBytes,"dispatched OFFER secret key")};case 3:return{kind:"inbound-offer",offer:kc(e,n,"inbound OFFER")};case 4:return{kind:"outbound-advance-prepared",advance:kc(e,r,"prepared ADVANCE"),nextRoot:kc(e,32,"candidate PQ root")};case 5:return{kind:"outbound-advance-awaiting-ack",advance:kc(e,r,"outbound ADVANCE")};case 6:return{kind:"inbound-advance-prepared",advance:kc(e,r,"inbound ADVANCE"),secretKey:kc(e,t.secretKeyBytes,"inbound ADVANCE secret key"),nextRoot:kc(e,32,"candidate PQ root")};case 7:return{kind:"inbound-advance-awaiting-ack-dispatch",advance:kc(e,r,"acknowledged ADVANCE")};default:return pc("checkpoint has an unknown PQ phase")}},Sc=e=>{for(const t of e.values())t.fill(0);e.clear()};class Ac{#e;#M;#K;#r;#n;#a;#U;#_;#D;#T;#O=null;#N=null;#B=null;#q=null;#L=new Map;#F=0;#z;#p=!1;constructor(e){const t=Z(e.pqMode);ee(e.pqMode)!==e.rootSuite&&pc("authenticated root suite and room PQ mode disagree"),yc(e.binding,"edge binding",32),yc(e.rootKey,"PQ root",32),this.#e=e.module,this.#M=e.pqMode,this.#K=e.rootSuite,this.#r=os(t),this.#n=hs(e.module,this.#r),this.#a=Uint8Array.from(e.binding),this.#D=new Qs({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=gc(e.now??Date.now(),"initial healing time"),this.#U=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#_=e.amInitiator?"responder-to-initiator":"initiator-to-responder"}get pqMode(){return this.#M}get rootSuite(){return this.#K}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.#K,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&&pc("application-message counter overflow"),this.#F+=1}healingDue(e=Date.now()){return this.#j(),gc(e,"healing clock"),!this.#D.trafficBlocked&&"local"===this.#D.nextOfferer&&(this.#F>=64||e-this.#z>=864e5)}copyPendingFrame(){return this.#j(),this.#O?Uint8Array.from(this.#O.frame):null}get pendingRetryAt(){return this.#j(),this.#O?.nextRetryAt??null}get pendingAttempts(){return this.#j(),this.#O?.attempts??0}markPendingDispatched(e=Date.now()){this.#j();const t=this.#O;if(!t)return pc("there is no PQ control outbox");gc(e,"dispatch clock"),t.attempts>=8&&pc("PQ control retry budget is exhausted"),this.#O={kind:t.kind,frame:t.frame,attempts:t.attempts+1,nextRetryAt:e+5e3}}async prepareHealingOffer(e=Date.now()){this.#j(),this.healingDue(e)||pc("a local sparse-PQ healing exchange is not due");const t=await this.#D.prepareOffer(),n=this.#D.copyRootKey();try{const r=oc({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#U,keyEpoch:this.#D.epoch,record:t});return this.#D.markOfferDispatched(),this.#O?.frame.fill(0),this.#O={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(),yc(e,"PQ control frame",j),gc(t,"control clock"),this.#N&&"advance"===this.#O?.kind&&mc(e,this.#N))return{dispatch:Uint8Array.from(this.#O.frame),changed:!1};if(this.#B&&this.#q&&mc(e,this.#B))return{dispatch:Uint8Array.from(this.#q),changed:!1};const n=this.#D.copyRootKey();let r=null;try{if(r=ic({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#_,keyEpoch:this.#D.epoch,frame:e}),64===r.length){const e=this.#O;if("advance"!==e?.kind)return pc("unexpected PQ ADVANCE acknowledgement");const n=Ds(r,this.#r,this.#a);return this.#D.acceptAuthenticatedAdvanceAcknowledgement(n),e.frame.fill(0),this.#O=null,this.#H(),this.#F=0,this.#z=t,this.#V(),{dispatch:null,changed:!0}}if("offer"===qs(r,this.#r).type){this.#D.acceptAuthenticatedOffer(r);const a=await this.#D.prepareAdvance();let o;try{o=oc({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#U,keyEpoch:this.#D.epoch,record:a}),this.#D.commitPreparedAdvance()}finally{a.fill(0)}return this.#O?.frame.fill(0),this.#O={kind:"advance",frame:Uint8Array.from(o),attempts:0,nextRetryAt:t},this.#N?.fill(0),this.#N=Uint8Array.from(e),this.#B?.fill(0),this.#B=null,this.#q?.fill(0),this.#q=null,this.#V(),{dispatch:o,changed:!0}}const a=this.#O;if("offer"!==a?.kind)return pc("unexpected PQ ADVANCE without a persisted OFFER");await this.#D.acceptAuthenticatedAdvance(r);const o=this.#D.commitAcceptedAdvance(),i=((e,t,n)=>{Ms(t),ks(n,"binding",fs);const r=As(e),a=new Uint8Array(64);a.set(ys,0),a[4]=1,a[5]=3,a[6]=Ps(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=oc({module:this.#e,suite:this.#r,rootKey:s,binding:this.#a,direction:this.#U,keyEpoch:o.epoch,record:i});return this.#D.markAdvanceAcknowledgementDispatched(o),a.frame.fill(0),this.#O=null,this.#B?.fill(0),this.#B=Uint8Array.from(e),this.#q?.fill(0),this.#q=Uint8Array.from(n),this.#N?.fill(0),this.#N=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 Ac({module:this.#e,pqMode:this.#M,rootSuite:this.#K,binding:this.#a,rootKey:e,nextOfferer:this.#D.nextOfferer,amInitiator:"initiator-to-responder"===this.#U,now:this.#z}),t.#D.destroy(),t.#D=this.#D.clone(),t.#T.fill(0),t.#T=Uint8Array.from(this.#T),t.#O=null===(n=this.#O)?null:{kind:n.kind,frame:Uint8Array.from(n.frame),attempts:n.attempts,nextRetryAt:n.nextRetryAt},t.#N=null===this.#N?null:Uint8Array.from(this.#N),t.#B=null===this.#B?null:Uint8Array.from(this.#B),t.#q=null===this.#q?null:Uint8Array.from(this.#q),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&&pc("cannot adopt a PQ runtime into itself"),e.#e===this.#e&&e.#M===this.#M&&e.#K===this.#K&&e.#U===this.#U&&mc(e.#a,this.#a)||pc("cannot adopt a PQ runtime from another authenticated edge"),this.#D.destroy(),this.#T.fill(0),this.#O?.frame.fill(0),this.#N?.fill(0),this.#B?.fill(0),this.#q?.fill(0),Sc(this.#L),this.#D=e.#D,this.#T=e.#T,this.#O=e.#O,this.#N=e.#N,this.#B=e.#B,this.#q=e.#q,this.#L=e.#L,this.#F=e.#F,this.#z=e.#z,e.#T=new Uint8Array(32),e.#O=null,e.#N=null,e.#B=null,e.#q=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 bc;try{return n.bytes(sc),n.u8(1),n.u8(512===(a=this.#r.parameterSet)?1:768===a?2:1024===a?3:pc("unsupported ML-KEM suite")),n.u8("initiator-to-responder"===this.#U?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:pc("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.#O),n.sized(this.#N),n.sized(this.#B),n.sized(this.#q),((e,t)=>{t.size>dc&&pc("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)||pc("active receive cache key is non-canonical");const n=hc.encode(t);(0===n.length||n.length>160)&&pc("active receive cache key length is invalid"),yc(r,"active receive message key",32),e.u16(n.length),e.bytes(n),e.bytes(r)}})(n,e),n.finish()}finally{Ws(t)}var r,a}static readCheckpointBinding(e){yc(e,"checkpoint");const t=sc.length+1+1+1+1+8+8;return e.length<t+32?pc("checkpoint is too short to contain a binding"):e.slice(t,t+32)}static restore(e,t){yc(e,"encrypted edge checkpoint plaintext"),yc(t.binding,"expected edge binding",32);const n=new vc(e);let r=null,a=null,o=null,i=null,s=null,c=null,l=null,d=null;try{const e=n.take(sc.length),h=mc(e,sc);e.fill(0),h||pc("checkpoint magic is invalid"),1!==n.u8()&&pc("checkpoint version is unsupported");const f=1===(u=n.u8())?512:2===u?768:3===u?1024:pc("checkpoint has an unknown ML-KEM suite");f!==Z(t.pqMode)&&pc("checkpoint suite disagrees with the authenticated room policy"),ee(t.pqMode)!==t.rootSuite&&pc("authenticated root suite and room PQ mode disagree");const p=n.u8();p!==(t.amInitiator?1:2)&&pc("checkpoint belongs to the opposite edge direction"),0!==n.u8()&&pc("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))&&pc("checkpoint counters exceed the safe-integer range");const g=n.take(32);mc(g,t.binding)||pc("checkpoint belongs to another authenticated edge");const w=n.take(32),b=os(f);r={formatVersion:1,parameterSet:f,binding:g,rootKey:w,epoch:n.u64(),localCounter:n.u64(),remoteCounter:n.u64(),nextOfferer:wc(n.u8()),phase:Ic(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 pc("checkpoint outbox kind is invalid");const n=e.u8();n>8&&pc("checkpoint outbox attempts exceed the retry budget");const r=e.u64();r>BigInt(Number.MAX_SAFE_INTEGER)&&pc("checkpoint retry deadline exceeds the safe-integer range");const a=kc(e,j,"outbox frame");return yc(a,"outbox frame",j),{kind:1===t?"offer":"advance",attempts:n,nextRetryAt:Number(r),frame:a}})(n),c=n.sized(j),l=n.sized(j),d=n.sized(j);for(const e of[c,l,d])e&&yc(e,"cached control frame",j);i=(e=>{const t=e.u16();t>dc&&pc("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)&&pc("checkpoint active receive cache key length is invalid");const r=e.take(t);let a;try{a=fc.decode(r)}finally{r.fill(0)}0!==a.length&&uc.test(a)&&!n.has(a)||pc("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=hs(t.module,b);a=Qs.restore(r,{module:t.module,backend:v,suite:b,binding:t.binding});const k=a.copyRootKey();try{o=new Ac({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.#O=s,s=null,o.#N=c,c=null,o.#B=l,l=null,o.#q=d,d=null,o.#L=i,i=null,o.#F=Number(y),o.#$(),o}catch(e){throw o?.destroy(),e}finally{n.destroy(),r&&Ws(r),a?.destroy(),s?.frame.fill(0),c?.fill(0),l?.fill(0),d?.fill(0),i&&Sc(i)}var u}destroy(){this.#p||(this.#D.destroy(),this.#a.fill(0),this.#T.fill(0),this.#O?.frame.fill(0),this.#N?.fill(0),this.#B?.fill(0),this.#q?.fill(0),Sc(this.#L),this.#O=null,this.#N=null,this.#B=null,this.#q=null,this.#p=!0)}#V(){const e=this.#D.copyRootKey();this.#T.fill(0),this.#T=e}#H(){this.#N?.fill(0),this.#B?.fill(0),this.#q?.fill(0),this.#N=null,this.#B=null,this.#q=null}#$(){const e=this.#D.phase;("outbound-offer-dispatched"===e&&"offer"!==this.#O?.kind||"outbound-advance-awaiting-ack"===e&&"advance"!==this.#O?.kind||"offer"===this.#O?.kind&&"outbound-offer-dispatched"!==e||"advance"===this.#O?.kind&&"outbound-advance-awaiting-ack"!==e)&&pc("checkpoint PQ phase and sealed outbox disagree"),null!==this.#N&&"advance"!==this.#O?.kind&&pc("checkpoint cached OFFER has no matching ADVANCE outbox"),null===this.#B!=(null===this.#q)&&pc("checkpoint ADVANCE replay and ACK cache must be paired"),null!==this.#N&&null!==this.#B&&pc("checkpoint contains mutually exclusive replay caches")}#j(){this.#p&&pc("state is destroyed")}}const Cc=new TextEncoder,Ec=Cc.encode("CPaceRistretto255"),Pc=Cc.encode("CPaceRistretto255_ISK"),xc=new Uint8Array(0),Rc=(e,t,n)=>{if(t.length!==n)throw new Error(`cpace: ${e} must be ${n} bytes`)},Mc=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)},Kc=(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?ha(e,o):e._free(a)}},Uc=(e,t,n)=>{Kc(e,t,Mc(n.data.length)),Kc(e,t,n.data,n.secret)},_c=(e,t,n,r)=>{const a=Math.max(0,127-(Mc(Ec.length).length+Ec.length)-(Mc(e.length).length+e.length)),o=((e,t)=>{const n=e._malloc(y),r=e._malloc(m),a=new Uint8Array(e.wasmMemory.buffer,n,y),o=new Uint8Array(e.wasmMemory.buffer,r,m);try{if(a.fill(0),o.fill(0),0!==e._sha512_init(n))throw new Error("sha512_init failed");for(const r of t)Uc(e,n,r);if(0!==e._sha512_final(n,r))throw new Error("sha512_final failed");return Uint8Array.from(o)}finally{ha(e,a),ha(e,o)}})(r,[{data:Ec},{data:e,secret:!0},{data:new Uint8Array(a)},{data:n},{data:t}]),i=r._malloc(E),s=r._malloc(C),c=new Uint8Array(r.wasmMemory.buffer,i,E),l=new Uint8Array(r.wasmMemory.buffer,s,C);try{return c.set(o),l.fill(0),r._cpace_ristretto255_from_hash(s,i),Uint8Array.from(l)}finally{o.fill(0),ha(r,c),r._free(s)}},Dc=(new TextEncoder).encode("p2party-interactive-3dh-v2"),Tc=new Uint8Array(64),Oc=e=>{const t=new Uint8Array(H.length+e.length);return t.set(H,0),t.set(e,H.length),t},Nc=async(e,t,n)=>pa(Oc(e),t,n),Bc=async(e,t,n,r)=>ma(Oc(e),t,n,r),qc=e=>{const t=(e=>{if("hybrid-mlkem768"===e)return L;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},Lc=(new TextEncoder).encode("p2party-v4-hs-kc-transcript-v4"),Fc=(new TextEncoder).encode("p2party-v4-hs-kc-responder-v4"),zc=(new TextEncoder).encode("p2party-v4-hs-kc-initiator-ratchet-dh-v4"),jc=(new TextEncoder).encode("p2party-v4-hs-kc-responder-finish-v4"),Hc=new Uint8Array(64),Vc=(new TextEncoder).encode("p2party-v4-pq-healing-extract-v1"),$c=(new TextEncoder).encode("p2party-v4-pq-healing-root-v1"),Qc=(new TextEncoder).encode("p2party-v4-pq-healing-binding-v1\0"),Wc=64,Xc=129,Gc=e=>{const t=os(Z(e)),n=193+t.publicKeyBytes;return{suite:t,publicKeyOffset:193,ciphertextOffset:n,length:n+t.ciphertextBytes}},Jc=(e,t,n)=>{const r=n._malloc(e.length),a=n._malloc(t.length),o=n._malloc(Wc);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,Wc))}finally{ha(n,new Uint8Array(n.wasmMemory.buffer,r,e.length)),n._free(a),n._free(o)}},Yc=e=>{let t=0;for(const n of e)t|=n;return 0===t},Zc=(e,t)=>{const n=new Uint8Array(97);return n[0]=2,n.set(e,1),n.set(t,33),n},el=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=Gc(a),f=hs(n,h.suite),p=ee(a),g=crypto.getRandomValues(new Uint8Array(32)),w=uo(n);let b=new Uint8Array(32),v=null;const k=new Uint8Array(h.suite.publicKeyBytes),I=new Uint8Array(h.suite.ciphertextBytes);let S,A,E,x,R,M,K,U,_=null,D=null,T=null;const O=e=>{if("pin"!==r)return null;if(!o)throw new Error("PIN mode requires a PIN");const t=_c(o,e,i,n),a=((e,t)=>{Rc("generator",e,C);const n=t._malloc(P),r=t._malloc(C),a=t._malloc(C),o=new Uint8Array(t.wasmMemory.buffer,n,P),i=new Uint8Array(t.wasmMemory.buffer,r,C),s=new Uint8Array(t.wasmMemory.buffer,a,C);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{ha(t,o),t._free(r),t._free(a)}})(t,n);return t.fill(0),a},N=()=>((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,Xc),c.set(i,e.publicKeyOffset),c.set(s,e.ciphertextOffset),c})(h,g,w.publicKey,b,l,d,k,I);try{let t;if(s){_=await f.generateKeyPair(),k.set(_.publicKey);const n=O(g);n&&(v=n.y,b=n.Y),await e.send(N()),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),B=t.subarray(65,97),q=t.subarray(97,129),L=t.subarray(Xc,193),z=t.subarray(h.publicKeyOffset,h.publicKeyOffset+h.suite.publicKeyBytes),j=t.subarray(h.ciphertextOffset,h.ciphertextOffset+h.suite.ciphertextBytes);if(s){if(!Yc(z))throw new Error("Malformed handshake HELLO: responder ML-KEM public-key field must be zero");if(Yc(j))throw new Error("Malformed handshake HELLO: responder ML-KEM ciphertext is required")}else{if(Yc(z))throw new Error("Malformed handshake HELLO: initiator ML-KEM public key is required");if(!Yc(j))throw new Error("Malformed handshake HELLO: initiator ML-KEM ciphertext field must be zero")}if(!await Bc(q,L,u,n))throw new Error("Handshake peer X25519 identity cross-signature invalid");if(s){if(!_)throw new Error("Handshake ML-KEM initiator keypair is unavailable");D=await f.decapsulate(j,_.secretKey),_.destroy()}else{const t=await f.encapsulate(z);D=t,I.set(t.ciphertext);const n=O(a);n&&(v=n.y,b=n.Y),await e.send(N())}S=((e,t,n,r,a,o)=>{let i,s;const c=fo(n,r,o);a?(i=fo(e,r,o),s=fo(n,t,o)):(i=fo(n,t,o),s=fo(e,r,o));const l=new Uint8Array(96);l.set(i,0),l.set(s,32),l.set(c,64);const d=po(Tc,l,o),u=mo(d,Dc,32,o);return l.fill(0),i.fill(0),s.fill(0),c.fill(0),d.fill(0),u})(c,q,w.secretKey,o,s,n);const H=s?g:a,V=s?a:g,$=s?w.publicKey:o,Q=s?o:w.publicKey,W=s?b:B,X=s?B:b,G=s?l:q,J=s?d:L,Y=s?q:l,Z=s?L:d,ee=s?k:z,te=s?I:j,ne=s?z:k,re=s?j:I;if("pin"===r){if(!v)throw new Error("Handshake CPace scalar is unavailable");A=((e,t)=>{const{y:n,peerShare:r,sid:a,initiatorShare:o,responderShare:i,initiatorAssociatedData:s=xc,responderAssociatedData:c=xc}=e;Rc("private scalar",n,P),Rc("peer share",r,C),Rc("initiator share",o,C),Rc("responder share",i,C);const l=t._malloc(P),d=t._malloc(C),u=t._malloc(C),h=t._malloc(y),f=t._malloc(m),p=new Uint8Array(t.wasmMemory.buffer,l,P),g=new Uint8Array(t.wasmMemory.buffer,d,C),w=new Uint8Array(t.wasmMemory.buffer,u,C),b=new Uint8Array(t.wasmMemory.buffer,h,y),v=new Uint8Array(t.wasmMemory.buffer,f,m);try{if(p.set(n),g.set(r),w.fill(0),b.fill(0),v.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(Uc(t,h,{data:Pc}),Uc(t,h,{data:a}),Kc(t,h,Mc(C)),0!==t._sha512_update(h,u,C))throw new Error("sha512_update failed");if(Uc(t,h,{data:o}),Uc(t,h,{data:s}),Uc(t,h,{data:i}),Uc(t,h,{data:c}),0!==t._sha512_final(h,f))throw new Error("sha512_final failed");return Uint8Array.from(v)}finally{ha(t,p),t._free(d),ha(t,w),ha(t,b),ha(t,v)}})({y:v,peerShare:B,sid:H,initiatorShare:W,responderShare:X},n)}const ae=((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);E=await Br("pin"===r?[A,S,D.sharedSecret]:[S,D.sharedSecret]),x=po(Hc,E,n);const oe=await Br([ae,i,G,J,Y,Z,ee,re]);R=mo(x,oe,32,n);const ie=await Br([Qc,i,H,V,$,Q,G,J,Y,Z,ee,re]);try{U=new Uint8Array(await crypto.subtle.digest("SHA-256",ie.slice().buffer))}finally{ie.fill(0)}M=po(Vc,R,n);const se=await Br([$c,U]);try{K=mo(M,se,32,n)}finally{se.fill(0),M.fill(0),M=void 0}S.fill(0),A?.fill(0),E.fill(0),x.fill(0),D.destroy();const ce=(e,t,n,r=[])=>Br([Lc,e,H,V,$,Q,W,X,G,J,Y,Z,ee,te,ne,re,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);T=So(R,!0,r,n,p);const o=T.dhSelfPub,i=await ce(zc,r,o,[a]),s=Jc(R,i,n);try{await e.send(Zc(o,s));const t=await ce(Fc,r),i=Jc(R,t,n),c=await qr(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 ce(jc,r,o,[a,s]),h=Jc(R,u,n),f=await qr(d,h);if(h.fill(0),!f)throw new Error("Handshake final confirmation failed")}finally{s.fill(0)}}else{T=So(R,!1,null,n,p);const t=T.dhSelfPub,r=await ce(Fc,t),a=Jc(R,r,n);try{await e.send(Zc(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 ce(zc,t,o,[a]),c=Jc(R,s,n),l=await qr(i,c);if(c.fill(0),!l)throw new Error("Handshake key-confirmation failed");((e,t,n)=>{if(t.length!==F)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");Eo(e,{dhPub:t},n)})(T,o,n);const d=await ce(jc,t,o,[a,i]),u=Jc(R,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(!T)throw new Error("Handshake ratchet initialization failed");if(!K||!U)throw new Error("Handshake PQ-healing bootstrap failed");const le=T;T=null;const de={rootKey:K,binding:U,nextOfferer:s?"local":"remote"};return K=void 0,U=void 0,{state:le,secret:R,pqHealing:de}}catch(e){throw R?.fill(0),K?.fill(0),U?.fill(0),e}finally{w.secretKey.fill(0),v?.fill(0),S?.fill(0),A?.fill(0),E?.fill(0),x?.fill(0),M?.fill(0),K?.fill(0),U?.fill(0),D?.destroy(),_?.destroy(),T&&_o(T)}},tl=/a=fingerprint:sha-256\s+([0-9A-Fa-f:]+)/,nl=e=>{const t=tl.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)},rl=e=>e.replace(/:/g,"").toLowerCase(),al=new Map,ol=(e,t)=>`${e}\0${t}`,il=(e,t,n=new Error("Handshake channel closed"),r)=>{const a=ol(e,t),o=al.get(a);if(!o||r&&o.lease!==r)return!1;al.delete(a);for(const e of o.waiters)e.reject(n);return!0},sl=(e,t,n,r)=>{const a=al.get(ol(e,t));if(!a||a.lease!==r)return!1;if(null===a.nextStep||!((e,t,n="hybrid-mlkem768")=>1===t?e.length===Gc(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 il(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},cl=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=rl(Lr(nl(t))),a=rl(Lr(nl(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=rl(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}=Pu.getState().keyPair,p=ba(f,e.withPeerPublicKey),m=await Fa();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=Fr(e.withPeerPublicKey),b=((e,t,n)=>{const r=ol(e,t),a=al.get(r);if(!a||a.lease!==n)throw new Error(`No owned handshake channel registered for ${t}`);const o=()=>{if(al.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 el(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 Ac({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),!xi(t,e.withPeerId,c))throw new Error("Handshake transport lease is stale");ci(e,t),await(async(e,t,n,r,a,o)=>{const i=()=>n.pqRuntime.serialize();e.serializeEdgeCryptoState=i;try{await hi(e,n.state,t,()=>{r(),e.ratchetState&&_o(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(!xi(t,e.withPeerId,c))throw new Error("Handshake transport lease was replaced during persistence");if(!((e,t,n)=>{const r=Ei(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 Mi(t,e.withPeerId,n,c),n}finally{d?.fill(0),l?.fill(0),u&&_o(u),h?.destroy(),il(t,e.withPeerId,new Error("Handshake attempt finished"),s)}},ll=new WeakMap,dl=(e,t,n,r)=>(async(e,t,n,r)=>si(n,e.withPeerPublicKey,async()=>{li(e,n);const a=r?.()??e.serializeEdgeCryptoState?.()??null;try{await di(t,n,e.withPeerPublicKey,e.withPeerId,a)}finally{a?.fill(0)}li(e,n)}))(e,t,n,r),ul=e=>{throw new Error(`pqHealingOrchestrator: ${e}`)};class hl extends Error{constructor(e){super("pqHealingOrchestrator: edge checkpoint persistence failed",{cause:e}),this.name="PqPersistenceError"}}const fl=e=>{const t=ll.get(e);return!(!t||!t.inboundBlocked&&!t.failed)||(e.pqHealingState?.trafficBlocked??!1)},pl=(e,t)=>0===(e.messageChannels?.size??0)&&!((e,t)=>{const n=Vi(e,t);return(zi.get(n)??0)>0||Fi.has(n)})(t,e.withPeerId),ml=async(e,t,n)=>pi(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 hl(e)}if(e.pqHealingState!==r)throw new hl(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))}),yl=e=>{const t=ll.get(e);t&&(t.destroyed=!0,null!==t.interval&&clearInterval(t.interval),t.interval=null,ll.delete(e))},gl=(e,t)=>{e.failed||(e.failed=!0,e.hooks.failEdge(t))},wl=async e=>{const t=ll.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 gl(t,new Error("pqHealingOrchestrator: control retry budget exhausted; failing the authenticated edge")):void await ml(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&&pl(e,t.roomId)&&await ml(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}}},bl=async(e,t,n)=>{const r=ll.get(e),a=e.pqHealingState;if(r&&!r.destroyed&&!r.failed&&a)if(n.length===j){r.inboundBlocked=!0;try{await(async(e,t)=>{const n=Vi(e,t);for(;;){const e=Fi.get(n);if(!e&&0===(zi.get(n)??0))return;e?await e.catch(()=>{}):await new Promise(e=>setTimeout(e,10))}})(t,e.withPeerId);const a=r.now();await ml(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 hl)return void console.error("pqHealingOrchestrator: inbound transition not durable",e);gl(r,new Error("pqHealingOrchestrator: unauthenticated or forked control cell; failing the authenticated edge",{cause:e}))}finally{r.inboundBlocked=!1}}else gl(r,new Error("pqHealingOrchestrator: malformed control cell length"))},vl=(e,t)=>{if(!Number.isSafeInteger(t))throw new Error(`coverScheduler: ${e} must be a safe integer`)},kl=(e,t)=>{if(!(t instanceof Uint8Array))throw new Error(`coverScheduler: ${e} must return a Uint8Array`);return t},Il=e=>e.cancelRequested?0:"control"===e.job.kind?1:2,Sl=(e,t)=>{const n=Il(e)-Il(t);if(0!==n)return n;return(t.job.priority??0)-(e.job.priority??0)||e.sequence-t.sequence},Al=e=>({id:e.job.id,kind:e.job.kind,declaredCellCount:e.job.declaredCellCount});class Cl{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(Pl(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>=El(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(Sl).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(vl("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&&vl("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 vl("cycle index",t),t}sortQueue(){this.queued.sort(Sl)}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?Al(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??kl("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:kl("nextCell",r),source:n.job.kind,slot:t,jobId:n.job.id,jobCellIndex:n.sentCells}}}}return{cell:kl("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 El=e=>e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell),Pl=e=>{if(null===e||"object"!=typeof e)throw new Error("coverScheduler: schedule must be an object");if(vl("phase offset",e.phaseOffsetMs),vl("cover cadence",e.coverCadenceMs),vl("cover lanes",e.coverLanes),vl("cover frames per cell",e.coverFramesPerCell),vl("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(El(e)<25)throw new Error("coverScheduler: schedule requires at least 25ms per staggered slot")},xl=j-69-S,Rl=m,Ml=xl-1-4,Kl=(1n<<64n)-1n,Ul=(new TextEncoder).encode("p2party/cover-cell/key/v1\0");class _l extends Error{code;constructor(e,t){super(`coverCell: ${t}`),this.name="CoverCellError",this.code=e}}const Dl=(e,t)=>{throw new _l(e,t)},Tl=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&Dl("invalid-cell",`${t} must be exactly ${String(n)} bytes`),e):Dl("invalid-cell",`${t} must be a Uint8Array`),Ol=(e,t)=>"bigint"!=typeof e||e<0n||e>Kl?Dl("invalid-cell",`${t} must be an unsigned 64-bit bigint`):e,Nl=(e,t,n,r,a,o)=>{Tl(n,"PQ message root",32),Tl(r,"edge binding",32);const i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,Ol(o,"keyEpoch"),!1);const s=new Uint8Array(Ul.length+1+1+r.length+i.length);s.set(Ul,0),s[Ul.length]=(e=>e===$?1:e===V?2:e===Q?3:Dl("invalid-cell","authenticated room suite is unsupported"))(t),s[Ul.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:Dl("invalid-direction","cover-cell direction is unknown"))(a),s.set(r,Ul.length+2),s.set(i,Ul.length+2+r.length);const c=po(n,r,e);try{return mo(c,s,k,e)}finally{c.fill(0),i.fill(0)}},Bl=e=>{const t=Tl(e.binding,"edge binding",32),n=Ol(e.keyEpoch,"keyEpoch"),r=Ol(e.counter,"counter"),a=(e=>{if("dummy"===e.subtype)return new Uint8Array(0);if("cancel"===e.subtype)return Uint8Array.from(Tl(e.merkleRoot,"cancel transfer root",Rl));const t=Tl(e.merkleRoot,"receipt transfer root",Rl),n=Tl(e.token,"receipt token",Rl),r=new Uint8Array(t.length+n.length);return r.set(t,0),r.set(n,t.length),r})(e.content);a.length>Ml&&Dl("invalid-cell","cover payload does not fit the uniform cell");const o=(()=>{const e=new Uint8Array(I);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(xl);var l;c[0]="dummy"===(l=e.content.subtype)?1:"cancel"===l?2:"receipt"===l?3:Dl("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=Nl(e.module,e.rootSuite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+S,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)?Dl("invalid-cell","cover-cell AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{ha(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),ha(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),ha(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,d,o,c,i),n=new Uint8Array(j);return n.set(i,0),n.set(t,69),n}finally{d.fill(0),c.fill(0),a.fill(0)}},ql=e=>{const t=Tl(e.frame,"cover cell",j),n=Tl(e.binding,"edge binding",32),r=Ol(e.keyEpoch,"keyEpoch");4!==t[0]&&Dl("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)||Dl("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)&&Dl("invalid-cell","cover-cell reserved header must be zero"),o.getBigUint64(49,!1)!==r&&Dl("epoch-mismatch","cover-cell epoch is not the expected epoch"),void 0!==e.counterAbove&&(Ol(e.counterAbove,"counterAbove"),i<=e.counterAbove&&Dl("replayed-counter","cover-cell counter is not strictly newer"));const s=t.subarray(57,69),c=t.subarray(69),l=Nl(e.module,e.rootSuite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-S,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)?Dl("authentication-failed","cover-cell authentication failed"):Uint8Array.from(u)}finally{ha(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),ha(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>Ml&&Dl("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&&Dl("invalid-padding","encrypted cover padding must be all zero");return{content:(u=d[0],h=d.subarray(n,r),1===u?(0!==h.length&&Dl("invalid-cell","dummy cover cells carry no payload"),{subtype:"dummy"}):2===u?(h.length!==Rl&&Dl("invalid-cell","CANCEL payload must be one 64-byte transfer root"),{subtype:"cancel",merkleRoot:Uint8Array.from(h)}):3===u?(h.length!==2*Rl&&Dl("invalid-cell","receipt payload must be root ‖ token"),{subtype:"receipt",merkleRoot:h.slice(0,Rl),token:h.slice(Rl)}):Dl("invalid-cell","cover-cell subtype is unknown")),counter:i}}finally{l.fill(0),d?.fill(0)}var u,h},Ll={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Fl=(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 zl{#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.#U=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#_=e.amInitiator?"responder-to-initiator":"initiator-to-responder";const t={...e.schedule,phaseOffsetMs:Fl(e.policyHash,e.schedule.coverCadenceMs)},n=El(t),r=e.maxTimerDriftMs??Math.max(0,Math.min(Math.floor(n)-1,500));this.#X=(e=>new Cl(e))({schedule:t,maxTimerDriftMs:r,clock:e.clock??Ll,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!==j)return!1;const n=t.currentMessageContext();try{const t=ql({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#_,keyEpoch:n.epoch,frame:e});return!!this.#le(t.counter)&&("cancel"===t.content.subtype?this.#W.onRemoteCancel?.(Lr(t.content.merkleRoot)):"receipt"===t.content.subtype&&this.#W.onScheduledReceipt?.(Lr(t.content.merkleRoot),t.content.token),!0)}catch{return!1}}async makeDummyLaneLabel(){const e=new Uint8Array(64);return crypto.getRandomValues(e),Va(this.#W.laneLabelName,e)}#le(e){const t=this.#J;if(null!==t&&t>=zl.#Z&&e<=t-zl.#Z)return!1;if(this.#Y.has(e))return!1;if(this.#Y.add(e),(null===t||e>t)&&(this.#J=e,e>=zl.#Z)){const t=e-zl.#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,Bl({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#U,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!==j)throw new Error("coverRuntime: refusing a non-uniform cell at the lane boundary");if("open"!==n.readyState)return!1;if(n.bufferedAmount>=U)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),`${Lr(t)}~${Lr(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 jl=new WeakMap,Hl=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}},Vl=(e,t,n,r,a)=>{let o=jl.get(e);o||(o=new Map,jl.set(e,o)),o.set(r,{transferId:a,peerId:n,roomId:t})},$l=e=>{const t=e.epc.coverRuntime;if(!t)return!1;const n=Bi({runtime:t,channelMessageLabel:e.channelMessageLabel,totalChunks:e.totalChunks,sealSlotCell:e.sealSlotCell,getAckedChunks:e.getAckedChunks});return t.enqueue(n),!0},Ql=new Map,Wl=(e,t)=>{const n=Ql.get(e);n&&(n.delete(t),0===n.size&&Ql.delete(e))},Xl=(e,t)=>{e.controller.signal.aborted||e.controller.abort(t)},Gl=()=>{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},Jl=e=>/^[0-9a-f]{64}$/.test(e),Yl=(e,t=Gl())=>{if(0===e.length)throw new Error("Transfer roomId must not be empty");if(!Jl(t))throw new Error("Transfer ID must be 32-byte lowercase hex");if([...Ql.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=Ql.get(e);return r||(r=new Set,Ql.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,Wl(e,n))}}},Zl=(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&&!Jl(t.transferId))throw new Error("Transfer ID must be 32-byte lowercase hex");const n=Ql.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)Xl(e,new Error("Message transfer cancelled")),a++;return a},ed=e=>{const t=Ql.get(e);if(!t)return 0;let n=0;for(const e of t)Xl(e,new Error("Room transfers cancelled")),n++;return n},td=()=>{let e=0;for(const t of[...Ql.keys()])e+=ed(t);return e},nd=e=>{if(e?.aborted){if(e.reason instanceof Error)throw e.reason;throw new Error("Message transfer cancelled")}},rd=async(e,t)=>(nd(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),ad=e=>{e.fill(0)},od=e=>{if("string"!=typeof e||0===e.length)throw new Error("roomPinVault: room context must be a non-empty string")};const id=new class{#me=new Map;#ye;constructor(e=ad){this.#ye=e}put(e,t){od(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){od(e);const t=this.#me.get(e);return t?Uint8Array.from(t):void 0}has(e){return od(e),this.#me.has(e)}delete(e){od(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()}},sd=e=>id.delete(e),cd=()=>{id.clear()},ld=3e5,dd=new Map,ud=(e,t)=>{const n=t-ld,r=(dd.get(e)??[]).filter(e=>e>n);return 0===r.length?dd.delete(e):dd.set(e,r),r},hd=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]+ld).toISOString()}`)})(e,n);const r=await La(e,t);if(r&&r.retryAfter>n)throw new Error(`PIN retry for this peer identity is throttled until ${new Date(r.retryAfter).toISOString()}`)},fd=async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=ud(e,t);n.push(t),dd.set(e,n)})(e,n),await((e,t,n,r,a,o)=>Ea("incrementPinAttemptState",e,t,n,r,a,o))(e,t,n,3,500,3e5)},pd=(e,t)=>(void 0===t&&(e=>{dd.delete(e)})(e),((e,t)=>Ea("deletePinAttemptState",e,t))(e,t)),md=new Map,yd=(new TextEncoder).encode("p2party/room-channel/v1\0"),gd=(e,t,n)=>{const r=Fr(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(yd.length+r.length+n.length+a.length);let i=0;return o.set(yd,i),i+=yd.length,o.set(r,i),i+=r.length,o.set(n,i),i+=n.length,o.set(a,i),o},wd=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&&(y=i.publicKey,g=t.withPeerPublicKey,ba(y,g)))throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected incoming main DataChannel on the designated opener side");var y,g;if(!a&&"main"===p&&!ba(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 w="string"==typeof e?t.createDataChannel(e,{ordered:"main"===e,protocol:"raw"}):e;w.binaryType="arraybuffer";const b=w;b.withPeerId=t.withPeerId,b.roomIds=[n],"main"===b.label&&(t.mainChannel=b);const v="main"!==b.label&&void 0!==t.coverRuntime;if(v)t.coverChannels??=new Set,t.coverChannels.add(b);else if("main"!==b.label){if(t.messageChannels??=new Set,!t.messageChannels.has(b)&&t.messageChannels.size>=64)throw"closed"!==b.readyState&&b.close(),new Error("Too many message DataChannels on one peer edge");t.messageChannels.add(b)}const k=t.ratchetGateLease,I="main"===b.label?t.ratchetGateLease:void 0,S="main"===b.label?((e,t,n,r="hybrid-mlkem768",a=!1)=>{const o=ol(e,t),i=al.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 al.set(o,{lease:s,pqMode:r,expectFinish:a,channel:n,queue:[],nextStep:1,waiters:[]}),s})(n,t.withPeerId,b,s[c]?.policy.pqMode??"hybrid-mlkem768",ba(i.publicKey,t.withPeerPublicKey)):void 0;let A;try{A=await $a(p)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw t.messageChannels?.delete(b),t.mainChannel===b&&(t.mainChannel=void 0),S&&il(n,t.withPeerId,r,S),"closed"!==b.readyState&&b.close(),r}const{channelLabel:C,merkleRoot:E,merkleRootHex:P}=A;let x=!1,R=!1;const M=()=>{R||(R=!0,(e=>{if(e.released)return;e.released=!0;const t=e.pending.length;e.pending.length=0,e.seen.clear(),t>0&&Gi(e,-t)})(f),t.messageChannels?.delete(b))},K=()=>{x||(x=!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&&Wi(e,t,n,-a),r&&$i(e,r)})(l,n,t.withPeerId,u),M())};b.releaseProtocolResources=K;let U,_=!1;const D=()=>U||(_=!0,K(),U=(async()=>{await Qi(l,u),""!==P&&(await bi(t,n,P),await Ta(P))})(),U);return"main"!==b.label&&(b.cancelReceiveTransfer=D),b.onclose=async()=>{if(tt(`Channel with label ${b.label} has closed.`),v){if(t.coverChannels?.delete(b),M(),await Qi(l,u),""!==P)try{const e=await Ma(P);await vi(t,n,P,e)}catch(e){console.error(e)}K()}else if("main"===b.label){if(K(),I&&!xi(n,t.withPeerId,I))return;S&&il(n,t.withPeerId,new Error("Main data channel closed"),S),await o.dispatch(hu.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}));const e=Date.now(),r=md.get(n)??0;e-r>2e3?(md.set(n,e),o.dispatch(Me({roomId:n,connectingToPeers:!0}))):tt(`Skipping reconnection for ${n} - debounce (${String(e-r)}ms since last)`)}else{if(!r.includes(b))return;M(),await Qi(l,u);let e,a=!1;if(_)try{await U,a=!0}catch(e){console.error(e)}else if(""!==P)try{e=await Ma(P);const r="connected"===t.connectionState&&xi(n,t.withPeerId,k);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(P)&&(a=!0)}catch(e){console.error(e),a=!1}if(a)try{await D()}catch(e){console.error(e),a=!1}else{if(""!==P)try{await vi(t,n,P,e)}catch(e){console.error(e)}K()}await o.dispatch(hu.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:b.label,channel:b,alsoDeleteData:a}))}},b.onerror=async e=>{if(console.error(e),"main"===b.label){if(I&&!xi(n,t.withPeerId,I))return;await o.dispatch(hu.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}))}else{if(!r.includes(b))return K(),void("closed"!==b.readyState&&b.close());await o.dispatch(hu.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:b.label,channel:b}))}const a=Date.now(),i=md.get(n)??0;a-i>2e3?(md.set(n,a),o.dispatch(Me({roomId:n,connectingToPeers:!0}))):tt(`Skipping reconnection for ${n} - debounce (${String(a-i)}ms since last)`)},b.onmessage=async e=>{const r=new Uint8Array(e.data);if("main"!==b.label&&!Ri(n,t.withPeerId,k))return console.error("Rejected application data before peer authentication"),K(),void("closed"!==b.readyState&&b.close());const a=(e=>{const t=e.length>=1?e[0]:-1,n=3===t&&e.length!==q?-1:t;return{type:n,payload:-1===n?e.subarray(e.length):e.subarray(1)}})(r);if("main"!==b.label&&3===a.type){return void(((e,t,n)=>{if(t.released)return!1;const r=Li(e);if(t.seen.has(r))return!0;const a=Hi.get(Vi(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),Gi(t,1),t.draining||Ji(t,n),0))})(a.payload,f,async e=>{Ri(n,t.withPeerId,k)&&await no(e,b.label,b.withPeerId,n,o)})||(console.error("Closing message DataChannel: receipt queue budget exceeded"),K(),"closed"!==b.readyState&&b.close()))}if(2===a.type&&r.length===j){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=Li(e);if(n.has(p))return!0;const m=zi.get(Vi(o,i))??0;return!(t.length>=64||m+e.byteLength>16777216)&&(n.add(p),n.size>4096&&n.clear(),t.push(e),Wi(t,o,i,e.byteLength),r.value||Zi(t,n,r,a,o,i,s,c,l,d,u,h,f),!0)})(r,l,d,u,o,n,b.withPeerId,C,P,E,b,t,t.receiveMessageModule,h.signal);return void(e||(console.error("Closing message DataChannel: receive queue budget exceeded"),K(),"closed"!==b.readyState&&b.close()))}if(("main"===b.label||v)&&5===a.type&&r.length===j)return Ri(n,t.withPeerId,k)?void bl(t,n,r):void console.error("Rejected PQ control cell before peer authentication");if(4===a.type&&r.length===j&&t.coverRuntime)return Ri(n,t.withPeerId,k)?void t.coverRuntime.processInboundCoverCell(r):void console.error("Rejected cover cell before peer authentication");if("main"===b.label){const{type:e,payload:r}=a;if(1===e)return void(S&&!sl(n,t.withPeerId,r,S)&&(console.error("Closing main DataChannel: malformed or surplus handshake frame"),K(),"closed"!==b.readyState&&b.close()))}console.error(new Error("Wrong data length received"))},b.onopen=()=>{if("main"!==b.label&&!xi(n,t.withPeerId,k))return K(),void("closed"!==b.readyState&&b.close());tt(`Channel with label "${b.label}" and client ${t.withPeerId} is open.`),r.includes(b)||r.push(b),""===P&&C.length>0&&o.dispatch(Ne({roomId:n,label:p,peerId:b.withPeerId})),"main"===b.label&&(async()=>{let e,r=!1,a=!1;o.dispatch(Oe({roomId:n,peerId:t.withPeerId,status:"authenticating"}));try{if(!I||!S)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=id.get(l),!e))throw new Error("PIN room has no local PIN");r&&await hd(n,t.withPeerPublicKey);const u=ba(i.publicKey,t.withPeerPublicKey),h=Fr(i.publicKey),f=Fr(t.withPeerPublicKey),p=nl(t.localDescription?.sdp??""),m=nl(t.remoteDescription?.sdp??""),y=await Se(d.policy),g=qc({channelId:gd(d.url,b.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 cl(t,n,d.policy.authMode,d.policy.pqMode,e??null,g,t.receiveMessageModule,S,I),o.dispatch(Oe({roomId:n,peerId:t.withPeerId,status:"authenticated"})),((e,t,n)=>{e.pqHealingState||ul("cannot install an orchestrator without a PQ runtime"),yl(e);const r={roomId:t,hooks:n,now:n.now??Date.now,persistEdge:n.persistEdge??dl,interval:null,busy:!1,inboundBlocked:!1,destroyed:!1,failed:!1};ll.set(e,r);const a=n.tickMs??1e3;a>0&&(r.interval=setInterval(()=>{wl(e)},a))})(t,n,{sendControlFrame:e=>"open"===b.readyState&&(b.send(e.buffer),!0),failEdge:e=>{console.error(e),"closed"!==b.readyState&&b.close(),"closed"!==t.connectionState&&t.close()}}),(e=>{const{epc:t,roomId:n,policy:r}=e;if("scheduled"!==r.coverMode)return;Hl(t),t.coverChannels??=new Set;const a=new zl({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=jl.get(t)?.get(e);n&&Ya(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(Te({roomId:n,peerId:t.withPeerId,status:e}))},onRemoteCancel:e=>{try{Zl(n,{merkleRootHex:e})}catch(e){console.error("scheduled CANCEL abort failed",e)}}}),r&&await pd(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 fd(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 La(n,t.withPeerPublicKey);e&&e.retryAfter>Date.now()&&(s=e.retryAfter)}catch{}o.dispatch(Oe({roomId:n,peerId:t.withPeerId,status:"failed",reason:c,retryAfter:s})),I&&Mi(n,t.withPeerId,i,I),S&&il(n,t.withPeerId,i,S),console.error("protocol-v4 handshake failed:",i),"closed"!==b.readyState&&b.close(),"closed"!==t.connectionState&&t.close()}finally{e?.fill(0)}var l})(),""!==P&&"string"!=typeof e&&(async()=>{try{if(!await(async()=>!!xi(n,t.withPeerId,k)&&(await Pi(n,t.withPeerId),xi(n,t.withPeerId,k)))())return;const e=await(e=>Ea("getDBAllChunkLeafHashes",e))(P);if(0===e.length)return;let r=[];for(const{chunkIndex:t,leafHash:n}of e)if(n?.length===2*m&&(r.push(await lo(E,t,Fr(n))),32===r.length)){if(!await _i(b,r))return;r=[]}if(r.length>0&&!await _i(b,r))return;const a=await Ma(P);a&&a.totalSize>0&&a.savedSize===a.totalSize&&a.hash.length===2*m&&Ui(b,Fr(a.hash))}catch(e){console.error(e)}})()},b},bd=/(?:^|\r?\n)a=ice-ufrag:([^\r\n]+)/g,vd=/(?:^|\s)ufrag\s+([^\s]+)/i,kd=(e,t)=>{const n=(e=>{const t=new Set,n=e?.sdp;if(!n)return t;for(const e of n.matchAll(bd)){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(vd)?.[1];return n?.trim()||null})(e);return null===r||n.has(r)},Id=async(e,t)=>{if(!("closed"===e.connectionState||"closed"===e.signalingState))try{return e.restartIce(),"restarted"}catch{}return await t(),"disconnected"},Sd=(e,t,n)=>e.findIndex(e=>((e,t,n)=>e.roomId===t&&e.withPeerId===n)(e,t,n)),Ad=(e,t,n)=>{const r=Sd(e,t,n);return r<0?void 0:e[r]};class Cd{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 Ed=new Map,Pd=new Map,xd=(e,t)=>`${String(e.length)}:${e}${t}`,Rd=(e,t)=>`${String(e.length)}:${e}${t}`,Md=(e,t)=>{const n=xd(e,t);let r=Ed.get(n);return r||(r=new Cd,Ed.set(n,r)),r},Kd=(e,t)=>{const n=xd(e,t),r=Ed.get(n);r&&(async()=>{for(;;)if(await r.whenIdle(),r.isIdle())return void(Ed.get(n)===r&&Ed.delete(n))})()},Ud=async({peerId:t,peerPublicKey:n,roomId:r,peerConnections:a,rtcConfig:o},i)=>{const{keyPair:s,signalingServer:c}=i.getState();if(o??=Ce,!e.isUUID(t))throw new Error("PeerId is not a valid uuidv4");if(wa(s.publicKey,"Self Ed25519 identity"),wa(n,"Peer Ed25519 identity"),n===s.publicKey)throw new Error("Cannot connect to the same Ed25519 identity");const l=((e,t)=>{const n=Rd(e,t);let r=Pd.get(n);return r||(r=new Cd,Pd.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(hu.endpoints.disconnectFromPeer.initiate({roomId:r,peerId:t.withPeerId}));let l=Ad(a,r,t);if(l&&l.withPeerPublicKey!==n&&(await i.dispatch(hu.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=Ci(e,t),a=Ai.get(r);return a&&!a.settled&&(a.settled=!0,a.outcome="rejected",a.reject(n)),Ai.delete(r),Ei(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,ci(u,r),a.push(u);const h=()=>{if(!a.includes(u))throw new Error("WebRTC transport was replaced during initialization")},f=(async()=>{const e=Wr(),a=await ua(e);h(),u.receiveMessageModule=a,c.isConnected&&(await i.dispatch(Su.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)tt(`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(Su.endpoints.sendMessage.initiate({content:{type:"description",description:u.localDescription,fromPeerId:s.peerId,fromPeerPublicKey:s.publicKey,toPeerId:t,roomId:r,protocolVersion:4}})),tt(`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(Su.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(Su.endpoints.connectWebSocket.initiate(e.serverUrl));const n=Date.now();n-p>m&&(p=n,tt(`ICE ${u.iceConnectionState} with ${t}, restarting`),u.restartIce())}tt(`ICE candidate connection state with ${t} is ${u.iceConnectionState}.`)},u.onicegatheringstatechange=()=>{tt(`ICE gathering state with ${t} is ${u.iceGatheringState}.`)},u.onsignalingstatechange=async()=>{tt(`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&&kd(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 Id(u,()=>{}).catch(()=>{}),y&&clearTimeout(y),y=setTimeout(()=>{"disconnected"===u.connectionState&&(i.dispatch(hu.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(hu.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(Su.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(De({roomId:r,peerId:t,peerPublicKey:n})),tt(`RTC Connection status with peer ${t} is ${u.connectionState}.`))},u}finally{l.release(),((e,t)=>{const n=Rd(e,t),r=Pd.get(n);r&&r.whenIdle().then(()=>{r.isIdle()&&Pd.get(n)===r&&Pd.delete(n)})})(r,n)}},_d=async(e,t,n)=>{const r=e.createDataChannel("main",{ordered:!0,protocol:"raw"});e.mainChannel=await wd({channel:r,epc:e,roomId:e.roomId,dataChannels:t},n)},Dd=(e,t,n)=>{for(let r=e.length-1;r>=0;r--)e[r].roomId===t&&e[r].withPeerId===n&&e.splice(r,1)},Td=async({peerId:e,peerPublicKey:t,roomId:n,description:r,rtcConfig:a,peerConnections:o,iceCandidates:i,dataChannels:s},c)=>Md(n,e).runExclusive(async()=>{const{keyPair:l}=c.getState(),d=Sd(o,n,e),u=d>-1?o[d]:await Ud({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 wd({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,Dd(t,n,r)})(u.iceCandidates,i,n,e)};if(p)return m(),{data:void 0};if(h&&f)try{await u.setLocalDescription({type:"rollback"}),tt(`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===Sd(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(Su.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&&ba(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 wd({channel:e,epc:u,roomId:u.roomId,dataChannels:s},c)}return{data:void 0}}),Od=(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)))}}),Nd=async(e,t,n=!0,r=!0,a=!0)=>{if(t??=e,0===t&&e===t)return"";const o=t>e?await Od(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[Bd(0,o.length)];a(i)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}))(o,n,r,a);return i};function Bd(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 qd=(e,t)=>{const n=t._malloc(y),r=t._malloc(1+e.length),a=t._malloc(m);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,m))}finally{t._free(n),t._free(r),t._free(a)}},Ld=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)},Fd=async(e,t)=>{if(e.length%m!==0)throw new Error("Hashes were not passed");const n=e.length/m;if(0===n)throw new Error("Cannot calculate Merkle root of tree with no leaves.");if(1===n)return e;const r=t?.wasmMemory??Xr(n),a=t??await ua(r),o=a._malloc(n*m),i=new Uint8Array(r.buffer,o,n*m);i.set(e);const s=a._malloc(m),c=new Uint8Array(r.buffer,s,m),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.")}},zd=async(e,t,n,r)=>{if(e.length%m!==0)throw new Error("Hashes were not passed");const a=e.length/m;if(0===a)throw new Error("Cannot calculate Merkle proof of element of empty tree.");if(1===a){const e=new Uint8Array(m+1);if(e.set(t),r){const t=m+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??Gr(a),i=n??await ua(o),s=i._malloc(a*m),c=new Uint8Array(o.buffer,s,a*m);c.set(e);const l=i._malloc(m),d=new Uint8Array(o.buffer,l,m);d.set(t);const u=a*(m+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")}},jd=[1],Hd=(e,t=1,n=T,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>T||n<=O)throw new Error(`Chunk length needs to be between ${String(O)} and ${String(T)}`);if(!Number.isSafeInteger(e)||e<1)throw new Error("No data to split in chunks");if(e>K)throw new Error(`Message exceeds the ${String(K)} byte protocol limit`);const a=Math.ceil(n*r),o=Math.ceil(e/a);return Math.max(t,o)},Vd=async(e,t,n,r,a,o,i=1,s=T,c=.9,l=1)=>{const{keyPair:d}=t.getState();if(!jd.includes(l))throw new Error("Unknown metadata version schema.");const u=(e=>{if("string"==typeof e)return oo.Text;const t=e.name.split(".").pop()?.toLowerCase()??"";return{png:oo.ImagePNG,jpeg:oo.ImageJPEG,jpg:oo.ImageJPG,gif:oo.ImageGIF,bmp:oo.ImageBMP,tiff:oo.ImageTIFF,svg:oo.ImageSVG,webp:oo.ImageWEBP,heic:oo.ImageHEIC,pdf:oo.DocumentPDF,doc:oo.DocumentDOC,docx:oo.DocumentDOCX,xls:oo.DocumentXLS,xlsx:oo.DocumentXLSX,ppt:oo.DocumentPPT,pptx:oo.DocumentPPTX,txt:oo.DocumentTXT,rtf:oo.DocumentRTF,odt:oo.DocumentODT,mp3:oo.AudioMP3,wav:oo.AudioWAV,aac:oo.AudioAAC,flac:oo.AudioFLAC,ogg:oo.AudioOGG,m4a:oo.AudioM4A,mp4:oo.VideoMP4,avi:oo.VideoAVI,mkv:oo.VideoMKV,mov:oo.VideoMOV,wmv:oo.VideoWMV,flv:oo.VideoFLV,webm:oo.VideoWEBM,zip:oo.CompressedZIP,rar:oo.CompressedRAR,"7z":oo.Compressed7Z,tar:oo.CompressedTAR,gz:oo.CompressedGZ,html:oo.CodeHTML,css:oo.CodeCSS,js:oo.CodeJS,ts:oo.CodeTS,jsx:oo.CodeJSX,tsx:oo.CodeTSX,json:oo.CodeJSON,xml:oo.CodeXML,py:oo.CodePY,java:oo.CodeJAVA,c:oo.CodeC,cpp:oo.CodeCPP,cs:oo.CodeCS,rb:oo.CodeRB,php:oo.CodePHP,sql:oo.CodeSQL,epub:oo.EbookEPUB,mobi:oo.EbookMOBI,azw:oo.EbookAZW,ttf:oo.FontTTF,otf:oo.FontOTF,ico:oo.ImageICO,exe:oo.ExecutableEXE,dmg:oo.ExecutableDMG,apk:oo.ExecutableAPK}[t]??oo.Unknown})(e),h=u===oo.Text?await Nd(256):e.name.substring(0,255),f="string"==typeof e?(new TextEncoder).encode(e):e,p="string"==typeof e?f.length:f.size,g=Hd(p,i,s,c),w=await navigator.storage.estimate(),b=w.quota??10737418240,v=w.usage??65536,k=Math.max(0,b-v),I=((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+_+D+2048);return Number.isSafeInteger(r)?r:Number.POSITIVE_INFINITY})(p,g,s);if(I>k)throw new Error("Not enough space to stage the padded encrypted transfer in the browser.");const S=new Date;let A;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);A=new Uint8Array(e)}else A=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(y),o=t._malloc(Y),i=t._malloc(m);try{if(r(),0!==t._sha512_init(a))throw new Error("sha512_init failed");const n=new Uint8Array(t.wasmMemory.buffer,o,Y);for(let i=0;i<e.size;i+=J){r();const s=Math.min(i+J,e.size),c=new Uint8Array(await e.slice(i,s).arrayBuffer());r();for(let e=0;e<c.length;e+=Y){r();const i=Math.min(Y,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,m))}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 C=Lr(A);o.bindHash(C);const E={schemaVersion:l,messageType:u,hash:A,name:h,totalSize:p,date:S};let P=0;const x=new Uint8Array(s),R=new Uint8Array(g*m),M=Math.floor(s*(1-c)),K=Math.ceil(s*c);for(let a=0;a<g&&!o.signal.aborted;a++){window.crypto.getRandomValues(x);const i=await Od(0,M),s=p-P,c=Math.min(Math.max(s,0),K);let l=i+c;if(s>0){const t=f.slice(P,P+c);if("string"==typeof e)x.set(t,i);else{const e=await t.arrayBuffer();if(o.signal.aborted)break;x.set(new Uint8Array(e),i)}P+=c}else{const e=l+p+1,t=Number.MAX_SAFE_INTEGER-e;l+=await Od(e,t)}const y=await Ld(x),w=Lr(y);R.set(y,a*m);const b=ro({...E,chunkStartIndex:i,chunkEndIndex:l,chunkIndex:a});await Oa({transferId:o.transferId,hash:C,merkleRoot:"",chunkIndex:a,leafHash:w,receiptToken:"",data:x.slice().buffer,metadata:b.buffer,merkleProof:(new Uint8Array).buffer}),t.dispatch(qe({roomId:r.id,transferId:o.transferId,merkleRootHex:"",sha512Hex:C,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:a+1,totalChunks:g,messageType:u,filename:h,channelLabel:n,timestamp:S.getTime()}))}if(o.signal.aborted)return await Na({transferId:o.transferId}),t.dispatch(He({roomId:r.id,transferId:o.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};const U=await Fd(R,a),O=Lr(U);try{const e=so(u);for(let t=0;t<g&&!o.signal.aborted;t++){const n=await Ua(o.transferId,t);if(!n)throw new Error(`Missing staged outbound chunk ${String(t)}`);const r=ao(new Uint8Array(n.metadata)),a=r.chunkEndIndex-r.chunkStartIndex;a<=0||a>r.totalSize||await _a({merkleRoot:O,hash:C,chunkIndex:r.chunkIndex,data:n.data.slice(r.chunkStartIndex,r.chunkEndIndex),mimeType:e})}}catch(e){throw await Ta(O),e}if(o.signal.aborted)return await Na({transferId:o.transferId}),await Ta(O),t.dispatch(He({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)=>Ea("setDBRoomMessageData",e,t,n,r,a,o,i,s,c,l,d))(r.id,O,C,d.peerId,p,p,u,h,n,S.getTime(),o.transferId)}catch(e){throw await Ta(O),e}return t.dispatch(qe({roomId:r.id,transferId:o.transferId,merkleRootHex:O,sha512Hex:C,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:g,totalChunks:g,messageType:u,filename:h,channelLabel:n,timestamp:S.getTime()})),{merkleRoot:U,merkleRootHex:O,hash:A,hashHex:C,totalSize:p,totalChunks:g,messageType:u,chunkHashes:R}},$d=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},Qd=(e,t)=>`${e}\0${t}`,Wd=async e=>{let t=e.inFlight(),n=Date.now();for(;e.isOpen()&&e.inFlight()>=e.windowSize;){nd(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)),nd(e.signal)}nd(e.signal)},Xd=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f)=>{nd(u);const{merkleRootHex:p}=await $a(e.label);if(p!==Lr(i))throw new Error("Outbound channel label does not match its Merkle root");const y=f?.()??0;let g=0;const w=function(e){const t=e.slice();for(let e=t.length-1;e>0;e--){const n=Bd(0,e+1);[t[e],t[n]]=[t[n],t[e]]}return t}(Array.from({length:a},(e,t)=>t));for(let b=0;b<a;b++){nd(u);const a=w[b],v=await Ua(s,a);if(nd(u),!v)throw new Error(`Missing staged outbound chunk ${String(a)}`);const k=new Uint8Array(v.metadata),I=ao(k);if(I.chunkIndex!==a||v.chunkIndex!==a)throw new Error("Outbound chunk index does not match its staging key");const S=I.chunkEndIndex>I.chunkStartIndex&&I.chunkEndIndex-I.chunkStartIndex<=I.totalSize;if(void 0!==h&&(!S||h.has(I.chunkIndex)))continue;S&&f&&await Wd({windowSize:32,stallTimeoutMs:1e4,pollMs:25,isOpen:()=>"open"===e.readyState,inFlight:()=>g-Math.max(0,f()-y),signal:u});const A=new Uint8Array(D);if(0===v.merkleProof.byteLength){const e=await zd(o,Fr(v.leafHash),d,D);nd(u),A.set(e)}else A.set(new Uint8Array(v.merkleProof));const C=v.receiptToken.length===2*m?v.receiptToken:Lr(await lo(i,I.chunkIndex,Fr(v.leafHash)));if(nd(u),0!==v.merkleProof.byteLength&&v.merkleRoot===p&&v.receiptToken===C||await Oa({transferId:s,hash:c,merkleRoot:p,leafHash:v.leafHash,receiptToken:C,chunkIndex:a,data:v.data,metadata:v.metadata,merkleProof:A.buffer}),N!==k.length+A.length+new Uint8Array(v.data).length)throw new Error("Outbound staged chunk has invalid cell length");const E=await Br([k,A,new Uint8Array(v.data)]);for(nd(u);"open"===e.readyState&&e.bufferedAmount>=U;)await new Promise(e=>setTimeout(e,25)),nd(u);if("open"!==e.readyState){tt("Cannot send message because channel is "+e.readyState+" and bufferedAmount is "+String(e.bufferedAmount));break}let P;try{P=ei(t,n,E,i,l,r??void 0)}catch(e){throw new Error("Could not seal outbound message chunk",{cause:e})}nd(u);try{e.send(P.buffer),S&&g++}catch(t){if("open"!==e.readyState)break;throw t}}},Gd=async(e,t,n,r,a,o,i,s)=>{const c=Date.now()+i;for(;Date.now()<c;){nd(s);const i=a.find(e=>e.roomId===t&&e.withPeerId===n&&"connected"===e.connectionState);if(i)try{await Ba(Qd(t,r),n);const a=await wd({channel:r,epc:i,roomId:t,dataChannels:o},e);if(await $d(a,c-Date.now(),void 0,s))return{epc:i,channel:a};try{Jd(a)}catch(e){console.error(e)}nd(s)}catch(e){console.error(e)}else await new Promise(e=>setTimeout(e,500)),nd(s)}return null},Jd=e=>{e.releaseProtocolResources?.(),"closed"!==e.readyState&&e.close()},Yd=async(e,t)=>{if(!e.pqHealingState)return;const n=Date.now()+6e4;for(;fl(e);){if(nd(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))}},Zd=async(e,t,n,r,a=Pi,o=yi,i)=>{if(nd(i),e.epc===t)return e;if(await rd(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),nd(i)),e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),{epc:t,messageKey:s.messageKey,header:s.header,pqContext:s.pqContext}},eu=(e,t,n,r)=>"connected"===e.connectionState&&t.some(t=>t===e&&t.roomId===n&&t.withPeerId===r);class tu 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 nu=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f,p)=>{nd(p),eo(n,l,s),await Ba(Qd(n,e.label),l),nd(p);try{await rd(Pi(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 Yd(r,p);try{const e=await yi(r,n,d);p?.aborted&&(e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),nd(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 $d(w,void 0,void 0,p))throw new Error("Message DataChannel did not open before send timeout");nd(p),await Xd(w,m,y,g,a,o,i,s,c,d,u,p,void 0,()=>Ja(n,l,s));let v=0,k=0,I=!1;for(;v<5;){const e=await to(n,l,s,2e3*(v+1),p);if(nd(p),e){I=!0;break}if("closed"===w.readyState||"closing"===w.readyState){if(eu(b,h,n,l))throw new Error("Message transfer cancelled by peer");if(k>=3)break;k++;const e=await Gd(t,n,l,r,h,f,3e4,p);if(!e)break;const a=await Zd({epc:b,messageKey:m,header:y},e.epc,n,d,Pi,yi,p);b=a.epc,m=a.messageKey,y=a.header,g=a.pqContext??null,w=e.channel,v=0,t.dispatch(Fe({roomId:n,sha512Hex:c,retransmit:!0}));continue}await Xd(w,m,y,g,a,o,i,s,c,d,u,p,Ga(n,l,s),()=>Ja(n,l,s)),v++,t.dispatch(Fe({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{Jd(e())}})(()=>w,v)}finally{m.fill(0),g?.rootKey.fill(0),eo(n,l,s)}},ru=(e,t,n,r,a,o,i,s,c,l)=>async d=>{const u=await Ua(e,d);if(!u)return null;const h=new Uint8Array(u.metadata),f=ao(h),p=new Uint8Array(D);0===u.merkleProof.byteLength?p.set(await zd(n,Fr(u.leafHash),l,D)):p.set(new Uint8Array(u.merkleProof));const y=u.receiptToken.length===2*m?u.receiptToken:Lr(await lo(r,f.chunkIndex,Fr(u.leafHash)));0!==u.merkleProof.byteLength&&u.merkleRoot===a&&u.receiptToken===y||await Oa({transferId:e,hash:t,merkleRoot:a,leafHash:u.leafHash,receiptToken:y,chunkIndex:d,data:u.data,metadata:u.metadata,merkleProof:p.buffer});const g=await Br([h,p,new Uint8Array(u.data)]);return ei(o,i,g,r,c,s??void 0)},au=12e4,ou=async(e,t,n,r,a,o,i,s,c,l=1,d=T,u=.9,h=1)=>{const f=((e,t)=>{const n=[...Ql.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,Wl(e,n))}}:Yl(e,t)})(r,c);let p="",m=!1,y=!1;try{nd(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:v,merkleRootHex:k,hashHex:I,totalChunks:S,chunkHashes:A}=await Vd(e,t,n,c[g],s,f,l,d,u,h);if(f.bindMerkleRoot(k),p=k,nd(f.signal),0===v.length||0===I.length||0===S||0===A.length)return;m=!0;const C=await Va(n,k),E=c[g].channels[w].peerIds.map(e=>({peerId:e,epc:a.find(t=>t.roomId===r&&t.withPeerId===e)})),P="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 rd(Pi(e,m.peerId),u),!n.ratchetState)throw new Error("v4 scheduled send: no ratchet state");await Yd(n,u);const y=await yi(n,e,l),g=await Va(t,i),w=ru(s,c,a,o,i,y.messageKey,y.header,y.pqContext,l,d);if(!$l({epc:n,channelMessageLabel:g,totalChunks:r,sealSlotCell:w,getAckedChunks:()=>Ga(e,m.peerId,s)}))throw new Error("v4 scheduled send: edge has no cover runtime");Vl(n,e,m.peerId,i,s),p+=1,h?.();const b=await to(e,m.peerId,s,au,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,E,S,A,v,k,f.transferId,I,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*b){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)Jd(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){Jd(c),o.push({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})}}}return{outcomes:await Promise.all(o),startedTransfers:i}})(E,({epc:e})=>wd({channel:C,epc:e,roomId:r,dataChannels:o},t),({peerId:e,epc:n},c)=>nu(c,t,r,n,S,A,v,f.transferId,I,e,i,s,a,o,f.signal),f.signal,()=>{y=!0}),x={transferId:f.transferId,merkleRootHex:k,...P};nd(f.signal);const R=x.outcomes.filter(e=>"delivered"===e.status).length;if(0===x.startedTransfers)throw new tu(x,"No authenticated connected peers accepted the send");if(0===R)throw new tu(x,"Message was not delivered to any peer");return x}return}catch(e){if(((e,t,n)=>n||!e&&!t)(m,y,f.signal.aborted)&&(p.length>0&&await Ta(p),t.dispatch(He({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 Na({transferId:f.transferId}),f.finish()}},iu=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(hu.endpoints.disconnectFromPeer.initiate({peerId:e}));return e&&await Ea("deleteDB"),{data:void 0}},su=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(hu.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:e})),a.dispatch(ze({peerId:t,roomId:e}));if(t){if((await Ra()).findIndex(t=>t.roomId===e)>-1){await(e=>Ea("deleteDBUniqueRoom",e))(e);const t=await Ka(e),n=t.length;for(let r=0;r<n;r++)a.dispatch(He({roomId:e,merkleRootHex:t[r].merkleRoot}))}}return{data:void 0}},cu=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{}},lu=[],du=[],uu=[],hu=Dr({reducerPath:"webrtcApi",baseQuery:async({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:a,dataChannels:o},i)=>Md(n,e).runExclusive(async()=>{const{keyPair:s}=i.getState();if(e===s.peerId)throw new Error("Cannot create a connection with oneself.");const c=ba(s.publicKey,t);if(await xa(e))return{data:void 0};const l=Sd(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 _d(e,o,i),{data:void 0};Hl(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 Ud({peerId:e,peerPublicKey:t,roomId:n,peerConnections:a,rtcConfig:r},i);return((e,t,n)=>{e.ondatachannel=async r=>{try{const a=await wd({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 _d(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:lu,dataChannels:uu})}),setDescription:e.mutation({queryFn:(e,t,n)=>Td({...e,peerConnections:lu,iceCandidates:du,dataChannels:uu},t)}),setCandidate:e.mutation({queryFn:(e,t,n)=>(async({peerId:e,roomId:t,candidate:n,peerConnections:r,iceCandidates:a},o)=>Md(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=Sd(r,t,e);if(c>-1){const e=r[c];if(e.ignoreOffer)return{data:void 0};if(e.remoteDescription&&"stable"===e.signalingState){if(kd(s,e.remoteDescription))try{await e.addIceCandidate(s)}catch{const t=e.makingOffer||"stable"!==e.signalingState;!(i.peerId<e.withPeerId)&&t||await Id(e,async()=>{e.iceCandidates.length=0,await o.dispatch(hu.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:lu,iceCandidates:du},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 wd({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&&!ba(i.publicKey,e.withPeerPublicKey))return;const n=e.createDataChannel(t,{ordered:"main"===t,protocol:"raw"}),r=await wd({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=Ad(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:lu,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??T,f=c??.9,p="string"==typeof e?(new TextEncoder).encode(e).length:e.size,m=Hd(p,u,h,f),y=await ua(Wr()),g=await ua(Gr(m));try{return{data:await async function(){return await ou(e,d,n,r,a,o,y,g,t,u,h,f,l)}()}}catch(e){if(e instanceof tu)return{error:e};throw e}})({...e,peerConnections:lu,dataChannels:uu},t)}),disconnect:e.mutation({queryFn:(e,t,n)=>iu({...e,peerConnections:lu,dataChannels:uu},t)}),disconnectFromRoom:e.mutation({queryFn:(e,t,n)=>su({...e,peerConnections:lu,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(hu.endpoints.disconnectFromPeer.initiate(e)),a.dispatch(ze(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(He({roomId:e[r].id,merkleRootHex:e[r].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:lu,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(il(a.roomId,a.withPeerId,o),Mi(a.roomId,a.withPeerId,o),a.ratchetState&&(_o(a.ratchetState),a.ratchetState=void 0),Hl(a),Ni(a),yl(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)Dd(o,t,e),Kd(t,e);i.dispatch(ze({peerId:e,roomId:t})),i.dispatch(je({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(He({roomId:n[a].id,merkleRootHex:n[a].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:lu,dataChannels:uu,iceCandidates:du},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===m&&Ui(o[c],n),await cu(o[c]),r){const{merkleRootHex:n}=await $a(t);i.dispatch(He({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===m&&Ui(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 cu(c[h]),c.splice(h,1),await Ba(Qd(e,n),t));const{merkleRootHex:f}=await $a(n);f.length>0?a&&l.dispatch(He({roomId:e,merkleRootHex:f})):u.isConnected&&!a||l.dispatch(je({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=Sd(s,e,t);n>-1&&await l.dispatch(hu.endpoints.disconnectFromPeer.initiate({peerId:s[n].withPeerId,roomId:e}))}return{data:void 0}})({...e,peerConnections:lu,dataChannels:uu},t)})})}),fu=e=>"number"==typeof e&&Number.isInteger(e)&&4===e,pu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mu=(e,t)=>{const n=Object.keys(e);return n.length===t.length&&n.every(e=>t.includes(e))},yu=new Map,gu=async(t,n,r)=>{try{if("PING"===t.data)return void n.send("PONG");const s=String(t.data);if(s.length>524288)return void console.error("Rejecting oversized signaling message");const c=JSON.parse(s);switch(c.type){case"ping":{const{keyPair:e}=r.getState();await r.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"pong",fromPeerId:e.peerId}}));break}case"peerId":{if(!(pu(i=c)&&mu(i,["type","peerId","challenge","protocolVersion","message"])&&"peerId"===i.type&&"string"==typeof i.peerId&&e.isUUID(i.peerId)&&"string"==typeof i.challenge&&/^[0-9a-f]{64}$/.test(i.challenge)&&"number"==typeof i.protocolVersion&&fu(i.protocolVersion)&&"string"==typeof i.message)){console.error("Rejecting malformed or incompatible auth challenge"),n.close(1002,"protocol-v4 auth required");break}const{keyPair:t}=r.getState();await(async(e,t,n,r)=>{const a=Fr(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 pa(i,a),c=[...new Uint8Array(s)].map(e=>e.toString(16).padStart(2,"0")).join("");r.dispatch(d({peerId:t,challenge:n,signature:c}))})(t,c.peerId,c.challenge,r);break}case"roomId":{if(!fu(c.protocolVersion)||!e.isUUID(c.roomId)||!/^[0-9a-f]{64}$/.test(c.roomUrl)){console.error("Rejecting incompatible or malformed room response");break}let t;c.turnCredentials&&(t={...Ce,iceServers:[...Ce.iceServers??[],{urls:c.turnCredentials.urls,username:c.turnCredentials.username,credential:c.turnCredentials.credential}]}),r.dispatch(xe({id:c.roomId,url:c.roomUrl,rtcConfig:t}));break}case"challenge":if(!(t=>{if(!pu(t))return!1;const n=Object.hasOwn(t,"username");return n===Object.hasOwn(t,"credential")&&mu(t,n?["type","challengeId","protocolVersion","username","credential"]:["type","challengeId","protocolVersion"])&&"challenge"===t.type&&"string"==typeof t.challengeId&&e.isUUID(t.challengeId)&&"number"==typeof t.protocolVersion&&fu(t.protocolVersion)&&(!n||"string"==typeof t.username&&t.username.length>0&&"string"==typeof t.credential&&t.credential.length>0)})(c)){console.error("Rejecting malformed or incompatible auth success"),n.close(1002,"protocol-v4 auth required");break}r.dispatch(u(c));break;case"peerConnection":{if(!fu(c.protocolVersion)||!e.isUUID(c.peer.id)||!ga(c.peer.publicKey))break;if(await xa(c.peer.id,c.peer.publicKey))break;const{keyPair:t,rooms:n}=r.getState(),a=n.findIndex(e=>e.id===c.roomId);if(a>-1&&n[a].onlyConnectWithKnownAddresses){if(!await Pa(c.peer.id,c.peer.publicKey))break}await r.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"peerConnection",roomId:c.roomId,fromPeerId:t.peerId,toPeerId:c.peer.id,protocolVersion:4}}));break}case"peers":{if(!fu(c.protocolVersion)||!e.isUUID(c.roomId)||!Array.isArray(c.peers)){console.error("Rejecting incompatible or malformed peer roster");break}tt("[handleWebSocketMessage] Received peers response:",{roomId:c.roomId,peersCount:c.peers.length,peers:c.peers});const{keyPair:t,rooms:n}=r.getState(),a=n.findIndex(e=>e.id===c.roomId);if(a>-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.isUUID(t.id)||!ga(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[a].peers,c.peers,t);for(const e of o)r.dispatch(De({roomId:c.roomId,...e}));const i=c.peers.length;if(0===i){const{signalingServer:n}=r.getState(),a=Date.now(),o=yu.get(c.roomId)??0;n.isConnected&&n.isVerified&&e.isUUID(t.peerId)&&a-o>5e3&&(yu.set(c.roomId,a),await r.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:t.peerId,roomId:c.roomId,protocolVersion:4}})));break}const s=n[a].onlyConnectWithKnownAddresses;for(let l=0;l<i;l++){if(c.peers[l].publicKey===t.publicKey||c.peers[l].id===t.peerId||!e.isUUID(c.peers[l].id)||!ga(c.peers[l].publicKey))continue;if(!o.some(e=>e.peerId===c.peers[l].id&&e.peerPublicKey===c.peers[l].publicKey))continue;if(!await xa(c.peers[l].id,c.peers[l].publicKey)){if(s){if(!await Pa(c.peers[l].id,c.peers[l].publicKey))continue}await r.dispatch(hu.endpoints.connectWithPeer.initiate({roomId:c.roomId,peerId:c.peers[l].id,peerPublicKey:c.peers[l].publicKey,rtcConfig:n[a].rtcConfig}))}}}break}case"description":if(!(fu(c.protocolVersion)&&e.isUUID(c.fromPeerId)&&ga(c.fromPeerPublicKey)&&e.isUUID(c.roomId)&&(o=c.description,("offer"===o.type||"answer"===o.type||"pranswer"===o.type||"rollback"===o.type)&&"string"==typeof o.sdp&&o.sdp.length<=262144))){fu(c.protocolVersion)||console.error(`Rejecting SDP from ${c.fromPeerId}: incompatible protocol version ${String(c.protocolVersion)} (expected v4). No fallback.`);break}if(!await xa(c.fromPeerId,c.fromPeerPublicKey)){const{rooms:e}=r.getState(),t=e.findIndex(e=>e.id===c.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses){if(!await Pa(c.fromPeerId,c.fromPeerPublicKey))break}await r.dispatch(hu.endpoints.setDescription.initiate({peerId:c.fromPeerId,peerPublicKey:c.fromPeerPublicKey,roomId:c.roomId,description:c.description,rtcConfig:e[t].rtcConfig}))}break;case"candidate":if(!(fu(c.protocolVersion)&&e.isUUID(c.fromPeerId)&&e.isUUID(c.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)})(c.candidate))){console.error(`Rejecting ICE from ${c.fromPeerId}: incompatible protocol version ${String(c.protocolVersion)} (expected v4). No fallback.`);break}if(!await xa(c.fromPeerId)){const{rooms:e}=r.getState(),t=e.findIndex(e=>e.id===c.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses){if(!await Pa(c.fromPeerId))break}await r.dispatch(hu.endpoints.setCandidate.initiate({peerId:c.fromPeerId,roomId:c.roomId,candidate:c.candidate}))}break;case"connection":{const{keyPair:t,rooms:n}=r.getState(),o=n.findIndex(e=>e.id===c.roomId);if(fu(c.protocolVersion)&&e.isUUID(t.peerId)&&e.isHexadecimal(t.challenge)&&e.isHexadecimal(t.signature)&&128===t.signature.length&&64===t.challenge.length&&e.isUUID(c.fromPeerId)&&ga(c.fromPeerPublicKey)&&c.fromPeerId!==t.peerId&&c.fromPeerPublicKey!==t.publicKey&&e.isUUID(c.roomId)&&o>-1&&(a=c.labels,Array.isArray(a)&&a.length<=64&&a.every(e=>"string"==typeof e&&e.length>0&&e.length<=193))){if(await xa(c.fromPeerId,c.fromPeerPublicKey))break;if(n[o].onlyConnectWithKnownAddresses){if(!await Pa(c.fromPeerId,c.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})})(c,n[o].rtcConfig,{recordPeer:e=>{r.dispatch(De(e))},recordChannel:e=>{r.dispatch(Ne(e)),tt(`Connected with ${t.peerId} on websocket channel ${e.label}`)},ensureConnection:async e=>{await r.dispatch(hu.endpoints.connectWithPeer.initiate(e))}})}else fu(c.protocolVersion)||console.error(`Rejecting peer ${c.fromPeerId}: incompatible protocol version ${String(c.protocolVersion)} (expected v4). No fallback.`);break}case"error":console.error(c);break;default:console.error("Unknown message type "+JSON.stringify(c))}}catch(e){return void console.error("[p2party] WebSocket message handling error:",e)}var a,o,i},wu=(e,t,n=10,r=20)=>{let a=0;const o=setInterval(()=>{e.readyState===WebSocket.OPEN?(clearInterval(o),t()):(a+=1,tt(`Waiting for connection... Attempt ${String(a)}`),a>=n&&(clearInterval(o),tt("WebSocket failed to connect after multiple attempts, closing..."),e.removeEventListener("message",()=>{}),e.removeEventListener("open",()=>{}),e.removeEventListener("close",()=>{}),e.close()))},r)};let bu=null;const vu=(e,t)=>(bu&&(bu.removeEventListener("message",()=>{}),bu.removeEventListener("open",()=>{}),bu.removeEventListener("close",()=>{}),bu.close(),bu=null,tt("WebSocket manually disconnected")),t.dispatch(Je.disconnect()),{data:void 0}),ku=(t,n)=>{if(bu?.readyState===WebSocket.OPEN){const{keyPair:r}=n.getState();return e.isUUID(r.peerId)&&e.isHexadecimal(r.challenge)&&e.isHexadecimal(r.signature)&&128===r.signature.length&&64===r.challenge.length&&wu(bu,()=>{bu?.send(JSON.stringify(t.content))}),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},Iu=({peerId:t,peerPublicKey:n,roomId:r},a)=>{if(bu?.readyState===WebSocket.OPEN){const{keyPair:o}=a.getState();return e.isUUID(o.peerId)&&e.isHexadecimal(o.challenge)&&e.isHexadecimal(o.signature)&&128===o.signature.length&&64===o.challenge.length&&ga(n)&&(a.dispatch(De({roomId:r,peerId:t,peerPublicKey:n})),a.dispatch(Ne({roomId:r,label:"main",peerId:t})),tt(`Connected with ${o.peerId} on channel main`),wu(bu,()=>{bu?.send(JSON.stringify({type:"connection",roomId:r,fromPeerId:o.peerId,toPeerId:t,labels:["main"],protocolVersion:4}))})),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},Su=Dr({reducerPath:"signalingServerApi",baseQuery:async({signalingServerUrl:e},t)=>{const{keyPair:n,signalingServer:r}=t.getState();if(bu||r.isConnected||r.isEstablishingConnection)return tt("WebSocket already connected"),{data:void 0};t.dispatch(Je.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 Ea("getIdentityEd25519"),l=s?Lr(new Uint8Array(s.pub)):"",d=s?new Uint8Array(s.secret):void 0,u=d?Lr(d):"";d?.fill(0);const h=/^[0-9a-f]{128}$/;if(ga(o)&&h.test(i)){if(!s||l!==o||u!==i){const e=Fr(i);await ja({pub:r(Fr(o)),secret:r(e)}),e.fill(0)}}else{if(s)o=l,i=u;else{const e=localStorage.getItem("publicKey")??"",t=localStorage.getItem("secretKey")??"";if(ga(e)&&h.test(t)){o=e,i=t;const n=Fr(i);await ja({pub:r(Fr(o)),secret:r(n)}),n.fill(0)}else{const e=await fa();o=Lr(e.publicKey),i=Lr(e.secretKey),await ja({pub:r(e.publicKey),secret:r(e.secretKey)}),e.secretKey.fill(0)}}t.dispatch(c({publicKey:o,secretKey:i}))}wa(o,"Self Ed25519 identity"),localStorage.removeItem("secretKey");const f=i.length>0?i:n.secretKey,p=o.length>0?o:n.publicKey;if(f.length>0&&p.length>0){const e=await Fa();if(!(null!=e&&await Bc(new Uint8Array(e.pub),new Uint8Array(e.crossSig),Fr(p)))){const e=await ho(),t=await Nc(e.publicKey,Fr(f));await(a={pub:r(e.publicKey),secret:r(e.secretKey),crossSig:r(t)},Ea("setIdentityX25519",a))}}const m=e+"?publickey="+o;return bu=new WebSocket(m),bu.binaryType="arraybuffer",await new Promise((e,n)=>{if(!bu)return void n(new Error("WebSocket is null"));const r=bu;try{r.onopen=()=>{tt("WebSocket connected to:",m),t.dispatch(Je.connectionEstablished()),e({data:void 0})},r.onerror=e=>{console.error("WebSocket error:",e),bu&&(bu.removeEventListener("message",()=>{}),bu.removeEventListener("open",()=>{}),bu.removeEventListener("close",()=>{}),bu.close(),bu=null),t.dispatch(Je.disconnect()),n(new Error("WebSocket connection failed"))},r.onmessage=async e=>{await gu(e,r,t)},r.onclose=()=>{bu&&(bu.removeEventListener("message",()=>{}),bu.removeEventListener("open",()=>{}),bu.removeEventListener("close",()=>{}),bu.close(),bu=null),t.dispatch(Je.disconnect()),tt("WebSocket disconnected"),e({data:void 0})}}catch(e){n(e instanceof Error?e:new Error(String(e)))}return()=>{bu&&(tt("Cleaning up WebSocket connection..."),bu.removeEventListener("message",()=>{}),bu.removeEventListener("open",()=>{}),bu.removeEventListener("close",()=>{}),bu.close(),bu=null)}})}catch(e){return bu&&(bu.removeEventListener("message",()=>{}),bu.removeEventListener("open",()=>{}),bu.removeEventListener("close",()=>{}),bu.close(),bu=null),t.dispatch(Je.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:vu}),sendMessage:e.mutation({queryFn:ku}),connectWithPeer:e.mutation({queryFn:Iu})})}),Au=new Map,Cu=t.createListenerMiddleware();Cu.startListening({matcher:t.isAnyOf(Me,xe,qe,He,Ve),effect:async(t,n)=>{try{if(Me.match(t)){const{roomId:r,connectingToPeers:a}=t.payload;if(tt("[roomListenerMiddleware] setConnectingToPeers:",{roomId:r,connectingToPeers:a}),a){const{signalingServer:t,keyPair:a,rooms:o}=n.getState(),i=o.findIndex(e=>e.id===r);if(tt("[roomListenerMiddleware] setConnectingToPeers check:",{isConnected:t.isConnected,peerId:a.peerId,isPeerIdUUID:e.isUUID(a.peerId),roomIndex:i,roomId:i>-1?o[i].id:"N/A"}),t.isConnected&&t.isVerified&&e.isUUID(a.peerId)&&i>-1&&e.isUUID(o[i].id)){const e=Date.now();e-(Au.get(r)??0)<2e3?tt("[roomListenerMiddleware] Skipping peers request - debounced"):(Au.set(r,e),tt("[roomListenerMiddleware] Sending peers request from setConnectingToPeers"),await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:a.peerId,roomId:r,protocolVersion:4}})))}n.dispatch(Me({roomId:r,connectingToPeers:!1}))}}else if(xe.match(t)){const{signalingServer:i,keyPair:s,rooms:c}=n.getState(),{url:l,id:d,onlyConnectWithKnownPeers:u}=t.payload;if(tt("[roomListenerMiddleware] setRoom:",{url:l,id:d,onlyConnectWithKnownPeers:u}),64===l.length&&null!=u&&localStorage.setItem(l+"-onlyConnectWithKnownPeers",String(u)),64===l.length&&e.isUUID(d)){tt("[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=be(c[t].policy).slice().buffer;await(r=l,a=d,o=u,Ea("setDBUniqueRoom",r,a,o));const h=await Ka(d),f=h.length;for(let e=0;e<f;e++)n.dispatch(qe({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}));tt("[roomListenerMiddleware] Checking peers request conditions:",{isConnected:i.isConnected,isPeerIdUUID:e.isUUID(s.peerId),peerId:s.peerId,roomIndex:t,roomId:t>-1?c[t].id:"N/A"}),i.isConnected&&i.isVerified&&e.isUUID(s.peerId)&&t>-1&&e.isUUID(c[t].id)&&(tt("[roomListenerMiddleware] Sending peers request for room:",c[t].id),await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:s.peerId,roomId:c[t].id,protocolVersion:4}})))}}else if(qe.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 Va(s[l].messages[t].channelLabel,s[l].messages[t].merkleRootHex),o=Fr(a);await n.dispatch(hu.endpoints.disconnectFromChannelLabel.initiate({roomId:e,label:r,messageHash:o,alsoDeleteData:!1,alsoSendFinishedMessage:!0}))}}}else if(He.match(t)){const{merkleRootHex:e,hashHex:n}=t.payload;if(!e&&!n)return;if(e&&e.length!==2*m)return;if(n&&n.length!==2*m)return;e?(await Ta(e),await Na({merkleRootHex:e})):n&&await Na({hashHex:n})}else if(Ve.match(t)){const e=t.payload;await n.dispatch(hu.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:!0}))}}catch(e){console.error("p2party: room listener effect failed",e)}var r,a,o}});const Eu=t.createListenerMiddleware();Eu.startListening({matcher:t.isAnyOf(c,l,d,u,h),effect:async(t,n)=>{if(c.match(t)){const{publicKey:e,secretKey:n}=t.payload;64===e.length&&128===n.length&&(localStorage.setItem("publicKey",t.payload.publicKey),localStorage.removeItem("secretKey"))}else if(l.match(t)){const{peerId:r,challenge:a,signature:o,challengeId:i,username:s,credential:c}=t.payload;if(e.isUUID(r)&&e.isUUID(i)&&e.isHexadecimal(a)&&e.isHexadecimal(o)&&64===a.length&&128===o.length){n.dispatch(Je.connectionVerified()),localStorage.setItem("peerId",r),localStorage.setItem("challenge",a),localStorage.setItem("signature",o),localStorage.setItem("challengeId",i);const{keyPair:l,rooms:d,commonState:u}=n.getState(),h=64===u.currentRoomUrl.length?d.findIndex(e=>e.url===u.currentRoomUrl):-1;h>-1?(t.payload.username&&t.payload.credential&&n.dispatch(Be({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:s,credential:c}]})),e.isUUID(d[h].id)&&n.dispatch(Me({roomId:d[h].id,connectingToPeers:!0}))):e.isUUID(l.peerId)&&64===u.currentRoomUrl.length&&await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:l.peerId,roomUrl:u.currentRoomUrl,protocolVersion:4}}))}}else if(d.match(t)){const{peerId:r,challenge:a,signature:o}=t.payload;e.isUUID(r)&&e.isHexadecimal(a)&&e.isHexadecimal(o)&&64===a.length&&128===o.length&&(localStorage.setItem("peerId",r),localStorage.setItem("challenge",a),localStorage.setItem("signature",o),await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"challenge",fromPeerId:r,challenge:a,signature:o,protocolVersion:4}})))}else if(u.match(t)){const{challengeId:r}=t.payload;if(e.isUUID(r)){n.dispatch(Je.connectionVerified()),localStorage.setItem("challengeId",r);const{keyPair:a,rooms:o,commonState:i}=n.getState(),s=64===i.currentRoomUrl.length?o.findIndex(e=>e.url===i.currentRoomUrl):-1;s>-1?(t.payload.username&&t.payload.credential&&n.dispatch(Be({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:t.payload.username,credential:t.payload.credential}]})),e.isUUID(o[s].id)?n.dispatch(Me({roomId:o[s].id,connectingToPeers:!0})):e.isUUID(a.peerId)&&64===i.currentRoomUrl.length&&await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:a.peerId,roomUrl:i.currentRoomUrl,protocolVersion:4}}))):e.isUUID(a.peerId)&&64===i.currentRoomUrl.length&&await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:a.peerId,roomUrl:i.currentRoomUrl,protocolVersion:4}}))}}else h.match(t)&&(console.trace("[keyPairListenerMiddleware] resetIdentity dispatched"),localStorage.setItem("peerId",""),localStorage.setItem("challengeId",""),localStorage.setItem("publicKey",""),localStorage.removeItem("secretKey"),localStorage.setItem("challenge",""),localStorage.setItem("signature",""))}});const Pu=t.configureStore({reducer:{commonState:o,keyPair:f,rooms:Qe,signalingServer:Ye,[Su.reducerPath]:Su.reducer,[hu.reducerPath]:hu.reducer},middleware:e=>e({serializableCheck:{ignoredPaths:[`${hu.reducerPath}.mutations`,`${hu.reducerPath}.queries`,`${Su.reducerPath}.mutations`,`${Su.reducerPath}.queries`],ignoredActionPaths:["payload","error","meta.arg.originalArgs","meta.baseQueryMeta"]}}).concat([Su.middleware,hu.middleware,Cu.middleware,Eu.middleware])}),xu=Pu.dispatch,Ru=new Uint8Array([80,50,80,83,69,83,83,0]),Mu=262144,Ku=Ru.length+4+24+32+32+32+2,Uu="p2party-session",_u=e=>Uint8Array.from(e);function Du(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 Tu=(e,t)=>{if(!Number.isSafeInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new RangeError(`${t} must be a non-negative safe integer`)},Ou=(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},Nu=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Bu=async e=>new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",e.slice().buffer)),qu=async e=>{const t=new WebAssembly.Memory({initial:32,maximum:32});return e?.wasmBinary?await na({wasmBinary:(n=e.wasmBinary,n instanceof Uint8Array?n.slice().buffer:n.slice(0)),wasmMemory:t,getRandomValue:aa}):await ua(t);var n},Lu=async(e={})=>{const t=await qu(e);let n=null,r=null,a=null;try{if(e.ed25519KeyPair)Du(e.ed25519KeyPair.publicKey,"ed25519KeyPair.publicKey",b),Du(e.ed25519KeyPair.secretKey,"ed25519KeyPair.secretKey",v),n=_u(e.ed25519KeyPair.publicKey),r=_u(e.ed25519KeyPair.secretKey);else{const e=await fa(t);n=e.publicKey,r=e.secretKey}const o=await ho(t);a=o.secretKey;const i=await Nc(o.publicKey,r,t);if(!await Bc(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)}},Fu=(e,t)=>e.N===t.N&&e.PN===t.PN&&Ou(e.dhPub,t.dhPub);class zu{protocolVersion=4;#e;#ge=new Cd;#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 te(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){Du(e,"plaintext");const t=_u(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/T)),a=[],o=[];try{for(let t=0;t<r;t++){const r=t*T,o=Math.min(T,Math.max(0,n-r)),i=globalThis.crypto.getRandomValues(new Uint8Array(T));i.set(e.subarray(r,r+o),0),a.push(i)}const i=await Bu(e),s=new Uint8Array(r*m);for(let e=0;e<a.length;e++)s.set(qd(a[e],t),e*m);const c=Uint8Array.from(await Fd(s,t));for(let e=0;e<a.length;e++){const r=await zd(s,qd(a[e],t),t,D),c=Math.min(T,Math.max(0,n-e*T)),l=ro({schemaVersion:1,messageType:oo.Unknown,hash:i,totalSize:n,date:new Date(0),name:Uu,chunkStartIndex:0,chunkEndIndex:c,chunkIndex:e}),d=new Uint8Array(N);d.set(l,0),d.set(r,_),d.set(a[e],_+D),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=Uo(this.#be);const i=Ao(n,this.#e);r=i.messageKey,a=this.#ve.currentMessageContext();const s=e.plaintexts.map(t=>ei(r,i.header,t,e.root,this.#e,a));return Do(this.#be,n),this.#ve.noteApplicationMessage(),o=!0,{protocolVersion:4,root:_u(e.root),frames:s}}finally{t.fill(0),r?.fill(0),n&&!o&&_o(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(Du(e.root,"message.root",m),!Array.isArray(e.frames)||0===e.frames.length)throw new Error("session: encrypted message has no frames");for(const t of e.frames)if(Du(t,"message frame"),t.length!==j)throw new Error("session: invalid encrypted frame length");const t=_u(e.root),n=e.frames.map(_u);return this.#ge.runExclusive(async()=>{this.#j();const e=n.map(e=>qo(e));for(let t=1;t<e.length;t++)if(!Fu(e[0].header,e[t].header))throw new Error("session: mixed ratchet headers");const r=new Set;for(const t of e){const e=Nu(t.nonce);if(r.has(e))throw new Error("session: duplicate chunk nonce");r.add(e)}const a=Uo(this.#be),o=new Map(this.#ve.activeReceiveKeys),i=[];let s=!1;try{const e=[];for(const r of n){const n=ti(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=ao(n.decrypted.subarray(0,_));e.push({metadata:s,chunk:n.decrypted.subarray(_+D)})}const r=await(async e=>{if(0===e.length)throw new Error("session: encrypted message has no frames");const t=e[0].metadata;Tu(t.totalSize,"metadata.totalSize");const n=Math.max(1,Math.ceil(t.totalSize/T));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(Tu(e.chunkIndex,"metadata.chunkIndex"),Tu(e.chunkStartIndex,"metadata.chunkStartIndex"),Tu(e.chunkEndIndex,"metadata.chunkEndIndex"),Tu(e.totalSize,"metadata.totalSize"),1!==e.schemaVersion||e.messageType!==oo.Unknown||e.name!==Uu||0!==e.date.getTime())throw new Error("session: unsupported encrypted metadata");if(e.totalSize!==t.totalSize||!Ou(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(T,Math.max(0,t.totalSize-e.chunkIndex*T));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*T)}const o=await Bu(a),i=Ou(o,t.hash);if(o.fill(0),!i)throw a.fill(0),new Error("session: plaintext hash mismatch");return a})(e);return Do(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);_o(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 ju;const e=await this.#ve.prepareHealingOffer();return this.#ve.markPendingDispatched(),{frame:e,requiresPersistBeforeSend:!0}})}async acceptControlFrame(e){Du(e,"control frame",j);const t=_u(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(),Vu(this.#be,this.#ve,this.#we)))}async destroy(){await this.#ge.runExclusive(async()=>{this.#p||(_o(this.#be),this.#ve.destroy(),this.#p=!0)})}}const ju={frame:null,requiresPersistBeforeSend:!1},Hu=(e,t,n)=>(Tu(n,"snapshot counter"),e.setBigUint64(t,BigInt(n),!1),t+8),Vu=(e,t,n)=>{(e=>{if(Du(e.rootKey,"snapshot.rootKey",32),Du(e.dhSelfPub,"snapshot.dhSelfPub",32),Du(e.dhSelfSec,"snapshot.dhSelfSec",32),e.sendingChainKey&&Du(e.sendingChainKey,"snapshot.sendingChainKey",32),e.receivingChainKey&&Du(e.receivingChainKey,"snapshot.receivingChainKey",32),e.dhRemotePub&&Du(e.dhRemotePub,"snapshot.dhRemotePub",32),Tu(e.Ns,"snapshot.Ns"),Tu(e.Nr,"snapshot.Nr"),Tu(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>G)throw new Error("snapshot: too many skipped message keys")})(e);const r=Mo(e),a=t.serialize();if(0===a.length||a.length>Mu)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(Ku+32*t+72*r.skippedMessageKeys.length+4+a.length),i=new DataView(o.buffer);let s=0;o.set(Ru,s),s+=Ru.length,o[s++]=4,o[s++]=4,o[s++]=e,o[s++]=(e=>{if(e===$)return 3;if(e===V)return 4;if(e===Q)return 5;throw new Error("snapshot: unsupported root suite")})(r.rootSuite),s=Hu(i,s,r.Ns),s=Hu(i,s,r.Nr),s=Hu(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)Du(new Uint8Array(e.dhPub),"snapshot.skipped.dhPub",32),Du(new Uint8Array(e.messageKey),"snapshot.skipped.messageKey",32),o.set(new Uint8Array(e.dhPub),s),s+=32,s=Hu(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)}},$u=e=>{Du(e,"snapshot");const t=_u(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(!Ou(o(Ru.length),Ru))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 $;if(4===e)return V;if(5===e)return Q;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>G)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=`${Nu(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>Mu)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 A=Ko({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:A,pqCheckpoint:S,amInitiator:!!(8&e)}}finally{if(t.fill(0),!r)for(const e of a)e.fill(0)}},Qu=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");Du(e.ed25519PublicKey,"identity.ed25519PublicKey",b),Du(e.x25519PublicKey,"identity.x25519PublicKey",x),Du(e.x25519SecretKey,"identity.x25519SecretKey",R),Du(e.x25519CrossSignature,"identity.x25519CrossSignature",g)})(e.identity),Du(e.peerIdentityEd25519PublicKey,"peerIdentityEd25519PublicKey",b),!e.channel||"object"!=typeof e.channel)throw new TypeError("channel binding is required");if(Du(e.channel.channelId,"channel.channelId"),0===e.channel.channelId.length)throw new RangeError("channel.channelId must not be empty");Du(e.channel.localFingerprint,"channel.localFingerprint",32),Du(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(Du(t.pin,"pin"),0===t.pin.length)throw new RangeError("pin must not be empty");a=_u(t.pin)}else if(void 0!==t.pin)throw new Error("pin must not be provided in nopin mode");const o=_u(e.identity.x25519SecretKey),i=_u(e.identity.ed25519PublicKey),s=_u(e.identity.x25519PublicKey),c=_u(e.identity.x25519CrossSignature),l=_u(e.peerIdentityEd25519PublicKey),d=_u(e.channel.channelId),u=_u(e.channel.localFingerprint),h=_u(e.channel.remoteFingerprint);let f=null,p=null,m=null,y=null,w=null;try{const t=await qu(e.crypto);await(async(e,t)=>{const n=new Uint8Array(x);n[0]=9;const r=fo(e.x25519SecretKey,n,t);try{if(!Ou(r,e.x25519PublicKey))throw new Error("identity X25519 public and secret keys do not match")}finally{r.fill(0)}if(!await Bc(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 g="initiator"===e.role,b=qc({channelId:d,ikInitiator:g?i:l,ikResponder:g?l:i,fpInitiator:g?u:h,fpResponder:g?h:u,pqMode:r}),v=await el(e.transport,{mode:n,pqMode:r,pin:a,channelInput:b,amInitiator:g,idSelfSec:o,selfIdentityX25519Pub:s,selfIdentityCrossSignature:c,peerIdentityEd25519Pub:l},t);y=v.state,f=v.secret,p=v.pqHealing.rootKey,m=v.pqHealing.binding,w=new Ac({module:t,pqMode:r,rootSuite:y.rootSuite,binding:m,rootKey:p,nextOfferer:v.pqHealing.nextOfferer,amInitiator:g});const k=new zu(y,t,w,g);return y=null,w=null,k}finally{o.fill(0),a?.fill(0),f?.fill(0),p?.fill(0),m?.fill(0),y&&_o(y),w?.destroy()}},Wu=async(e,t)=>{const n=$u(e);let r=null;try{const e=await qu(t),a=Ac.readCheckpointBinding(n.pqCheckpoint);try{r=Ac.restore(n.pqCheckpoint,{module:e,pqMode:te(n.state.rootSuite),rootSuite:n.state.rootSuite,binding:a,amInitiator:n.amInitiator})}finally{a.fill(0)}const o=new zu(n.state,e,r,n.amInitiator);return r=null,o}catch(e){throw _o(n.state),r?.destroy(),e}finally{n.pqCheckpoint.fill(0)}};var Xu=["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 Gu=e=>e.normalize("NFKD"),Ju=async e=>{try{return await(async e=>{const t=Gu(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=Xu.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}},Yu=32,Zu=`v${String(1)}.`,eh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",th=/^[0-9a-fA-F]{64}$/u,nh=/^[A-Za-z0-9_-]{43}$/u,rh=(new TextEncoder).encode("p2party/room-invite/checksum/v1\0");if(2048!==Xu.length||2048!==new Set(Xu).size)throw new Error("Room invite word list must contain 2,048 unique words");const ah=new Map(Xu.map((e,t)=>[e,t])),oh=e=>{if(!(e instanceof Uint8Array))throw new TypeError("Room capability must be a Uint8Array");if(e.length!==Yu)throw new Error("Room capability must be exactly 32 bytes");return e},ih=()=>globalThis.crypto.getRandomValues(new Uint8Array(Yu)),sh=e=>{const t=oh(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+=eh[a>>>18&63],n+=eh[a>>>12&63],r>1&&(n+=eh[a>>>6&63]),r>2&&(n+=eh[63&a])}return n},ch=e=>{if("string"!=typeof e||!nh.test(e))throw new Error("Room capability must be exactly 43 unpadded base64url characters");if(3&eh.indexOf(e.at(-1)??""))throw new Error("Room capability base64url encoding is not canonical");const t=new Uint8Array(Yu);let n=0,r=0,a=0;for(const o of e)for(n=n<<6|eh.indexOf(o),r+=6;r>=8;)r-=8,t[a]=n>>>r&255,a+=1,n&=(1<<r)-1;if(a!==Yu||sh(t)!==e)throw new Error("Room capability base64url encoding is not canonical");return t},lh=e=>{if("string"!=typeof e)throw new TypeError("Room capability must be a string");return e.startsWith(Zu)||e.startsWith(`#${Zu}`)?hh(e):64===e.length?(e=>{if(!th.test(e))throw new Error("Room capability hex must contain exactly 64 hex digits");const t=new Uint8Array(Yu);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(2*n,2*n+2),16);return t})(e):ch(e)},dh=e=>(e=>{let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t})(lh(e)),uh=e=>`${Zu}${sh(e)}`,hh=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(Zu))throw new Error("Unsupported room invite version");return ch(t.slice(Zu.length))},fh=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})(rh,e));return new Uint8Array(t)[0]},ph=async(t,n="wss://signaling.p2party.com/ws",r={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},o={})=>{if(t=dh(t),null===o||"object"!=typeof o||Array.isArray(o))throw new Error("Invalid room connection options");const{keyPair:i,signalingServer:s,rooms:c,commonState:l}=Pu.getState(),d=c.findIndex(e=>e.url===t);let u;if(-1===d){const e=(await Ra()).find(e=>e.roomUrl===t);e?.roomPolicy&&(u=ve(new Uint8Array(e.roomPolicy)))}if(u&&o.policy&&!Ie(u,o.policy))throw new Error("Persisted room policy is immutable");const h=ke(o.policy??(d>-1?c[d].policy:u??Ae));if("legacy-signaling"!==h.rendezvousMode)throw new Error("Private rendezvous room connections are not wired yet");if("pin"===h.authMode){if(void 0!==o.pin){f=t,p=o.pin,id.put(f,p);const e=d>-1?c[d].id:"";e&&await pd(e)}else if(!(e=>id.has(e))(t))throw new Error("PIN room connection requires a PIN")}else{if(void 0!==o.pin)throw new Error("PIN must not be provided for a no-PIN room");sd(t)}var f,p;xu(-1===d?xe({url:t,id:"",rtcConfig:r,policy:h}):Re({roomContext:t,policy:h})),l.currentRoomUrl!==t&&xu(a(t)),s.isConnected&&s.isVerified&&e.isUUID(i.peerId)?-1===d?await xu(Su.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:i.peerId,roomUrl:t,protocolVersion:4}})):xu(Me({roomId:c[d].id,connectingToPeers:!0})):await xu(Su.endpoints.connectWebSocket.initiate(n))},mh=3e4,yh=async(e,t={})=>{const n=dh(e),{timeoutMs:r=mh,signal:a}=t,o=()=>{const e=$e(Pu.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=Pu.subscribe(d),d()})},gh=async(e,t,n,r={})=>{const{timeoutMs:a,signal:o,...i}=r;return await ph(e,t,n,i),await yh(e,{timeoutMs:a,signal:o})},wh=async(e,t={})=>{const{count:n=1,timeoutMs:r=mh,signal:a}=t,o=()=>{const t=$e(Pu.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=Pu.subscribe(u),u()})},bh=(e,t)=>{const n=new Set,r=()=>{const r=$e(Pu.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),vh(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=Pu.subscribe(r);return r(),a},vh=async(e,t,n=!0)=>{if(!e&&!t)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"txt",category:io.Text};try{const{keyPair:r,rooms:a}=Pu.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:io.Text};const c=a[i].messages[s].messageType,l=so(c),d=(e=>{switch(e){case oo.ImagePNG:return"png";case oo.ImageJPEG:return"jpeg";case oo.ImageJPG:return"jpg";case oo.ImageGIF:return"gif";case oo.ImageBMP:return"bmp";case oo.ImageTIFF:return"tiff";case oo.ImageSVG:return"svg";case oo.ImageWEBP:return"webp";case oo.ImageHEIC:return"heic";case oo.DocumentPDF:return"pdf";case oo.DocumentDOC:return"doc";case oo.DocumentDOCX:return"docx";case oo.DocumentXLS:return"xls";case oo.DocumentXLSX:return"xlsx";case oo.DocumentPPT:return"ppt";case oo.DocumentPPTX:return"pptx";case oo.DocumentTXT:return"txt";case oo.DocumentRTF:return"rtf";case oo.DocumentODT:return"odt";case oo.AudioMP3:return"mp3";case oo.AudioWAV:return"wav";case oo.AudioAAC:return"aac";case oo.AudioFLAC:return"flac";case oo.AudioOGG:return"ogg";case oo.AudioM4A:return"m4a";case oo.VideoMP4:return"mp4";case oo.VideoAVI:return"avi";case oo.VideoMKV:return"mkv";case oo.VideoMOV:return"mov";case oo.VideoWMV:return"wmv";case oo.VideoFLV:return"flv";case oo.VideoWEBM:return"webm";case oo.CompressedZIP:return"zip";case oo.CompressedRAR:return"rar";case oo.Compressed7Z:return"7z";case oo.CompressedTAR:return"tar";case oo.CompressedGZ:return"gz";case oo.CodeHTML:return"html";case oo.CodeCSS:return"css";case oo.CodeJS:return"js";case oo.CodeTS:return"ts";case oo.CodeJSX:return"jsx";case oo.CodeTSX:return"tsx";case oo.CodeJSON:return"json";case oo.CodeXML:return"xml";case oo.CodePY:return"py";case oo.CodeJAVA:return"java";case oo.CodeC:return"c";case oo.CodeCPP:return"cpp";case oo.CodeCS:return"cs";case oo.CodeRB:return"rb";case oo.CodePHP:return"php";case oo.CodeSQL:return"sql";case oo.EbookEPUB:return"epub";case oo.EbookMOBI:return"mobi";case oo.EbookAZW:return"azw";case oo.FontTTF:return"ttf";case oo.FontOTF:return"otf";case oo.ImageICO:return"ico";case oo.ExecutableEXE:return"exe";case oo.ExecutableDMG:return"dmg";case oo.ExecutableAPK:return"apk";default:return""}})(c),u=(e=>{switch(e){case oo.Text:return io.Text;case oo.ImagePNG:case oo.ImageJPEG:case oo.ImageJPG:case oo.ImageGIF:case oo.ImageBMP:case oo.ImageTIFF:case oo.ImageSVG:case oo.ImageWEBP:case oo.ImageHEIC:case oo.ImageICO:return io.Image;case oo.DocumentPDF:case oo.DocumentDOC:case oo.DocumentDOCX:case oo.DocumentXLS:case oo.DocumentXLSX:case oo.DocumentPPT:case oo.DocumentPPTX:case oo.DocumentTXT:case oo.DocumentRTF:case oo.DocumentODT:return io.Document;case oo.AudioMP3:case oo.AudioWAV:case oo.AudioAAC:case oo.AudioFLAC:case oo.AudioOGG:case oo.AudioM4A:return io.Audio;case oo.VideoMP4:case oo.VideoAVI:case oo.VideoMKV:case oo.VideoMOV:case oo.VideoWMV:case oo.VideoFLV:case oo.VideoWEBM:return io.Video;case oo.CompressedZIP:case oo.CompressedRAR:case oo.Compressed7Z:case oo.CompressedTAR:case oo.CompressedGZ:return io.Compressed;case oo.CodeHTML:case oo.CodeCSS:case oo.CodeJS:case oo.CodeJSX:case oo.CodeTS:case oo.CodeTSX:case oo.CodeJSON:case oo.CodeXML:case oo.CodePY:case oo.CodeJAVA:case oo.CodeC:case oo.CodeCPP:case oo.CodeCS:case oo.CodeRB:case oo.CodePHP:case oo.CodeSQL:return io.Code;case oo.EbookEPUB:case oo.EbookMOBI:case oo.EbookAZW:return io.Ebook;case oo.FontTTF:case oo.FontOTF:return io.Font;case oo.ExecutableEXE:case oo.ExecutableDMG:case oo.ExecutableAPK:return io.Executable;default:return io.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!==oo.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!==oo.Text&&100===h){const e=a[i].messages[s].filename,t=a[i].messages[s].fromPeerId===r.peerId?await((e,t,n,r)=>Ea("assembleToOPFS",e,t,n,r))(a[i].messages[s].merkleRootHex,a[i].messages[s].totalSize,e,l):await((e,t,n,r)=>Ea("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)=>Ea("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===oo.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:io.Text}}},kh=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*m)throw new Error("Invalid Merkle root length");if(n&&"string"!=typeof n&&n.length!==m)throw new Error("Invalid Merkle root length");if(r&&"string"==typeof r&&r.length!==2*m)throw new Error("Invalid hash length");if(r&&"string"!=typeof r&&r.length!==m)throw new Error("Invalid hash length");const o=n&&"string"==typeof n?n:n&&"string"!=typeof n?Lr(n):"",i=r&&"string"==typeof r?r:r&&"string"!=typeof r?Lr(r):"";Zl(e,{transferId:a,merkleRootHex:o||void 0,hashHex:i||void 0});const{rooms:s}=Pu.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*m){const n=await Va(t,s[c].messages[l].merkleRootHex);await Pu.dispatch(hu.endpoints.disconnectFromChannelLabel.initiate({roomId:s[c].id,label:n,alsoDeleteData:!0})),Pu.dispatch(He({roomId:e,merkleRootHex:s[c].messages[l].merkleRootHex}))}},Ih={store:Pu,commonStateSelector:e=>e.commonState,signalingServerSelector:e=>e.signalingServer,roomSelector:$e,keyPairSelector:e=>e.keyPair,connect:ph,connectToSignalingServer:async(e,t="wss://signaling.p2party.com/ws")=>{e=dh(e);const{signalingServer:n,rooms:r,commonState:o}=Pu.getState();-1===r.findIndex(t=>t.url===e)&&xu(xe({url:e,id:""})),o.currentRoomUrl!==e&&xu(a(e)),n.serverUrl===t&&(n.isConnected||n.isEstablishingConnection)||await xu(Su.endpoints.connectWebSocket.initiate(t))},disconnectFromSignalingServer:async()=>{await xu(Su.endpoints.disconnectWebSocket.initiate(void 0))},disconnectFromRoom:async(e,t=!1)=>{await xu(hu.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:t}))},disconnectFromAllRooms:async(e=!1,t=[])=>{await xu(hu.endpoints.disconnectFromAllRooms.initiate({deleteMessages:e,exceptionRoomIds:t}))},disconnectFromPeer:async e=>{await xu(hu.endpoints.disconnectFromPeer.initiate({peerId:e}))},allowConnectionRelay:(e,t=!0)=>{const{rooms:n}=Pu.getState(),r=n.findIndex(t=>t.id===e);r>-1&&xu(Ue({roomId:n[r].id,canBeConnectionRelay:t}))},onlyAllowConnectionsFromAddressBook:async(e,t)=>{let n;try{n=dh(e)}catch{return}e=n;const{rooms:r}=Pu.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 Pa(r[a].peers[t].peerId,r[a].peers[t].peerPublicKey)||await xu(hu.endpoints.disconnectFromPeer.initiate({peerId:r[a].peers[t].peerId,roomId:r[a].id,alsoDeleteData:!1}))}}xu(xe({url:a>-1?r[a].url:e,id:a>-1?r[a].id:"",onlyConnectWithKnownPeers:t}))},addPeerToAddressBook:(e,t,n)=>Ea("setDBAddressBookEntry",e,t,n),getPeerAddressBookEntry:Pa,getAllPeersInAddressBook:()=>Ea("getAllDBAddressBookEntries"),getAllPeersInBlacklist:()=>Ea("getAllDBBlacklisted"),deletePeerFromAddressBook:async(t,n,r)=>{const a=await((e,t,n)=>Ea("deleteDBAddressBookEntry",e,t,n))(t,n,r);e.isUUID(a)&&await xu(hu.endpoints.disconnectFromPeer.initiate({peerId:a,alsoDeleteData:!1}))},blacklistPeer:async(e,t)=>{await((e,t)=>Ea("setDBPeerInBlacklist",e,t))(e,t),await xu(hu.endpoints.disconnectFromPeer.initiate({peerId:e,alsoDeleteData:!0}))},getPeerIsBlacklisted:xa,removePeerFromBlacklist:(e,t)=>Ea("deleteDBPeerFromBlacklist",e,t),getAllExistingRooms:Ra,getRoomStats:e=>Ea("getDBRoomStats",e),sendMessage:(e,t,n,r=.9,a=3,o=T,i=1,s=Gl())=>{if(!/^[0-9a-f]{64}$/.test(s))throw new Error("Invalid transfer ID");const c=Yl(n,s),l=xu(hu.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:()=>kh(n,t,void 0,void 0,s)}},readMessage:vh,getSendChunksCount:e=>Ea("getDBAllNewChunksCount",e),cancelMessage:kh,createTransferId:Gl,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*m)throw new Error("Invalid Merkle root length");if(t&&"string"!=typeof t&&t.length!==m)throw new Error("Invalid Merkle root length");if(n&&"string"==typeof n&&n.length!==2*m)throw new Error("Invalid hash length");if(n&&"string"!=typeof n&&n.length!==m)throw new Error("Invalid hash length");const r=t&&"string"==typeof t?t:t&&"string"!=typeof t?Lr(t):"",a=n&&"string"==typeof n?n:n&&"string"!=typeof n?Lr(n):"";Zl(e,{merkleRootHex:r||void 0,hashHex:a||void 0});const{rooms:o}=Pu.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*m){const t=await Va(o[i].messages[s].channelLabel,o[i].messages[s].merkleRootHex);await Pu.dispatch(hu.endpoints.disconnectFromChannelLabel.initiate({roomId:o[i].id,label:t,alsoDeleteData:!0})),Pu.dispatch(He({roomId:e,merkleRootHex:o[i].messages[s].merkleRootHex}))}},purgeIdentity:async()=>{td(),cd(),xu(h()),await za(),await Ha();const{rooms:e}=Pu.getState(),t=e.length;for(let n=0;n<t;n++)await xu(hu.endpoints.disconnectFromRoom.initiate({roomId:e[n].id}));await xu(Su.endpoints.disconnectWebSocket.initiate(void 0))},purgeRoom:async e=>{e=dh(e),sd(e);const{rooms:t}=Pu.getState(),n=t.findIndex(t=>t.url===e);n>-1&&(ed(t[n].id),t[n].id&&await pd(t[n].id),xu(Ve(t[n].id))),await xu(Su.endpoints.disconnectWebSocket.initiate(void 0))},purge:async()=>{td(),cd(),xu(h()),await za(),await Ha(),await xu(Su.endpoints.disconnectWebSocket.initiate(void 0));const e=await Ra(),t=e.length;for(let n=0;n<t;n++)xu(Ve(e[n].roomId))},generateRandomRoomUrl:async()=>sh(ih()),generateRoomInvite:()=>uh(ih()),generateRoomCapability:ih,encodeRoomCapabilityBase64Url:sh,decodeRoomCapabilityBase64Url:ch,decodeRoomCapability:lh,normalizeRoomCapability:dh,encodeRoomInviteFragment:uh,decodeRoomInviteFragment:hh,encodeRoomCapabilityWords:async e=>{const t=oh(e),n=new Uint8Array(33);n.set(t),n[32]=await fh(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=>Xu[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=ah.get(e);if(void 0===t)throw new Error(`Unknown room invite word: ${e}`);return t})),a=r.slice(0,Yu),o=await fh(a);if(r[32]!==o)throw new Error("Room invite checksum is invalid");return a},ROOM_INVITE_WORDLIST_ID:"p2party-invite-en-v1",sign:pa,verify:ma,createSession:Qu,restoreSession:Wu,generateSessionIdentity:Lu,setWasmSourceUrl:da,DEFAULT_ROOM_POLICY_V1:Ae,encodeRoomPolicyV1:be,decodeRoomPolicyV1:ve,hashRoomPolicyV1:Se,roomPoliciesEqualV1:Ie,generateKeyPair:fa,newKeyPair:fa,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 Xu[t]}).join(" ")},keyPairFromMnemonic:async(e,t)=>{if(!await Ju(e))throw new Error("Invalid mnemonic.");const n=new Uint8Array(A),r=new TextEncoder;r.encodeInto("password12345678",n);const a=new Uint8Array(A);if(t){const e=r.encode(t),n=await window.crypto.subtle.digest("SHA-512",e);a.set(new Uint8Array(n).slice(m-A,m))}else a.set(n);const o=await(async(e,t,n)=>{const r=Gu(e),a=(new TextEncoder).encode(r).buffer,o=new Int8Array(a),i=o.length;t=t??window.crypto.getRandomValues(new Uint8Array(A));const s=n?.wasmMemory??Jr(i),c=(n=n??await ua(s))._malloc(w),l=new Uint8Array(s.buffer,c,w),d=n._malloc(i*Uint8Array.BYTES_PER_ELEMENT),u=new Int8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT),h=n._malloc(A),f=new Uint8Array(s.buffer,h,A);try{if(oa(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{ha(n,l),ha(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=Vr(),n=await ua(t),r=n._malloc(b),a=new Uint8Array(t.buffer,r,b),o=n._malloc(v),i=new Uint8Array(t.buffer,o,v),s=n._malloc(w),c=new Uint8Array(t.buffer,s,w);c.set(e);const l=n._keypair_from_seed(a.byteOffset,i.byteOffset,c.byteOffset);if(ha(n,c),0===l){const e={publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(i)};return n._free(r),ha(n,i),e}throw n._free(r),ha(n,i),new Error("An unexpected error occured.")})(o)},MIN_CHUNKS:1,MIN_CHUNK_SIZE:O+1,MAX_CHUNK_SIZE:T,WIRE_CHUNK_FRAME_LEN:j,MIN_COVER_CADENCE_MS:ne,MAX_COVER_CADENCE_MS:re,MAX_COVER_LANES:16,MAX_COVER_FRAMES_PER_CELL:ae,MIN_COVER_SLOT_MS:25,validateRoomPolicyV1:we,MessageDeliveryError:tu,joinRoom:gh,waitForRoom:yh,waitForPeers:wh,onMessage:bh,setDebugLogging:et,MIN_PERCENTAGE_FILLED_CHUNK:.1,MAX_PERCENTAGE_FILLED_CHUNK:.99,ROOM_URL_LENGTH:64,MessageType:oo,MessageCategory:io,VERSION:n};"undefined"!=typeof window&&(window.p2party=Ih),exports.DEFAULT_ROOM_POLICY_V1=Ae,exports.MAX_COVER_CADENCE_MS=re,exports.MAX_COVER_FRAMES_PER_CELL=ae,exports.MAX_COVER_LANES=16,exports.MIN_COVER_CADENCE_MS=ne,exports.MIN_COVER_SLOT_MS=25,exports.MessageDeliveryError=tu,exports.WIRE_CHUNK_FRAME_LEN=j,exports.canonicalizeRoomPolicyV1=ke,exports.createSession=Qu,exports.decodeRoomPolicyV1=ve,exports.default=Ih,exports.encodeRoomPolicyV1=be,exports.generateSessionIdentity=Lu,exports.hashRoomPolicyV1=Se,exports.joinRoom=gh,exports.onMessage=bh,exports.p2party=Ih,exports.restoreSession=Wu,exports.roomPoliciesEqualV1=Ie,exports.setDebugLogging=et,exports.setWasmSourceUrl=da,exports.validateRoomPolicyV1=we,exports.waitForPeers=wh,exports.waitForRoom=yh;
|
|
1
|
+
"use strict";var e=require("class-validator"),t=require("@reduxjs/toolkit");var n="0.14.3";const r=t.createSlice({name:"commonState",initialState:{currentRoomUrl:""},reducers:{setCurrentRoomUrl:(e,t)=>{e.currentRoomUrl=t.payload}}}),{setCurrentRoomUrl:a}=r.actions;var o=r.reducer;const i={peerId:localStorage.getItem("peerId")??"",challengeId:localStorage.getItem("challengeId")??"",publicKey:localStorage.getItem("publicKey")??"",secretKey:"",challenge:localStorage.getItem("challenge")??"",signature:localStorage.getItem("signature")??""},s=t.createSlice({name:"keyPair",initialState:i,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:(t,n)=>{const{peerId:r,challenge:a,signature:o,challengeId:i}=n.payload;e.isUUID(r,4)&&e.isUUID(i)&&e.isHexadecimal(a)&&e.isHexadecimal(o)&&64===a.length&&128===o.length&&(t.peerId=r,t.challenge=a,t.signature=o,t.challengeId=i)},setPeerData:(t,n)=>{const{peerId:r,challenge:a,signature:o}=n.payload;e.isUUID(r,4)&&e.isHexadecimal(a)&&e.isHexadecimal(o)&&64===a.length&&128===o.length&&(t.peerId=r,t.challenge=a,t.signature=o)},setChallengeId:(t,n)=>{const{challengeId:r}=n.payload;e.isUUID(r)&&(t.challengeId=r)},resetIdentity:()=>({peerId:"",challengeId:"",publicKey:"",secretKey:"",challenge:"",signature:""})}}),{setKeyPair:c,setReconnectData:l,setPeerData:d,setChallengeId:u,resetIdentity:h}=s.actions;var f=s.reducer;const p=64*Uint8Array.BYTES_PER_ELEMENT,m=64*Uint8Array.BYTES_PER_ELEMENT,y=208,g=64*Uint8Array.BYTES_PER_ELEMENT,w=32*Uint8Array.BYTES_PER_ELEMENT,b=32*Uint8Array.BYTES_PER_ELEMENT,v=64*Uint8Array.BYTES_PER_ELEMENT,k=32*Uint8Array.BYTES_PER_ELEMENT,I=12*Uint8Array.BYTES_PER_ELEMENT,S=16*Uint8Array.BYTES_PER_ELEMENT,A=16*Uint8Array.BYTES_PER_ELEMENT,C=32*Uint8Array.BYTES_PER_ELEMENT,E=64*Uint8Array.BYTES_PER_ELEMENT,P=32*Uint8Array.BYTES_PER_ELEMENT,x=32*Uint8Array.BYTES_PER_ELEMENT,R=32*Uint8Array.BYTES_PER_ELEMENT,M=65536,K=10737418240,U=1048576,_=9+m+8+8+256+8+8+8,D=4+48*(m+1),T=65405-(_+D),O=M-T,N=65405,B=m,q=1+B,L=new Uint8Array([1]),F=32,z=12,j=65474+S,H=(new TextEncoder).encode("p2party-x25519-idsig-v1"),V="hybrid-3dh-mlkem512-cpace21-v4",$="hybrid-3dh-mlkem768-cpace21-v4",Q="hybrid-3dh-mlkem1024-cpace21-v4",W=[V,$,Q],X=$,G=2e3,J=1048576,Y=65536,Z=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")},ee=e=>{if("hybrid-mlkem512"===e)return V;if("hybrid-mlkem768"===e)return $;if("hybrid-mlkem1024"===e)return Q;throw new Error("roomPolicy: unsupported PQ mode")},te=e=>{if(e===V)return"hybrid-mlkem512";if(e===$)return"hybrid-mlkem768";if(e===Q)return"hybrid-mlkem1024";throw new Error("roomPolicy: unsupported ratchet root suite")},ne=1e3,re=36e5,ae=1024,oe=new Uint8Array([80,50,82,80]),ie=(new TextEncoder).encode("p2party/room-policy/v1\0"),se=new Set(["version","revision","wireVersion","authMode","pqMode","rendezvousMode","coverMode","coverCadenceMs","coverLanes","coverFramesPerCell","coverDurationEpochs"]),ce={nopin:0,pin:1},le={"hybrid-mlkem768":1,"hybrid-mlkem512":2,"hybrid-mlkem1024":3},de={"legacy-signaling":0,"opaque-token":1,"blind-meeting-point":2},ue={immediate:0,scheduled:1},he=e=>{if(0===e)return"nopin";if(1===e)return"pin";throw new Error("roomPolicy: unsupported auth mode")},fe=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")},pe=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")},me=e=>{if(0===e)return"immediate";if(1===e)return"scheduled";throw new Error("roomPolicy: unsupported cover mode")},ye=(e,t,n)=>{if(!Number.isSafeInteger(t)||t<0||t>n)throw new Error(`roomPolicy: ${e} is out of range`)};function ge(e,t,n){if("string"!=typeof t||!Object.hasOwn(n,t))throw new Error(`roomPolicy: unsupported ${e}`)}const we=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!==se.size||n.some(e=>"string"!=typeof e||!se.has(e)))throw new Error("roomPolicy: policy has missing or unexpected fields (PIN bytes are never policy fields)");for(const t of se){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(ye("revision",e.revision,4294967295),ge("auth mode",e.authMode,ce),ge("PQ mode",e.pqMode,le),ge("rendezvous mode",e.rendezvousMode,de),ge("cover mode",e.coverMode,ue),ye("cover cadence",e.coverCadenceMs,4294967295),ye("cover lanes",e.coverLanes,65535),ye("cover frames per cell",e.coverFramesPerCell,65535),ye("cover duration epochs",e.coverDurationEpochs,65535),"immediate"!==e.coverMode){if(e.coverCadenceMs<ne||e.coverCadenceMs>re)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>ae)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")},be=e=>{we(e);const t=new Uint8Array(32);t.set(oe,0),t[4]=1,t[5]=e.wireVersion,t[6]=ce[e.authMode],t[7]=le[e.pqMode],t[8]=de[e.rendezvousMode],t[9]=ue[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},ve=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<oe.length;t++)if(e[t]!==oe[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:he(e[6]),pqMode:fe(e[7]),rendezvousMode:pe(e[8]),coverMode:me(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 we(n),n},ke=e=>ve(be(e)),Ie=(e,t)=>{const n=be(e),r=be(t);let a=0;for(let e=0;e<n.length;e++)a|=n[e]^r[e];return 0===a},Se=async e=>{const t=be(e),n=new Uint8Array(ie.length+t.length);n.set(ie,0),n.set(t,ie.length);const r=await globalThis.crypto.subtle.digest("SHA-256",n);return new Uint8Array(r)},Ae=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}),Ce={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},Ee=(e,t)=>{const n=ke(t);if(!Ie(e,n))throw new Error("roomSlice: room policy is immutable after creation")},Pe=t.createSlice({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.isUUID(a)){const e=t.findIndex(e=>e.url===r||e.id===a);e>-1?(c&&Ee(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??Ce,policy:ke(c??Ae),peers:[],channels:[],messages:[]})}else if(64===r.length){const e=t.findIndex(e=>e.url===r);e>-1?(c&&Ee(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??Ce,policy:ke(c??Ae),peers:[],channels:[],messages:[]})}},setRoomPolicy:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload.roomContext||e.id===t.payload.roomContext);n>-1&&Ee(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:y}=n.payload,g=t.findIndex(e=>e.id===r);if(g>-1){const n=t[g].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.isUUID(l)&&d&&h&&t[g].messages.push({transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:c,filename:s.length>0?s:"txt",messageType:d,fromPeerId:l,timestamp:y??Date.now(),savedSize:u>0?u:0,totalSize:h,chunksCreated:f??0,totalChunks:p??0}):t[g].messages[n].timestamp!==y&&t[g].messages[n].sha512Hex===i&&t[g].messages[n].savedSize===t[g].messages[n].totalSize?t[g].messages.push({transferId:a,merkleRootHex:o,sha512Hex:i,channelLabel:c,filename:s.length>0?s:"txt",messageType:d,fromPeerId:l,timestamp:y??Date.now(),savedSize:u,totalSize:h,chunksCreated:f??0,totalChunks:p??0}):(o.length===2*m&&""===t[g].messages[n].merkleRootHex&&(t[g].messages[n].merkleRootHex=o),h>0&&t[g].messages[n].totalSize!==h&&(t[g].messages[n].totalSize=h),u>0&&t[g].messages[n].totalSize>=t[g].messages[n].savedSize+u&&(t[g].messages[n].savedSize+=u),f&&f<=t[g].messages[n].totalChunks&&(t[g].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.isUUID(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*m)return;if(o&&o.length!==2*m)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:Ce,policy:ke(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:xe,setRoomPolicy:Re,setConnectingToPeers:Me,setConnectedToPeers:Ke,setConnectionRelay:Ue,setOnlyConnectWithKnownPeers:_e,setPeer:De,setPeerCoverStatus:Te,setPeerHandshakeStatus:Oe,setChannel:Ne,setIceServers:Be,setMessage:qe,setMessageAllChunks:Le,incrementMessageStats:Fe,deletePeer:ze,deleteChannel:je,deleteMessage:He,deleteRoom:Ve}=Pe.actions,$e=e=>e.rooms;var Qe=Pe.reducer;const We="wss://signaling.p2party.com/ws",Xe={isEstablishingConnection:!1,isConnected:!1,isVerified:!1,serverUrl:We},Ge=t.createSlice({name:"signalingServer",initialState:Xe,reducers:{startConnecting:(e,t)=>{e.isEstablishingConnection=!0,e.serverUrl=t.payload??We},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}}}),Je=Ge.actions;var Ye=Ge.reducer;let Ze=!1;Ze=(()=>{try{return"1"===globalThis.localStorage?.getItem("p2party:debug")}catch{return!1}})();const et=e=>{Ze=e},tt=(...e)=>{Ze&&console.log(...e)};var nt=Symbol.for("immer-nothing"),rt=Symbol.for("immer-draftable"),at=Symbol.for("immer-state");function ot(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var it=Object,st=it.getPrototypeOf,ct="constructor",lt="prototype",dt="configurable",ut="enumerable",ht="writable",ft="value",pt=e=>!!e&&!!e[at];function mt(e){return!!e&&(wt(e)||At(e)||!!e[rt]||!!e[ct]?.[rt]||Ct(e)||Et(e))}var yt=it[lt][ct].toString(),gt=new WeakMap;function wt(e){if(!e||!Pt(e))return!1;const t=st(e);if(null===t||t===it[lt])return!0;const n=it.hasOwnProperty.call(t,ct)&&t[ct];if(n===Object)return!0;if(!xt(n))return!1;let r=gt.get(n);return void 0===r&&(r=Function.toString.call(n),gt.set(n,r)),r===yt}function bt(e,t,n=!0){if(0===vt(e)){(n?Reflect.ownKeys(e):it.keys(e)).forEach(n=>{t(n,e[n],e)})}else e.forEach((n,r)=>t(r,n,e))}function vt(e){const t=e[at];return t?t.type_:At(e)?1:Ct(e)?2:Et(e)?3:0}var kt=(e,t,n=vt(e))=>2===n?e.has(t):it[lt].hasOwnProperty.call(e,t),It=(e,t,n=vt(e))=>2===n?e.get(t):e[t],St=(e,t,n,r=vt(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n};var At=Array.isArray,Ct=e=>e instanceof Map,Et=e=>e instanceof Set,Pt=e=>"object"==typeof e,xt=e=>"function"==typeof e,Rt=e=>"boolean"==typeof e;var Mt=e=>e.copy_||e.base_,Kt=e=>e.modified_?e.copy_:e.base_;function Ut(e,t){if(Ct(e))return new Map(e);if(Et(e))return new Set(e);if(At(e))return Array[lt].slice.call(e);const n=wt(e);if(!0===t||"class_only"===t&&!n){const t=it.getOwnPropertyDescriptors(e);delete t[at];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const a=n[r],o=t[a];!1===o[ht]&&(o[ht]=!0,o[dt]=!0),(o.get||o.set)&&(t[a]={[dt]:!0,[ht]:!0,[ut]:o[ut],[ft]:e[a]})}return it.create(st(e),t)}{const t=st(e);if(null!==t&&n)return{...e};const r=it.create(t);return it.assign(r,e)}}function _t(e,t=!1){return Tt(e)||pt(e)||!mt(e)||(vt(e)>1&&it.defineProperties(e,{set:Dt,add:Dt,clear:Dt,delete:Dt}),it.freeze(e),t&&bt(e,(e,t)=>{_t(t,!0)},!1)),e}var Dt={[ft]:function(){ot(2)}};function Tt(e){return null===e||!Pt(e)||it.isFrozen(e)}var Ot="MapSet",Nt="Patches",Bt="ArrayMethods",qt={};function Lt(e){const t=qt[e];return t||ot(0),t}var Ft,zt=e=>!!qt[e];var jt=()=>Ft;function Ht(e,t){t&&(e.patchPlugin_=Lt(Nt),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Vt(e){$t(e),e.drafts_.forEach(Wt),e.drafts_=null}function $t(e){e===Ft&&(Ft=e.parent_)}var Qt=e=>Ft={drafts_:[],parent_:Ft,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:zt(Ot)?Lt(Ot):void 0,arrayMethodsPlugin_:zt(Bt)?Lt(Bt):void 0};function Wt(e){const t=e[at];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function Xt(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[at].modified_&&(Vt(t),ot(4)),mt(e)&&(e=Gt(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[at].base_,e,t)}else e=Gt(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&_t(t,n)}(t,e,!0),Vt(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==nt?e:void 0}function Gt(e,t){if(Tt(t))return t;const n=t[at];if(!n){return nn(t,e.handledSet_,e)}if(!Yt(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)}tn(n,e)}return n.copy_}function Jt(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var Yt=(e,t)=>e.scope_===t,Zt=[];function en(e,t,n,r){const a=Mt(e),o=e.type_;if(void 0!==r){if(It(a,r,o)===t)return void St(a,r,n,o)}if(!e.draftLocations_){const t=e.draftLocations_=new Map;bt(a,(e,n)=>{if(pt(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const i=e.draftLocations_.get(t)??Zt;for(const e of i)St(a,e,n,o)}function tn(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)}Jt(e)}}function nn(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||pt(e)||t.has(e)||!mt(e)||Tt(e)||(t.add(e),bt(e,(r,a)=>{if(pt(a)){const t=a[at];if(Yt(t,n)){const n=Kt(t);St(e,r,n,e.type_),Jt(t)}}else mt(a)&&nn(a,t,n)})),e}var rn={get(e,t){if(t===at)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=Mt(e);if(!kt(a,t,e.type_))return function(e,t,n){const r=sn(t,n);return r?ft in r?r[ft]:r.get?.call(e.draft_):void 0}(e,a,t);const o=a[t];if(e.finalized_||!mt(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===on(e.base_,t)||function(e,t,n){if(1!==e.type_||!e.allIndicesReassigned_||e.assigned_?.get(t)||!mt(n)||n[at])return!1;return e.baseRefs_.has(n)}(e,t,o)){ln(e);const n=1===e.type_?+t:t,r=dn(e.scope_,o,e,n);return e.copy_[n]=r}return o},has:(e,t)=>t in Mt(e),ownKeys:e=>Reflect.ownKeys(Mt(e)),set(e,t,n){const r=sn(Mt(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=on(Mt(e),t),i=r?.[at];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||kt(e.base_,t,e.type_)))return!0;ln(e),cn(e)}var a,o;return e.copy_[t]===n&&(void 0!==n||kt(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(pt(n)){const a=n[at];Yt(a,r)&&a.callbacks_.push(function(){ln(e);const r=Kt(a);en(e,n,r,t)})}else mt(n)&&e.callbacks_.push(function(){const a=Mt(e);3===e.type_?a.has(n)&&nn(n,r.handledSet_,r):It(a,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&nn(It(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(ln(e),void 0!==on(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),cn(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Mt(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[ht]:!0,[dt]:1!==e.type_||"length"!==t,[ut]:r[ut],[ft]:n[t]}:r},defineProperty(){ot(11)},getPrototypeOf:e=>st(e.base_),setPrototypeOf(){ot(12)}},an={};for(let e in rn){let t=rn[e];an[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function on(e,t){const n=e[at];return(n?Mt(n):e)[t]}function sn(e,t){if(!(t in e))return;let n=st(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=st(n)}}function cn(e){e.modified_||(e.modified_=!0,e.parent_&&cn(e.parent_))}function ln(e){e.copy_||(e.assigned_=new Map,e.copy_=Ut(e.base_,e.scope_.immer_.useStrictShallowCopy_))}an.deleteProperty=function(e,t){return an.set.call(this,e,t,void 0)},an.set=function(e,t,n){return rn.set.call(this,e[0],t,n,e[0])};function dn(e,t,n,r){const[a,o]=Ct(t)?Lt(Ot).proxyMap_(t,n):Et(t)?Lt(Ot).proxySet_(t,n):function(e,t){const n=At(e),r={type_:n?1:0,scope_:t?t.scope_:jt(),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=rn;n&&(a=[r],o=an);const{revoke:i,proxy:s}=Proxy.revocable(a,o);return r.draft_=s,r.revoke_=i,[s,r]}(t,n);return(n?.scope_??jt()).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||!Yt(a,r))return;r.mapSetPlugin_?.fixSetContents(a);const o=Kt(a);en(e,a.draft_??a,o,n),tn(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 pt(e)||ot(10),hn(e)}function hn(e){if(!mt(e)||Tt(e))return e;const t=e[at];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Ut(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=Ut(e,!0);return bt(n,(e,t)=>{St(n,e,hn(t))},r),t&&(t.finalized_=!1),n}function fn(){const e="replace",t="add",n="remove";function r(e){if(!mt(e))return e;if(At(e))return e.map(r);if(Ct(e))return new Map(Array.from(e.entries()).map(([e,t])=>[e,r(t)]));if(Et(e))return new Set(Array.from(e).map(r));const t=Object.create(st(e));for(const n in e)t[n]=r(e[n]);return kt(e,rt)&&(t[rt]=e[rt]),t}function a(e){return pt(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=vt(c);let n=i[e];"string"!=typeof n&&"number"!=typeof n&&(n=""+n),0!==t&&1!==t||"__proto__"!==n&&n!==ct||ot(19),xt(c)&&n===lt&&ot(19),c=It(c,n),null!==c&&Pt(c)||ot(18,i.join("/"))}const l=vt(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:ot(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:ot(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;bt(r.assigned_,(r,u)=>{const h=It(c,r,d),f=It(l,r,d),p=u?kt(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?.[at];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===nt?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=It(e,t.key_),Pt(r)?r?.[at]:null),o=It(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||kt(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=It(n,r),!Pt(n)||null===n)throw new Error(`Cannot resolve path at '${t.join("/")}'`)}}(t.copy_,n)}catch(e){return null}return n}},qt[o=Nt]||(qt[o]=i)}var pn=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(xt(e)&&!xt(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(xt(t)||ot(6),void 0===n||xt(n)||ot(7),mt(e)){const a=Qt(this),o=dn(a,e,void 0);let i=!0;try{r=t(o),i=!1}finally{i?Vt(a):$t(a)}return Ht(a,n),Xt(r,a)}if(!e||!Pt(e)){if(r=t(e),void 0===r&&(r=e),r===nt&&(r=void 0),this.autoFreeze_&&_t(r,!0),n){const t=[],a=[];Lt(Nt).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:a}),n(t,a)}return r}ot(1)},this.produceWithPatches=(e,t)=>{if(xt(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]},Rt(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),Rt(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),Rt(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){mt(e)||ot(8),pt(e)&&(e=un(e));const t=Qt(this),n=dn(t,e,void 0);return n[at].isManual_=!0,$t(t),n}finishDraft(e,t){const n=e&&e[at];n&&n.isManual_||ot(9);const{scope_:r}=n;return Ht(r,t),Xt(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=Lt(Nt).applyPatches_;return pt(e)?r(e,t):this.produce(e,e=>r(e,t))}};pn.produce;var mn=pn.produceWithPatches.bind(pn),yn=pn.applyPatches.bind(pn),gn=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}};var wn=e=>Array.isArray(e)?e:[e];function bn(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 vn="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function kn(){return{s:0,v:void 0,o:null,p:null}}function In(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=kn(),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=kn(),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 vn(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 Sn(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=In,argsMemoizeOptions:u=[]}=s,h=wn(l),f=wn(u),p=bn(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 An=Sn(In),Cn=Object.assign((e,t=An)=>{!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:()=>Cn}),En="uninitialized",Pn="pending",xn="fulfilled",Rn="rejected";function Mn(e){return{status:e,isUninitialized:e===En,isLoading:e===Pn,isSuccess:e===xn,isError:e===Rn}}var Kn=t.isPlainObject;function Un(e,t){if(e===t||!(Kn(e)&&Kn(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]=Un(e[r],t[r]),a&&(a=e[r]===o[r]);return a?e:o}function _n(e,t,n){return e.reduce((e,r,a)=>(t(r,a)&&e.push(n(r,a)),e),[]).flat()}function Dn(e){return null!=e}function Tn(e){return[...e?.values()??[]].filter(Dn)}function On(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var Nn=()=>new Map,Bn=class{constructor(e,t=void 0){this.value=e,this.meta=t}value;meta},qn="__rtkq/",Ln="focused",Fn=t.createAction(`${qn}${Ln}`),zn=t.createAction(`${qn}un${Ln}`),jn=t.createAction(`${qn}online`),Hn=t.createAction(`${qn}offline`),Vn="query",$n="mutation",Qn="infinitequery";function Wn(e){return e.type===Vn}function Xn(e){return e.type===Qn}function Gn(e){return Wn(e)||Xn(e)}function Jn(e,t,n,r,a,o){const i="function"==typeof e?e(t,n,r,a):e;return i?_n(i,Dn,e=>o(Yn(e))):[]}function Yn(e){return"string"==typeof e?{type:e}:e}var Zn=(e,t)=>e.endpointDefinitions[t],er=Symbol("forceQueryFn"),tr=e=>"function"==typeof e[er];var nr=class extends gn{constructor(e,t,n,r){super(e),this.value=t,this.schemaName=n,this._bqMeta=r}value;schemaName;_bqMeta},rr=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function ar(e,t,n,r){const a=await e["~standard"].validate(t);if(a.issues)throw new nr(a.issues,t,n,r);return a.value}function or(e){return e}var ir=(e={})=>({...e,[t.SHOULD_AUTOBATCH]:!0});function sr(e,{pages:t,pageParams:n},r){const a=t.length-1;return e.getNextPageParam(t[a],t,n[a],n,r)}function cr(e,{pages:t,pageParams:n},r){return e.getPreviousPageParam?.(t[0],t,n[0],n,r)}function lr(e,n,r,a){return Jn(r[e.meta.arg.endpointName][n],t.isFulfilled(e)?e.payload:void 0,t.isRejectedWithValue(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,a)}function dr(e){return pt(e)?un(e):e}function ur(e,t,n){const r=e[t];r&&n(r)}function hr(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function fr(e,t,n){const r=e[hr(t)];r&&n(r)}var pr={};function mr({reducerPath:e,queryThunk:n,mutationThunk:r,serializeQueryArgs:a,context:{endpointDefinitions:o,apiUid:i,extractRehydrationInfo:s,hasRehydrationInfo:c},assertTagType:l,config:d}){const u=t.createAction(`${e}/resetApiState`);function h(e,t,n,r){e[t.queryCacheKey]??={status:En,endpointName:t.endpointName},ur(e,t.queryCacheKey,e=>{e.status=Pn,e.requestId=n&&e.requestId?e.requestId:r.requestId,void 0!==t.originalArgs&&(e.originalArgs=t.originalArgs),e.startedTimeStamp=r.startedTimeStamp;Xn(o[r.arg.endpointName])&&"direction"in t&&(e.direction=t.direction)})}function f(e,n,r,a){ur(e,n.arg.queryCacheKey,e=>{if(e.requestId!==n.requestId&&!a)return;const{merge:i}=o[n.arg.endpointName];if(e.status=xn,i)if(void 0!==e.data){const{fulfilledTimeStamp:a,arg:o,baseQueryMeta:s,requestId:c}=n;let l=t.createNextState(e.data,e=>i(e,r,{arg:o.originalArgs,baseQueryMeta:s,fulfilledTimeStamp:a,requestId:c}));e.data=l}else e.data=r;else e.data=o[n.arg.endpointName].structuralSharing??1?Un(pt(e.data)?(s=e.data,pt(s)||ot(15),s[at].base_):e.data,r):r;var s;delete e.error,e.fulfilledTimeStamp=n.fulfilledTimeStamp})}const p=t.createSlice({name:`${e}/queries`,initialState:pr,reducers:{removeQueryResult:{reducer(e,{payload:{queryCacheKey:t}}){delete e[t]},prepare:t.prepareAutoBatched()},cacheEntriesUpserted:{reducer(e,t){for(const n of t.payload){const{queryDescription:r,value:a}=n;h(e,r,!0,{arg:r,requestId:t.meta.requestId,startedTimeStamp:t.meta.timestamp}),f(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,i=o[t];return{queryDescription:{type:Vn,endpointName:t,originalArgs:e.arg,queryCacheKey:a({queryArgs:n,endpointDefinition:i,endpointName:t})},value:r}}),meta:{[t.SHOULD_AUTOBATCH]:!0,requestId:t.nanoid(),timestamp:Date.now()}})},queryResultPatched:{reducer(e,{payload:{queryCacheKey:t,patches:n}}){ur(e,t,e=>{e.data=yn(e.data,n.concat())})},prepare:t.prepareAutoBatched()}},extraReducers(e){e.addCase(n.pending,(e,{meta:t,meta:{arg:n}})=>{h(e,n,tr(n),t)}).addCase(n.fulfilled,(e,{meta:t,payload:n})=>{f(e,t,n,tr(t.arg))}).addCase(n.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=Rn,e.error=o??a}})}).addMatcher(c,(e,t)=>{const{queries:n}=s(t);for(const[t,r]of Object.entries(n))r?.status!==xn&&r?.status!==Rn||(e[t]=r)})}}),m=t.createSlice({name:`${e}/mutations`,initialState:pr,reducers:{removeMutationResult:{reducer(e,{payload:t}){const n=hr(t);n in e&&delete e[n]},prepare:t.prepareAutoBatched()}},extraReducers(e){e.addCase(r.pending,(e,{meta:t,meta:{requestId:n,arg:r,startedTimeStamp:a}})=>{r.track&&(e[hr(t)]={requestId:n,status:Pn,endpointName:r.endpointName,startedTimeStamp:a})}).addCase(r.fulfilled,(e,{payload:t,meta:n})=>{n.arg.track&&fr(e,n,e=>{e.requestId===n.requestId&&(e.status=xn,e.data=t,e.fulfilledTimeStamp=n.fulfilledTimeStamp)})}).addCase(r.rejected,(e,{payload:t,error:n,meta:r})=>{r.arg.track&&fr(e,r,e=>{e.requestId===r.requestId&&(e.status=Rn,e.error=t??n)})}).addMatcher(c,(e,t)=>{const{mutations:n}=s(t);for(const[t,r]of Object.entries(n))r?.status!==xn&&r?.status!==Rn||t===r?.requestId||(e[t]=r)})}}),y=t.createSlice({name:`${e}/invalidation`,initialState:{tags:{},keys:{}},reducers:{updateProvidedBy:{reducer(e,t){for(const{queryCacheKey:n,providedTags:r}of t.payload){g(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:t.prepareAutoBatched()}},extraReducers(e){e.addCase(p.actions.removeQueryResult,(e,{payload:{queryCacheKey:t}})=>{g(e,t)}).addMatcher(c,(e,t)=>{const{provided:n}=s(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(t.isAnyOf(t.isFulfilled(n),t.isRejectedWithValue(n)),(e,t)=>{w(e,[t])}).addMatcher(p.actions.cacheEntriesUpserted.match,(e,t)=>{w(e,t.payload.map(({queryDescription:e,value:t})=>({type:"UNKNOWN",payload:t,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:e}})))})}});function g(e,t){const n=dr(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]=dr(o).filter(e=>e!==t))}delete e.keys[t]}function w(e,t){const n=t.map(e=>{const t=lr(e,"providesTags",o,l),{queryCacheKey:n}=e.meta.arg;return{queryCacheKey:n,providedTags:t}});y.caseReducers.updateProvidedBy(e,y.actions.updateProvidedBy(n))}const b=t.createSlice({name:`${e}/subscriptions`,initialState:pr,reducers:{updateSubscriptionOptions(e,t){},unsubscribeQueryResult(e,t){},internal_getRTKQSubscriptions(){}}}),v=t.createSlice({name:`${e}/internalSubscriptions`,initialState:pr,reducers:{subscriptionsUpdated:{reducer:(e,t)=>yn(e,t.payload),prepare:t.prepareAutoBatched()}}}),k=t.createSlice({name:`${e}/config`,initialState:{online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine,focused:"undefined"==typeof document||"hidden"!==document.visibilityState,middlewareRegistered:!1,...d},reducers:{middlewareRegistered(e,{payload:t}){e.middlewareRegistered="conflict"!==e.middlewareRegistered&&i===t||"conflict"}},extraReducers:e=>{e.addCase(jn,e=>{e.online=!0}).addCase(Hn,e=>{e.online=!1}).addCase(Fn,e=>{e.focused=!0}).addCase(zn,e=>{e.focused=!1}).addMatcher(c,e=>({...e}))}}),I=t.combineReducers({queries:p.reducer,mutations:m.reducer,provided:y.reducer,subscriptions:v.reducer,config:k.reducer});return{reducer:(e,t)=>I(u.match(t)?void 0:e,t),actions:{...k.actions,...p.actions,...b.actions,...v.actions,...m.actions,...y.actions,resetApiState:u}}}var yr=Symbol.for("RTKQ/skipToken"),gr={status:En},wr=t.createNextState(gr,()=>{}),br=t.createNextState(gr,()=>{});var vr=WeakMap?new WeakMap:void 0,kr=({endpointName:e,queryArgs:n})=>{let r="";const a=vr?.get(n);if("string"==typeof a)r=a;else{const e=JSON.stringify(n,(e,n)=>(n="bigint"==typeof n?{$bigint:n.toString()}:n,n=t.isPlainObject(n)?Object.keys(n).sort().reduce((e,t)=>(e[t]=n[t],e),{}):n));t.isPlainObject(n)&&vr?.set(n,e),r=e}return`${e}(${r})`};function Ir(...e){return function(n){const r=In(e=>n.extractRehydrationInfo?.(e,{reducerPath:n.reducerPath??"api"})),a={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...n,extractRehydrationInfo:r,serializeQueryArgs(e){let t=kr;if("serializeQueryArgs"in e.endpointDefinition){const n=e.endpointDefinition.serializeQueryArgs;t=e=>{const t=n(e);return"string"==typeof t?t:kr({...e,queryArgs:t})}}else n.serializeQueryArgs&&(t=n.serializeQueryArgs);return t(e)},tagTypes:[...n.tagTypes||[]]},o={endpointDefinitions:{},batch(e){e()},apiUid:t.nanoid(),extractRehydrationInfo:r,hasRehydrationInfo:In(e=>null!=r(e))},i={injectEndpoints:function(e){const n=e.endpoints({query:e=>({...e,type:Vn}),mutation:e=>({...e,type:$n}),infiniteQuery:e=>({...e,type:Qn})});for(const[r,a]of Object.entries(n))if(!0!==e.overrideExisting&&r in o.endpointDefinitions){if("throw"===e.overrideExisting)throw new Error(t.formatProdErrorMessage(39))}else{o.endpointDefinitions[r]=a;for(const e of s)e.injectEndpoint(r,a)}return i},enhanceEndpoints({addTagTypes:e,endpoints:t}){if(e)for(const t of e)a.tagTypes.includes(t)||a.tagTypes.push(t);if(t)for(const[e,n]of Object.entries(t))"function"==typeof n?n(Zn(o,e)):Object.assign(Zn(o,e)||{},n);return i}},s=e.map(e=>e.init(i,a,o));return i.injectEndpoints({endpoints:n.endpoints})}}function Sr(e,...t){return Object.assign(e,...t)}var Ar=({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=On(n,e.queryCacheKey,Nn);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=On(n,t.queryCacheKey,Nn);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]=mn(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]}},Cr=({reducerPath:e,api:n,queryThunk:r,context:a,internalState:o,selectors:{selectQueryEntry:i,selectConfig:s},getRunningQueryThunk:c,mwApi:l})=>{const{removeQueryResult:d,unsubscribeQueryResult:u,cacheEntriesUpserted:h}=n.internalActions,f=t.isAnyOf(u.match,r.fulfilled,r.rejected,h.match);function p(e){const t=o.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=i(r,a);e?.endpointName&&w(a,e.endpointName,t,n)}}function w(e,t,n,r){const o=Zn(a,t),s=o?.keepUnusedDataFor??r.keepUnusedDataFor;if(s===1/0)return;const l=Math.max(0,Math.min(s,2147482.647));if(!p(e)){const t=m[e];t&&clearTimeout(t),m[e]=setTimeout(()=>{if(!p(e)){const t=i(n.getState(),e);if(t?.endpointName){const e=n.dispatch(c(t.endpointName,t.originalArgs));e?.abort()}n.dispatch(d({queryCacheKey:e}))}delete m[e]},1e3*l)}}return(e,t)=>{const r=t.getState(),i=s(r);if(f(e)){let n;if(h.match(e))n=e.payload.map(e=>e.queryDescription.queryCacheKey);else{const{queryCacheKey:t}=u.match(e)?e.payload:e.meta.arg;n=[t]}g(n,t,i)}if(n.util.resetApiState.match(e)){for(const[e,t]of Object.entries(m))t&&clearTimeout(t),delete m[e];y(o.runningQueries),y(o.runningMutations)}if(a.hasRehydrationInfo(e)){const{queries:n}=a.extractRehydrationInfo(e);g(Object.keys(n),t,i)}}},Er=new Error("Promise never resolved before cacheEntryRemoved."),Pr=({api:e,reducerPath:n,context:r,queryThunk:a,mutationThunk:o,internalState:i,selectors:{selectQueryEntry:s,selectApiState:c}})=>{const l=t.isAsyncThunkAction(a),d=t.isAsyncThunkAction(o),u=t.isFulfilled(a,o),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,n,a,o,i){const s=Zn(r,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 Er})]);u.catch(()=>{}),h[a]=l;const f=e.endpoints[t].select(Gn(s)?n:a),p=o.dispatch((e,t,n)=>n),m={...o,getCacheEntry:()=>f(o.getState()),requestId:i,extra:p,updateCachedData:Gn(s)?r=>o.dispatch(e.util.updateQueryData(t,n,r)):void 0,cacheDataLoaded:u,cacheEntryRemoved:d},y=c(n,m);Promise.resolve(y).catch(e=>{if(e!==Er)throw e})}return(t,r,i)=>{const c=function(e){if(l(e))return e.meta.arg.queryCacheKey;if(d(e))return e.meta.arg.fixedCacheKey??e.meta.requestId;return f.match(e)?e.payload.queryCacheKey:p.match(e)?hr(e.payload):""}(t);function v(e,t,n,a){const o=s(i,t),c=s(r.getState(),t);!o&&c&&b(e,a,t,r,n)}if(a.pending.match(t)){const[e,n,r]=w(t);v(e,c,r,n)}else if(m.match(t))for(const{queryDescription:e,value:n}of t.payload){const{endpointName:r,originalArgs:a,queryCacheKey:o}=e;v(r,o,t.meta.requestId,a),y(o,n,{})}else if(o.pending.match(t)){if(r.getState()[n].mutations[c]){const[e,n,a]=w(t);b(e,n,c,r,a)}}else if(u(t))y(c,t.payload,t.meta.baseQueryMeta);else if(f.match(t)||p.match(t))g(c);else if(e.util.resetApiState.match(t))for(const e of Object.keys(h))g(e)}},xr=({api:e,context:{apiUid:t},reducerPath:n})=>(n,r)=>{e.util.resetApiState.match(n)&&r.dispatch(e.internalActions.middlewareRegistered(t))},Rr=({reducerPath:e,context:n,context:{endpointDefinitions:r},mutationThunk:a,queryThunk:o,api:i,assertTagType:s,refetchQuery:c,internalState:l})=>{const{removeQueryResult:d}=i.internalActions,u=t.isAnyOf(t.isFulfilled(a),t.isRejectedWithValue(a)),h=t.isAnyOf(t.isFulfilled(o,a),t.isRejected(o,a));let f=[],p=0;function m(t,r){const a=r.getState(),o=a[e];if(f.push(...t),"delayed"===o.config.invalidationBehavior&&p>0)return;const s=f;if(f=[],0===s.length)return;const u=i.util.selectInvalidatedBy(a,s);n.batch(()=>{const e=Array.from(u.values());for(const{queryCacheKey:t}of e){const e=o.queries[t],n=On(l.currentSubscriptions,t,Nn);e&&(0===n.size?r.dispatch(d({queryCacheKey:t})):e.status!==En&&r.dispatch(c(e)))}})}return(e,t)=>{(o.pending.match(e)||a.pending.match(e))&&p++,h(e)&&(p=Math.max(0,p-1)),u(e)?m(lr(e,"invalidatesTags",r,s),t):h(e)?m([],t):i.util.invalidateTags.match(e)&&m(Jn(e.payload,void 0,void 0,void 0,void 0,s),t)}},Mr=({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===En)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===En)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())}},Kr=({api:e,context:n,queryThunk:r,mutationThunk:a})=>{const o=t.isPending(r,a),i=t.isRejected(r,a),s=t.isFulfilled(r,a),c={};return(t,r)=>{if(o(t)){const{requestId:a,arg:{endpointName:o,originalArgs:i}}=t.meta,s=Zn(n,o),l=s?.onQueryStarted;if(l){const t={},n=new Promise((e,n)=>{t.resolve=e,t.reject=n});n.catch(()=>{}),c[a]=t;const d=e.endpoints[o].select(Gn(s)?i:a),u=r.dispatch((e,t,n)=>n),h={...r,getCacheEntry:()=>d(r.getState()),requestId:a,extra:u,updateCachedData:Gn(s)?t=>r.dispatch(e.util.updateQueryData(o,i,t)):void 0,queryFulfilled:n};l(i,h)}}else if(s(t)){const{requestId:e,baseQueryMeta:n}=t.meta;c[e]?.resolve({data:t.payload,meta:n}),delete c[e]}else if(i(t)){const{requestId:e,rejectedWithValue:n,baseQueryMeta:r}=t.meta;c[e]?.reject({error:t.payload??t.error,isUnhandledError:!n,meta:r}),delete c[e]}}};function Ur(e){const{reducerPath:n,queryThunk:r,api:a,context:o,getInternalState:i}=e,{apiUid:s}=o,c={invalidateTags:t.createAction(`${n}/invalidateTags`)},l=e=>e.type.startsWith(`${n}/`),d=[xr,Cr,Rr,Mr,Pr,Kr];return{middleware:r=>{let c=!1;const h=i(r.dispatch),f={...e,internalState:h,refetchQuery:u,isThisApiSliceAction:l,mwApi:r},p=d.map(e=>e(f)),m=Ar(f),y=(({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!==En&&n.dispatch(r(t)))}})}return(e,t)=>{Fn.match(e)&&i(t,"refetchOnFocus"),jn.match(e)&&i(t,"refetchOnReconnect")}})(f);return e=>i=>{if(!t.isAction(i))return e(i);c||(c=!0,r.dispatch(a.internalActions.middlewareRegistered(s)));const d={...r,next:e},u=r.getState(),[h,f]=m(i,d,u);let g;if(g=h?e(i):f,r.getState()[n]&&(y(i,d,u),l(i)||o.hasRehydrationInfo(i)))for(const e of p)e(i,d,u);return g}},actions:c};function u(t){return e.api.endpoints[t.endpointName].initiate(t.originalArgs,{subscribe:!1,forceRefetch:!0})}}var _r=Symbol(),Dr=Ir((({createSelector:e=t.createSelector}={})=>({name:_r,init(n,{baseQuery:r,tagTypes:a,reducerPath:o,serializeQueryArgs:i,keepUnusedDataFor:s,refetchOnMountOrArgChange:c,refetchOnFocus:l,refetchOnReconnect:d,invalidationBehavior:u,onSchemaFailure:h,catchSchemaFailure:f,skipSchemaValidation:p},m){fn();const y=e=>e;Object.assign(n,{reducerPath:o,endpoints:{},internalActions:{onOnline:jn,onOffline:Hn,onFocus:Fn,onFocusLost:zn},util:{}});const g=function({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=e=>wr,a=e=>br;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,...Mn(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?hr(e)??yr:e,n(t===yr?a:e=>i(e)?.mutations?.[t]??br,o)}},selectInvalidatedBy:function(e,n){const r=e[t],a=new Set,o=_n(n,Dn,Yn);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 _n(Object.values(s(e)),e=>e?.endpointName===t&&e.status!==En,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,...Mn(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===yr)return n(r,o);const s=e({queryArgs:i,endpointDefinition:a,endpointName:t});return n(e=>c(e,s)??wr,o)}}function d(e,t,n){return!!t&&null!=sr(e,t,n)}function u(e,t,n){return!(!t||!e.getPreviousPageParam)&&null!=cr(e,t,n)}}({serializeQueryArgs:i,reducerPath:o,createSelector:e}),{selectInvalidatedBy:w,selectCachedArgsForQuery:b,buildQuerySelector:v,buildInfiniteQuerySelector:k,buildMutationSelector:I}=g;Sr(n.util,{selectInvalidatedBy:w,selectCachedArgsForQuery:b});const{queryThunk:S,infiniteQueryThunk:A,mutationThunk:C,patchQueryData:E,updateQueryData:P,upsertQueryData:x,prefetch:R,buildMatchThunkActions:M}=function({reducerPath:e,baseQuery:n,context:{endpointDefinitions:r},serializeQueryArgs:a,api:o,assertTagType:i,selectors:s,onSchemaFailure:c,catchSchemaFailure:l,skipSchemaValidation:d}){function u(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}function h(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}const f=(e,t)=>e.query&&e[t]?e[t]:or,p=async(e,{signal:t,abort:a,rejectWithValue:o,fulfillWithValue:i,dispatch:p,getState:y,extra:g})=>{const w=r[e.endpointName],{metaSchema:b,skipSchemaValidation:v=d}=w,k=e.type===Vn;try{let I=or;const S={signal:t,abort:a,dispatch:p,getState:y,extra:g,endpoint:e.endpointName,type:e.type,forced:k?m(e,y()):void 0,queryCacheKey:k?e.queryCacheKey:void 0},A=k?e[er]:void 0;let C;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?u:h;return{data:{pages:s(t.pages,i.data,r),pageParams:s(t.pageParams,n,r)},meta:i.meta}};async function P(e){let t;const{extraOptions:r,argSchema:a,rawResponseSchema:o,responseSchema:i}=w;if(a&&!rr(v,"arg")&&(e=await ar(a,e,"argSchema",{})),A?t=A():w.query?(I=f(w,"transformResponse"),t=await n(w.query(e),S,r)):t=await w.queryFn(e,S,r,e=>n(e,S,r)),t.error)throw new Bn(t.error,t.meta);let{data:s}=t;o&&!rr(v,"rawResponse")&&(s=await ar(o,t.data,"rawResponseSchema",t.meta));let c=await I(s,t.meta,e);return i&&!rr(v,"response")&&(c=await ar(i,c,"responseSchema",t.meta)),{...t,data:c}}if(k&&"infiniteQueryOptions"in w){const{infiniteQueryOptions:x}=w,{maxPages:R=1/0}=x,M=e.refetchCachedPages??x.refetchCachedPages??!0;let K;const U={pages:[],pageParams:[]},_=s.selectQueryEntry(y(),e.queryCacheKey)?.data,D=m(e,y())&&!e.direction||!_?U:_;if("direction"in e&&e.direction&&D.pages.length){const T="backward"===e.direction,O=(T?cr:sr)(x,D,e.originalArgs);K=await E(D,O,R,T)}else{const{initialPageParam:N=x.initialPageParam}=e,B=_?.pageParams??[],q=B[0]??N,L=B.length;if(K=await E(D,q,R),A&&(K={data:K.data.pages[0]}),M)for(let F=1;F<L;F++){const z=sr(x,K.data,e.originalArgs);K=await E(K.data,z,R)}}C=K}else C=await P(e.originalArgs);return b&&!rr(v,"meta")&&C.meta&&(C.meta=await ar(b,C.meta,"metaSchema",C.meta)),i(C.data,ir({fulfilledTimeStamp:Date.now(),baseQueryMeta:C.meta}))}catch(j){let H=j;if(H instanceof Bn){let V=f(w,"transformErrorResponse");const{rawErrorResponseSchema:$,errorResponseSchema:Q}=w;let{value:W,meta:X}=H;try{$&&!rr(v,"rawErrorResponse")&&(W=await ar($,W,"rawErrorResponseSchema",X)),b&&!rr(v,"meta")&&(X=await ar(b,X,"metaSchema",X));let G=await V(W,X,e.originalArgs);return Q&&!rr(v,"errorResponse")&&(G=await ar(Q,G,"errorResponseSchema",X)),o(G,ir({baseQueryMeta:X}))}catch(J){H=J}}try{if(H instanceof nr){const Y={endpoint:e.endpointName,arg:e.originalArgs,type:e.type,queryCacheKey:k?e.queryCacheKey:void 0};w.onSchemaFailure?.(H,Y),c?.(H,Y);const{catchSchemaFailure:Z=l}=w;if(Z)return o(Z(H,Y),ir({baseQueryMeta:H._bqMeta}))}}catch(ee){H=ee}throw console.error(H),H}};function m(e,t){const n=s.selectQueryEntry(t,e.queryCacheKey),r=s.selectConfig(t).refetchOnMountOrArgChange,a=n?.fulfilledTimeStamp,o=e.forceRefetch??(e.subscribe&&r);return!!o&&(!0===o||(Number(new Date)-Number(a))/1e3>=o)}const y=()=>t.createAsyncThunk(`${e}/executeQuery`,p,{getPendingMeta({arg:e}){const t=r[e.endpointName];return ir({startedTimeStamp:Date.now(),...Xn(t)?{direction:e.direction}:{}})},condition(e,{getState:t}){const n=t(),a=s.selectQueryEntry(n,e.queryCacheKey),o=a?.fulfilledTimeStamp,i=e.originalArgs,c=a?.originalArgs,l=r[e.endpointName],d=e.direction;return!(!tr(e)&&("pending"===a?.status||!m(e,n)&&(!Wn(l)||!l?.forceRefetch?.({currentArg:i,previousArg:c,endpointState:a,state:n}))&&o&&!d))},dispatchConditionRejection:!0}),g=y(),w=y(),b=t.createAsyncThunk(`${e}/executeMutation`,p,{getPendingMeta:()=>ir({startedTimeStamp:Date.now()})});function v(e){return t=>t?.meta?.arg?.endpointName===e}return{queryThunk:g,mutationThunk:b,infiniteQueryThunk:w,prefetch:(e,t,n={})=>(r,a)=>{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 o.endpoints[e].initiate(t,r)},l=o.endpoints[e].select(t)(a());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)=>(a,i)=>{const s=o.endpoints[e].select(t)(i()),c={patches:[],inversePatches:[],undo:()=>a(o.util.patchQueryData(e,t,c.inversePatches,r))};if(s.status===En)return c;let l;if("data"in s)if(mt(s.data)){const[e,t,r]=mn(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||a(o.util.patchQueryData(e,t,c.patches,r)),c},upsertQueryData:(e,t,n)=>r=>r(o.endpoints[e].initiate(t,{subscribe:!1,forceRefetch:!0,[er]:()=>({data:n})})),patchQueryData:(e,t,n,s)=>(c,l)=>{const d=r[e],u=a({queryArgs:t,endpointDefinition:d,endpointName:e});if(c(o.internalActions.queryResultPatched({queryCacheKey:u,patches:n})),!s)return;const h=o.endpoints[e].select(t)(l()),f=Jn(d.providesTags,h.data,void 0,t,{},i);c(o.internalActions.updateProvidedBy([{queryCacheKey:u,providedTags:f}]))},buildMatchThunkActions:function(e,n){return{matchPending:t.isAllOf(t.isPending(e),v(n)),matchFulfilled:t.isAllOf(t.isFulfilled(e),v(n)),matchRejected:t.isAllOf(t.isRejected(e),v(n))}}}}({baseQuery:r,reducerPath:o,context:m,api:n,serializeQueryArgs:i,assertTagType:y,selectors:g,onSchemaFailure:h,catchSchemaFailure:f,skipSchemaValidation:p}),{reducer:K,actions:U}=mr({context:m,queryThunk:S,mutationThunk:C,serializeQueryArgs:i,reducerPath:o,assertTagType:y,config:{refetchOnFocus:l,refetchOnReconnect:d,refetchOnMountOrArgChange:c,keepUnusedDataFor:s,reducerPath:o,invalidationBehavior:u}});Sr(n.util,{patchQueryData:E,updateQueryData:P,upsertQueryData:x,prefetch:R,resetApiState:U.resetApiState,upsertQueryEntries:U.cacheEntriesUpserted}),Sr(n.internalActions,U);const _=new WeakMap,D=e=>On(_,e,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:T,buildInitiateInfiniteQuery:O,buildInitiateMutation:N,getRunningMutationThunk:B,getRunningMutationsThunk:q,getRunningQueriesThunk:L,getRunningQueryThunk:F}=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=Zn(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=>Tn(s(e))},getRunningMutationsThunk:function(){return e=>Tn(c(e))}};function h(r,o){const i=(c,{subscribe:d=!0,forceRefetch:h,subscriptionOptions:f,[er]:p,...m}={})=>(y,g)=>{const w=e({queryArgs:c,endpointDefinition:o,endpointName:r});let b;const v={...m,type:Vn,subscribe:d,forceRefetch:h,subscriptionOptions:f,endpointName:r,originalArgs:c,queryCacheKey:w,[er]:p};if(Wn(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:A,abort:C}=I,E=S.requestId!==A,P=s(y)?.get(w),x=()=>k(g()),R=Object.assign(p?I.then(x):E&&!P?Promise.resolve(S):Promise.all([P,I]).then(x),{arg:c,requestId:A,subscriptionOptions:f,queryCacheKey:w,abort:C,async unwrap(){const e=await R;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:A}))},updateSubscriptionOptions(e){R.subscriptionOptions=e,y(u({endpointName:r,requestId:A,queryCacheKey:w,options:e}))}});if(!P&&!E&&!p){const e=s(y);e.set(w,R),R.then(()=>{e.delete(w)})}return R};return i}}({queryThunk:S,mutationThunk:C,infiniteQueryThunk:A,api:n,serializeQueryArgs:i,context:m,getInternalState:D});Sr(n.util,{getRunningMutationThunk:B,getRunningMutationsThunk:q,getRunningQueryThunk:F,getRunningQueriesThunk:L});const{middleware:z,actions:j}=Ur({reducerPath:o,context:m,queryThunk:S,mutationThunk:C,infiniteQueryThunk:A,api:n,assertTagType:y,selectors:g,getRunningQueryThunk:F,getInternalState:D});return Sr(n.util,j),Sr(n,{reducer:K,middleware:z}),{name:_r,injectEndpoint(e,t){const r=n,a=r.endpoints[e]??={};Wn(t)&&Sr(a,{name:e,select:v(e,t),initiate:T(e,t)},M(S,e)),t.type===$n&&Sr(a,{name:e,select:I(),initiate:N(e)},M(C,e)),Xn(t)&&Sr(a,{name:e,select:k(e,t),initiate:O(e,t)},M(S,e))}}}}))());const Tr="0123456789abcdef",Or=new Array(64),Nr=new Array(128),Br=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)}),qr=(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)}),Lr=e=>{const t=e.length,n=t===m?Nr:32===t?Or:new Array(2*t);let r=0;for(let a=0;a<t;a++){const t=e[a];n[r++]=Tr[t>>4],n[r++]=Tr[15&t]}return n.join("")},Fr=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},zr=(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 jr=()=>{const e=(b+v)*Uint8Array.BYTES_PER_ELEMENT,t=zr(e);return new WebAssembly.Memory({initial:t,maximum:t})},Hr=()=>{const e=(x+R)*Uint8Array.BYTES_PER_ELEMENT,t=zr(e);return new WebAssembly.Memory({initial:t,maximum:t})},Vr=()=>{const e=(b+v+w)*Uint8Array.BYTES_PER_ELEMENT,t=zr(e);return new WebAssembly.Memory({initial:t,maximum:t})},$r=e=>{const t=(e+g+v+m)*Uint8Array.BYTES_PER_ELEMENT,n=zr(t);return new WebAssembly.Memory({initial:n,maximum:n})},Qr=e=>{const t=(e+g+b)*Uint8Array.BYTES_PER_ELEMENT,n=zr(t);return new WebAssembly.Memory({initial:n,maximum:n})},Wr=()=>{const e=zr(0);return new WebAssembly.Memory({initial:e,maximum:e})},Xr=e=>{const t=zr((2*e+3)*m);return new WebAssembly.Memory({initial:t,maximum:t})},Gr=e=>{const t=zr(e*m+e*(m+1)+3*m);return new WebAssembly.Memory({initial:t,maximum:t})},Jr=e=>{const t=(78643200+e+w+A)*Uint8Array.BYTES_PER_ELEMENT,n=zr(t);return new WebAssembly.Memory({initial:n,maximum:n})};function Yr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Zr,ea={exports:{}};var ta=(Zr||(Zr=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=_(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 A(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 C(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 A(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=[],R=(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 O[e](...r)},M=e=>{I("OOM")},K=(e,t)=>Math.ceil(e/t)*t,U=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 _,D,T,O={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"}}}},N={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)=>R(e,t,n),f:e=>{var t=w.length,n=1073741824;(e>>>=0)>n&&M();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,K(Math.max(e,a),65536));if(U(o))return!0}M()},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,_=e.Q,D=e.R,e.__indirect_function_table}(T=e.exports),T}var t={a:N};h??=S();var r=function(t){return e(t.instance)}(await C(c,h,t));return r}(),await async function(){d||(v=!0,T.h())}(),n});e.exports=n,e.exports.default=n}(ea)),ea.exports),na=Yr(ta);const ra=new Uint32Array(1),aa=()=>{const e=globalThis.crypto;if("function"!=typeof e?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");try{return e.getRandomValues(ra),ra[0]>>>0}finally{ra[0]=0}},oa=(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 ia="0.14.3";let sa=new URL(`https://cdn.p2party.com/@${ia}/libcrypto.wasm`),ca=!1;const la={integrity:"sha384-pBMyUqQ3KBztxgeJMgDFZeohfj9QlAFNwt4/gRlqT0vlZ2kbkKxv+q5DwbZOBuUP"},da=e=>{if(ca)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:");sa=t},ua=async e=>{ca=!0;const t=await(async()=>{const e=await fetch(sa,la);if(!e.ok)throw new Error(`Unable to load p2party ${ia} WASM: HTTP ${String(e.status)}`);return await e.arrayBuffer()})();return await na({wasmBinary:t,wasmMemory:e,getRandomValue:aa})},ha=(e,t)=>{t.fill(0),e._free(t.byteOffset)},fa=async e=>{const t=e?.wasmMemory??jr(),n=e??await ua(t),r=n._malloc(b),a=new Uint8Array(t.buffer,r,b),o=n._malloc(v),i=new Uint8Array(t.buffer,o,v),s=n._malloc(w),c=new Uint8Array(t.buffer,s,w);try{oa(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),ha(n,i),ha(n,c)}},pa=async(e,t,n)=>{if(t.length!==v)throw new Error(`Ed25519 secret key must be ${String(v)} bytes`);const r=e.length,a=n?n.wasmMemory:$r(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(g),l=new Uint8Array(a.buffer,c,g),d=o._malloc(v),u=new Uint8Array(a.buffer,d,v);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),ha(o,u)}},ma=async(e,t,n,r)=>{const a=e.length,o=r?r.wasmMemory:Qr(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(g),d=new Uint8Array(o.buffer,l,g);d.set(t);const u=i._malloc(b),h=new Uint8Array(o.buffer,u,b);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},ya=/^[0-9a-f]{64}$/,ga=e=>"string"==typeof e&&ya.test(e),wa=(e,t="Ed25519 identity")=>{if(!ga(e))throw new Error(`${t} must be 32-byte lowercase hexadecimal`)},ba=(e,t)=>{if(wa(e,"Self Ed25519 identity"),wa(t,"Peer Ed25519 identity"),e===t)throw new Error("Cannot assign a protocol role to the same Ed25519 identity");return e<t},va='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',ka=new Blob([va],{type:"application/javascript"}),Ia=new Worker(URL.createObjectURL(ka),{type:"module"});let Sa=0;const Aa=new Map;Ia.onmessage=e=>{const{id:t,result:n,error:r}=e.data,a=Aa.get(t);a&&(Aa.delete(t),r?a.reject(r):a.resolve(n))};const Ca=e=>{const t=[...Aa.values()];Aa.clear();for(const n of t)n.reject(e)};function Ea(e,...t){return new Promise((n,r)=>{const a=++Sa;Aa.set(a,{resolve:n,reject:r}),Ia.postMessage({id:a,method:e,args:t})})}Ia.onerror=e=>{Ca(new Error(`p2party: the database worker failed: ${e.message||"unknown error"}`))},Ia.onmessageerror=()=>{Ca(new Error("p2party: a database worker message could not be deserialized"))};const Pa=(e,t)=>Ea("getDBAddressBookEntry",e,t),xa=async(e,t)=>{try{return await Ea("getDBPeerIsBlacklisted",e,t)}catch(e){return console.error("p2party: blacklist lookup failed; treating this peer as blocked",e),!0}},Ra=()=>Ea("getAllDBUniqueRooms"),Ma=(e,t)=>Ea("getDBMessageData",e,t),Ka=e=>Ea("getDBRoomMessageData",e),Ua=(e,t)=>Ea("getDBNewChunk",e,t),_a=e=>Ea("setDBChunk",e),Da=e=>Ea("storeReceiveChunk",e),Ta=e=>Ea("deleteReceiveTransfer",e),Oa=e=>Ea("setDBNewChunk",e),Na=e=>Ea("deleteDBNewChunk",e),Ba=(e,t,n)=>Ea("deleteDBSendQueue",e,t,n),qa=(e,t)=>Ea("deleteRatchetSession",e,t),La=(e,t)=>Ea("getPinAttemptState",e,t),Fa=()=>Ea("getIdentityX25519"),za=()=>Ea("deleteIdentityX25519"),ja=e=>Ea("setIdentityEd25519",e),Ha=()=>Ea("deleteIdentityEd25519"),Va=(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!==m)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+=Lr(o),a+="~",a+="string"==typeof t?t:Lr(t),n(a)}catch(e){r(e)}}),$a=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=Fr(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=Fr(n[1]);if(i.length!==m)throw new Error("Merkle root has invalid length");t({channelLabel:o,merkleRoot:i,merkleRootHex:n[1]})}catch(e){n(e)}}),Qa=new Map,Wa=(e,t,n)=>`${e}\0${t}\0${n}`,Xa=(e,t,n)=>{const r=Wa(e,t,n);let a=Qa.get(r);return a||(a={acked:new Set,complete:!1},Qa.set(r,a)),a},Ga=(e,t,n)=>new Set(Xa(e,t,n).acked),Ja=(e,t,n)=>Xa(e,t,n).acked.size,Ya=(e,t,n)=>{const r=Xa(e,t,n);return!r.complete&&(r.complete=!0,!0)},Za=(e,t,n)=>Qa.get(Wa(e,t,n))?.complete??!1,eo=(e,t,n)=>{Qa.delete(Wa(e,t,n))},to=async(e,t,n,r,a)=>{const o=Date.now()+r;for(;Date.now()<o&&!Za(e,t,n)&&!a?.aborted;)await new Promise(e=>setTimeout(e,200));return!a?.aborted&&Za(e,t,n)},no=async(e,t,n,r,a)=>{try{const o=Lr(e),{merkleRootHex:i}=await $a(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 Ya(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)=>Ea("getDBNewChunkByReceipt",e,t))(i,o),t=e?.chunkIndex??-1;if(e&&e.transferId===u&&t>-1){const e=((e,t,n,r)=>{const a=Xa(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}},ro=e=>{const t=new Uint8Array(_);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+=m;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},ao=e=>{if(e.length!==_)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+m);t+=m;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 y=new DataView(e.buffer,e.byteOffset+t,8),g=Number(y.getBigUint64(0,!1));t+=8;const w=new DataView(e.buffer,e.byteOffset+t,8);return{schemaVersion:r,messageType:a,hash:o,totalSize:s,date:d,name:h,chunkStartIndex:p,chunkEndIndex:g,chunkIndex:Number(w.getBigUint64(0,!1))}},oo={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},io={Text:"Text",Image:"Image",Document:"Document",Audio:"Audio",Video:"Video",Compressed:"Compressed",Code:"Code",Ebook:"Ebook",Font:"Font",Executable:"Executable",Unknown:"Unknown"},so=e=>{switch(e){case oo.Text:return"text/plain";case oo.ImagePNG:return"image/png";case oo.ImageJPEG:case oo.ImageJPG:return"image/jpeg";case oo.ImageGIF:return"image/gif";case oo.ImageBMP:return"image/bmp";case oo.ImageTIFF:return"image/tiff";case oo.ImageSVG:return"image/svg+xml";case oo.ImageWEBP:return"image/webp";case oo.ImageHEIC:return"image/heic";case oo.ImageICO:return"image/vnd.microsoft.icon";case oo.DocumentPDF:return"application/pdf";case oo.DocumentDOC:return"application/msword";case oo.DocumentDOCX:return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case oo.DocumentXLS:return"application/vnd.ms-excel";case oo.DocumentXLSX:return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case oo.DocumentPPT:return"application/vnd.ms-powerpoint";case oo.DocumentPPTX:return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case oo.DocumentTXT:return"text/plain";case oo.DocumentRTF:return"application/rtf";case oo.DocumentODT:return"application/vnd.oasis.opendocument.text";case oo.AudioMP3:return"audio/mpeg";case oo.AudioWAV:return"audio/wav";case oo.AudioAAC:return"audio/aac";case oo.AudioFLAC:return"audio/flac";case oo.AudioOGG:return"audio/ogg";case oo.AudioM4A:return"audio/mp4";case oo.VideoMP4:return"video/mp4";case oo.VideoAVI:return"video/x-msvideo";case oo.VideoMKV:return"video/x-matroska";case oo.VideoMOV:return"video/quicktime";case oo.VideoWMV:return"video/x-ms-wmv";case oo.VideoFLV:return"video/x-flv";case oo.VideoWEBM:return"video/webm";case oo.CompressedZIP:return"application/zip";case oo.CompressedRAR:return"application/vnd.rar";case oo.Compressed7Z:return"application/x-7z-compressed";case oo.CompressedTAR:return"application/x-tar";case oo.CompressedGZ:return"application/gzip";case oo.CodeHTML:return"text/html";case oo.CodeCSS:return"text/css";case oo.CodeJS:case oo.CodeJSX:return"application/javascript";case oo.CodeTS:case oo.CodeTSX:return"application/typescript";case oo.CodeJSON:return"application/json";case oo.CodeXML:return"application/xml";case oo.CodePY:return"text/x-python";case oo.CodeJAVA:return"text/x-java-source";case oo.CodeC:return"text/x-c";case oo.CodeCPP:return"text/x-c++";case oo.CodeCS:return"text/plain";case oo.CodeRB:return"text/x-ruby";case oo.CodePHP:return"application/x-httpd-php";case oo.CodeSQL:return"application/sql";case oo.EbookEPUB:return"application/epub+zip";case oo.EbookMOBI:return"application/x-mobipocket-ebook";case oo.EbookAZW:return"application/vnd.amazon.ebook";case oo.FontTTF:return"font/ttf";case oo.FontOTF:return"font/otf";case oo.ExecutableEXE:return"application/vnd.microsoft.portable-executable";case oo.ExecutableDMG:return"application/x-apple-diskimage";case oo.ExecutableAPK:return"application/vnd.android.package-archive";default:return"application/octet-stream"}},co=(new TextEncoder).encode("p2party/protocol-v3/chunk-receipt/v1\0"),lo=async(e,t,n)=>{if(e.length!==m)throw new Error("Chunk receipt Merkle root must be 64 bytes");if(n.length!==m)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(co.length+e.length+8+n.length);let a=0;return r.set(co,a),a+=co.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(R);if(0!==e._x25519_keypair(t,n))throw e._free(t),ha(e,new Uint8Array(e.wasmMemory.buffer,n,R)),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,R));return e._free(t),ha(e,new Uint8Array(e.wasmMemory.buffer,n,R)),{publicKey:r,secretKey:a}},ho=async e=>{const t=e?.wasmMemory??Hr(),n=e??await ua(t);return uo(n)},fo=(e,t,n)=>{const r=n._malloc(x),a=n._malloc(R),o=n._malloc(x);new Uint8Array(n.wasmMemory.buffer,a,R).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(ha(n,new Uint8Array(n.wasmMemory.buffer,r,x)),ha(n,new Uint8Array(n.wasmMemory.buffer,a,R)),n._free(o),!i)throw new Error("x25519_dh failed (identity point)");return i},po=(e,t,n)=>{const r=Math.max(e.length,1),a=Math.max(t.length,1),o=n._malloc(p),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,p))}finally{ha(n,new Uint8Array(n.wasmMemory.buffer,o,p)),ha(n,new Uint8Array(n.wasmMemory.buffer,i,r)),ha(n,new Uint8Array(n.wasmMemory.buffer,s,a))}},mo=(e,t,n,r)=>{const a=r._malloc(n),o=r._malloc(p),i=r._malloc(Math.max(t.length,1));try{new Uint8Array(r.wasmMemory.buffer,o,p).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{ha(r,new Uint8Array(r.wasmMemory.buffer,a,n)),ha(r,new Uint8Array(r.wasmMemory.buffer,o,p)),r._free(i)}},yo=(new TextEncoder).encode("p2party-rk-v1"),go=(new TextEncoder).encode("p2party-ck-v1"),wo=(new TextEncoder).encode("p2party-mk-v1"),bo=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),vo=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},ko=(e,t,n)=>{const r=po(e,t,n),a=mo(r,yo,64,n);r.fill(0);const o=a.slice(0,32),i=a.slice(32,64);return a.fill(0),{rootKey:o,chainKey:i}},Io=(e,t)=>{const n=po(e,wo,t),r=po(e,go,t),a=n.slice(0,32),o=r.slice(0,32);return n.fill(0),r.fill(0),{chainKey:o,messageKey:a}},So=(e,t,n,r,a=X)=>{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=fo(i.dhSelfSec,i.dhRemotePub,r),t=ko(i.rootKey,e,r);e.fill(0),i.rootKey.fill(0),i.rootKey=t.rootKey,i.sendingChainKey=t.chainKey}return i},Ao=(e,t)=>{if(!e.sendingChainKey)throw new Error("ratchet: no sending chain");const{chainKey:n,messageKey:r}=Io(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}},Co=(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}=Io(e.receivingChainKey,n);e.receivingChainKey.fill(0),e.receivingChainKey=t,e.skipped.set(`${bo(e.dhRemotePub)}:${e.Nr}`,r),e.Nr+=1}if(e.skipped.size>G)for(const t of e.skipped.keys()){if(e.skipped.size<=G)break;e.skipped.get(t)?.fill(0),e.skipped.delete(t)}}},Eo=(e,t,n)=>{e.PN=e.Ns,e.Ns=0,e.Nr=0,e.dhRemotePub=Uint8Array.from(t.dhPub);let r=fo(e.dhSelfSec,e.dhRemotePub,n),a=ko(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=fo(e.dhSelfSec,e.dhRemotePub,n),a=ko(e.rootKey,r,n),r.fill(0),e.rootKey.fill(0),e.rootKey=a.rootKey,e.sendingChainKey?.fill(0),e.sendingChainKey=a.chainKey},Po=(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=`${bo(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))&&(Co(e,t.PN,n),Eo(e,t,n)),t.N<e.Nr)throw new Error("ratchet: message key already consumed");Co(e,t.N,n);const{chainKey:a,messageKey:o}=Io(e.receivingChainKey,n);return e.receivingChainKey.fill(0),e.receivingChainKey=a,e.Nr+=1,o},xo=e=>e.slice().buffer,Ro=e=>e?e.slice().buffer:null,Mo=e=>({rootSuite:e.rootSuite,rootKey:xo(e.rootKey),sendingChainKey:Ro(e.sendingChainKey),receivingChainKey:Ro(e.receivingChainKey),dhSelfPub:xo(e.dhSelfPub),dhSelfSec:xo(e.dhSelfSec),dhRemotePub:Ro(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:vo(e.slice(0,n)).slice().buffer,n:Number(e.slice(n+1)),messageKey:t.slice().buffer}})}),Ko=e=>{const t=new Map;for(const n of e.skippedMessageKeys){const e=new Uint8Array(n.dhPub);t.set(`${bo(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}},Uo=e=>Ko(Mo(e)),_o=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)},Do=(e,t)=>{if(e.rootSuite!==t.rootSuite)throw new Error("ratchet: cannot adopt a different root suite");_o(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},To=(1n<<64n)-1n,Oo=(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)},No=(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)},Bo=(e,t,n=0n)=>{if(e.dhPub.length!==F)throw new Error("chunkFrame: dhPub must be 32 bytes");if(t.length!==z)throw new Error("chunkFrame: nonce must be 12 bytes");const r=new Uint8Array(69);return r[0]=2,r.set(e.dhPub,1),Oo(r,33,e.N),Oo(r,41,e.PN),((e,t,n)=>{if("bigint"!=typeof n||n<0n||n>To)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},qo=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:No(e,33),PN:No(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},Lo=k,Fo=(1n<<64n)-1n,zo=(new TextEncoder).encode("p2party/pq-message-key/v1\0"),jo=(e,t,n)=>{if(!(e instanceof Uint8Array)||e.length!==n)throw new Error(`pqMessageKey: ${t} must be ${String(n)} bytes`)},Ho=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new Error(`pqMessageKey: ${t} is outside the safe u64 range`)},Vo=(e,t)=>{if("string"!=typeof(n=e.rootSuite)||!W.includes(n))throw new Error("pqMessageKey: unsupported root suite");var n;jo(e.rootKey,"rootKey",32),jo(e.binding,"binding",32),(e=>{if("bigint"!=typeof e||e<0n||e>Fo)throw new Error("pqMessageKey: epoch is outside the u64 range")})(e.epoch),jo(t.dhPub,"header.dhPub",F),Ho(t.N,"header.N"),Ho(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=zo.length+2+r.length+32+8+1+F+8+8,o=new Uint8Array(a);let i=0;o.set(zo,i),i+=zo.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+=F,s.setBigUint64(i,BigInt(t.N),!1),i+=8,s.setBigUint64(i,BigInt(t.PN),!1),o},$o=(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{jo(e,"classicalMessageKey",Lo);const a=Vo(t,n);return i=Uint8Array.from(t.rootKey),s=po(i,e,r),mo(s,a,Lo,r)}finally{e.fill(0),i?.fill(0),s?.fill(0)}},Qo=k,Wo=I,Xo=S,Go=m+57,Jo=(1n<<64n)-1n,Yo=(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>Jo)throw new Error("messageChunkCrypto: PQ epoch out of u64 range");return`${r}:${n.toString(10)}`},Zo=(e,t,n,r)=>{const a=e._malloc(M),o=e._malloc(N),i=e._malloc(m),s=e._malloc(Qo),c=new Uint8Array(e.wasmMemory.buffer,a,M),l=new Uint8Array(e.wasmMemory.buffer,o,N);c.fill(0),l.fill(0),c.set(t.subarray(0,M),0),new Uint8Array(e.wasmMemory.buffer,i,m).set(n),new Uint8Array(e.wasmMemory.buffer,s,Qo).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),ha(e,new Uint8Array(e.wasmMemory.buffer,s,Qo)),ha(e,l),{code:d,decrypted:u}},ei=(e,t,n,r,a,o)=>{if(r.length!==m)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const i=(()=>{const e=new Uint8Array(Wo);return crypto.getRandomValues(e),e})(),s=Bo(t,i,o?.epoch??0n),c=((e,t)=>{if(t.length<57)throw new Error("messageChunkCrypto: incomplete chunk frame header");const n=new Uint8Array(Go);return n.set(e,0),n.set(t.subarray(0,57),m),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+Xo,c=e._malloc(Qo),l=e._malloc(Wo),d=e._malloc(o),u=e._malloc(i),h=e._malloc(s);new Uint8Array(e.wasmMemory.buffer,c,Qo).set(t),new Uint8Array(e.wasmMemory.buffer,l,Wo).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(ha(e,new Uint8Array(e.wasmMemory.buffer,c,Qo)),e._free(l),ha(e,new Uint8Array(e.wasmMemory.buffer,d,o)),e._free(u),ha(e,new Uint8Array(e.wasmMemory.buffer,h,s)),!f)throw new Error("messageChunkCrypto: AEAD encrypt failed");return f})(a,o?l=$o(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)}},ti=(e,t,n,r,a,o)=>{if(r.length!==m)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const{header:i,pqEpoch:s}=qo(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=Yo(i.dhPub,i.N,o?s:void 0),f=n.get(h);if(f){const{code:e,decrypted:n}=Zo(a,t,r,f);return{decrypted:0===e?n:null,ok:0===e,stateAdvanced:!1}}const p=Uo(e);let y;try{y=ni(p,i,a),c&&(y=$o(y,c,i,a))}catch{return _o(p),{decrypted:null,ok:!1,stateAdvanced:!1}}const{code:g,decrypted:w}=Zo(a,t,r,y);return-2===g?(y.fill(0),_o(p),{decrypted:null,ok:!1,stateAdvanced:!1}):(Do(e,p),n.set(h,y),{decrypted:0===g?w:null,ok:0===g,stateAdvanced:!0})},ni=(e,t,n)=>{try{return Po(e,t,n)}catch(t){throw _o(e),t}},ri=(e,t)=>`${e.length}:${e}${t.length}:${t}`,ai=new Map,oi=new Map,ii=new WeakMap,si=async(e,t,n)=>{const r=ri(e,t),a=ai.get(r)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=a.catch(()=>{}).then(()=>i);ai.set(r,s),await a.catch(()=>{});try{return await n()}finally{o(),ai.get(r)===s&&ai.delete(r)}},ci=(e,t)=>{const n=ri(t,e.withPeerPublicKey),r=ii.get(e);if(r){if(oi.get(n)!==r)throw new Error("ratchet persistence: stale connection cannot reclaim edge");return}const a=Symbol(n);ii.set(e,a),oi.set(n,a)},li=(e,t)=>{const n=ri(t,e.withPeerPublicKey),r=ii.get(e);if(!r||oi.get(n)!==r)throw new Error("ratchet persistence: stale connection owner")},di=async(e,t,n,r,a=null)=>{const o=Mo(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=>Ea("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)=>si(t,n,()=>di(e,t,n,r,a)),hi=async(e,t,n,r,a=di,o=qa)=>si(n,e.withPeerPublicKey,async()=>{li(e,n);let i=!1;const s=e.serializeEdgeCryptoState?.()??null;try{i=!0,await a(t,n,e.withPeerPublicKey,e.withPeerId,s),li(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)}}),fi=new WeakMap,pi=async(e,t)=>{const n=fi.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>a);fi.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),fi.get(e)===o&&fi.delete(e)}},mi=async(e,t,n,r)=>pi(e,async()=>{const a=e.ratchetState;if(!a)throw new Error("ratchet persistence: no live ratchet state");const o=Uo(a);let i,s=!1;try{if(i=n(o),i.advanced){const n=i.stageEdgeCryptoState;if(r===ui)await si(t,e.withPeerPublicKey,async()=>{if(li(e,t),e.ratchetState!==a)throw new Error("ratchet persistence: live state changed");const r=n?.()??e.serializeEdgeCryptoState?.()??null;try{await di(o,t,e.withPeerPublicKey,e.withPeerId,r)}finally{r?.fill(0)}li(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");Do(a,o),s=!0}else _o(o);return i.commit?.(),i.value}catch(e){throw s||_o(o),i?.rollback?.(),e}}),yi=async(e,t,n,r=ui)=>mi(e,t,t=>{const r=Ao(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),gi=async(e,t,n,r,a=ui)=>mi(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),wi=new WeakMap,bi=async(e,t,n,r=gi)=>{let a=wi.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),wi.set(e,a);try{return await i}finally{a.get(n)===i&&a.delete(n),0===a.size&&wi.delete(e)}},vi=async(e,t,n,r,a=gi)=>!!(e=>void 0!==e&&Number.isSafeInteger(e.savedSize)&&Number.isSafeInteger(e.totalSize)&&e.savedSize>=0&&e.totalSize>0&&e.savedSize===e.totalSize)(r)&&bi(e,t,n,a),ki=()=>({date:new Date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!1,totalSize:0,messageType:oo.Text,filename:"",chunkHash:new Uint8Array,messageHash:new Uint8Array}),Ii=async(e,t,n=Da)=>{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)}},Si=async(e,t,n,r,a,o,i,s={})=>{if(i?.aborted)return ki();if(!r.ratchetState)return console.error("v3 receive: no ratchet state for peer"),ki();r.messageKeyCache||(r.messageKeyCache=r.pqHealingState?.activeReceiveKeys??new Map);const c=r.messageKeyCache;let l;try{const{header:t,pqEpoch:n}=qo(e);l=Yo(t.dhPub,t.N,r.pqHealingState?n:void 0)}catch{return ki()}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)=>mi(e,t,t=>{const i=e.pqHealingState,{header:s,pqEpoch:c}=qo(n),l=Yo(s.dhPub,s.N,i?c:void 0),d=new Map(r),u=ti(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>G;){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),ki()}if(!u||!d)return console.error("Could not decrypt or verify message"),ki();const h=Lr(a);((e,t,n)=>{e.messageKeyByMerkleRoot??=new Map,e.messageKeyByMerkleRoot.set(t,n)})(r,h,l);try{if(i?.aborted)return ki();const e=d.subarray(0,_),o=d.slice(_,_+m),c=d.subarray(_+D),l=ao(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!==m)throw new Error("Invalid metadata hash");if(!Number.isSafeInteger(e.totalSize)||e.totalSize<1||e.totalSize>K)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>M?0:l.chunkEndIndex-l.chunkStartIndex,g=()=>({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 g();if(f=l.chunkStartIndex,p=l.chunkEndIndex,y=c.length,!(Number.isSafeInteger(f)&&Number.isSafeInteger(p)&&f>=0&&p>=f&&p<=y))return g();const w=await lo(a,l.chunkIndex,o);if(i?.aborted)return w.fill(0),ki();const b=so(l.messageType),v=c.slice(l.chunkStartIndex,l.chunkEndIndex),k=await Ii({schemaVersion:l.schemaVersion,roomId:t,fromPeerId:r.withPeerId,channelLabel:n,timestamp:l.date.getTime(),merkleRoot:h,hash:Lr(l.hash),filename:l.name,messageType:l.messageType,chunkIndex:l.chunkIndex,mimeType:b,leafHash:Lr(o),realLen:u,totalSize:l.totalSize,storage:l.messageType===oo.Text?"indexeddb":"opfs"},v,s.storeReceiveChunk);if(!k)return w.fill(0),ki();if(i?.aborted)return w.fill(0),ki();const I=k.complete;return{date:l.date,chunkIndex:l.chunkIndex,chunkSize:u,receivedFullSize:I,chunkAlreadyExists:!k.stored,totalSize:l.totalSize,messageType:l.messageType,filename:l.name,chunkHash:w,messageHash:l.hash}}catch(e){return console.error("Could not parse or store decrypted message",e),ki()}finally{d.fill(0)}var f,p,y},Ai=new Map,Ci=(e,t)=>`${e}\0${t}`,Ei=(e,t)=>{const n=Ci(e,t);let r=Ai.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")}},Ai.set(n,r)}return r},Pi=(e,t)=>Ei(e,t).promise,xi=(e,t,n)=>Ai.get(Ci(e,t))?.lease===n,Ri=(e,t,n)=>{const r=Ai.get(Ci(e,t));return"open"===r?.outcome&&(void 0===n||r.lease===n)},Mi=(e,t,n,r)=>{const a=Ei(e,t);return(!r||a.lease===r)&&(a.settled||(a.settled=!0,a.outcome="rejected",a.reject(n)),!0)},Ki=e=>{if(e.length!==B)throw new Error("Receipt token must be exactly 64 bytes");const t=new Uint8Array(q);return t[0]=3,t.set(e,1),t},Ui=(e,t)=>"open"===e.readyState&&(e.send(Ki(t).buffer),!0),_i=async(e,t)=>{let n=0;for(const r of t){for(;"open"===e.readyState&&e.bufferedAmount>=U;)await new Promise(e=>setTimeout(e,25));if("open"!==e.readyState)return!1;e.send(Ki(r).buffer),n++,32===n&&(n=0,await new Promise(e=>setTimeout(e,10)))}return"open"===e.readyState},Di=new WeakMap,Ti=(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=Di.get(e);return t||(t={pending:[],drainJobActive:!1,jobSequence:0},Di.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 Oi(e,r,a),!0},Oi=(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,Oi(e,t,n)})},Ni=e=>{const t=Di.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,Di.delete(e)}},Bi=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?.()??qi;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!==j)throw new Error("coverTransfer: sealed transfer cell is not the uniform length");return o}}},qi=new Set,Li=e=>{if(e.byteLength<32)return`${String(e.byteLength)}:${Lr(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")},Fi=new Map,zi=new Map,ji=new WeakMap,Hi=new Map,Vi=(e,t)=>`${String(e.length)}:${e}${t}`,$i=(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()},Qi=(e,t)=>t.value||0!==e.length?new Promise(e=>{t.idleWaiters??=new Set,t.idleWaiters.add(e)}):Promise.resolve(),Wi=(e,t,n,r)=>{const a=Math.max(0,(ji.get(e)??0)+r);0===a?ji.delete(e):ji.set(e,a);const o=Vi(t,n),i=Math.max(0,(zi.get(o)??0)+r);0===i?zi.delete(o):zi.set(o,i)},Xi=async(e,t)=>{const n=Fi.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.then(()=>a);Fi.set(e,o),await n;try{return await t()}finally{r(),Fi.get(e)===o&&Fi.delete(e)}},Gi=(e,t)=>{const n=Vi(e.roomId,e.peerId),r=Math.max(0,(Hi.get(n)??0)+t);0===r?Hi.delete(n):Hi.set(n,r)},Ji=async(e,t)=>{if(e.draining||e.released)return;e.draining=!0;const n=Vi(e.roomId,e.peerId);try{for(;!e.released;){const r=e.pending.shift();if(!r)break;Gi(e,-1);try{await Xi(n,()=>t(r))}finally{e.seen.delete(Li(r))}}}catch(e){console.error(e)}finally{e.draining=!1,!e.released&&e.pending.length>0&&Ji(e,t)}},Yi=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(!xi(n,r,u))return{receivedFullSize:!1};if(await Pi(n,r),d?.aborted)return{receivedFullSize:!1};if(!xi(n,r,u))return{receivedFullSize:!1};const h=await Si(e,n,a,c,i,l,d),{date:f,chunkSize:p,chunkIndex:y,receivedFullSize:g,chunkAlreadyExists:w,totalSize:b,messageType:v,filename:k,messageHash:I}=h;if(d?.aborted)return{receivedFullSize:!1};c?.coverRuntime||((e,t)=>{if(e.totalSize>0&&e.chunkHash.length===m&&e.chunkIndex>-1&&e.chunkSize>0)return!!t&&Ui(t,e.chunkHash);if("open"!==t?.readyState)return!1;const n=new Uint8Array(m);crypto.getRandomValues(n),Ui(t,n)})(h,s);const S=Lr(I);return g&&c?.coverRuntime&&Ti(c,i,i),g?(await(e=>Ea("closeReceiveFile",e))(o),t.dispatch(Le({roomId:n,merkleRootHex:o,sha512Hex:S,fromPeerId:r,totalSize:b,messageType:v,filename:k,channelLabel:a,timestamp:f.getTime(),alsoSendFinishedMessage:!0})),(e=>void 0===e?.coverRuntime)(c)&&s&&Ui(s,I)):p>0&&y>-1&&!w&&t.dispatch(qe({roomId:n,merkleRootHex:o,sha512Hex:S,fromPeerId:r,chunkSize:p,totalSize:b,messageType:v,filename:k,channelLabel:a,timestamp:f.getTime()})),t.dispatch(Fe({roomId:n,merkleRootHex:o,real:p>0&&y>-1&&!w})),{receivedFullSize:g}}catch(e){return console.error(e),{receivedFullSize:!1}}return{receivedFullSize:!1}},Zi=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=Vi(a,o);try{for(;!n.released&&!h?.aborted;){const t=e.pop();if(!t)break;Wi(e,a,o,-t.byteLength),await Xi(f,async()=>Yi(t,r,a,o,i,s,c,l,d,u,h))}}finally{n.value=!1,e.length>0&&!n.released&&!h?.aborted?Zi(e,t,n,r,a,o,i,s,c,l,d,u,h):$i(e,n)}},es=e=>Object.freeze({...e,wasmExports:Object.freeze({...e.wasmExports})}),ts=es({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"}}),ns=es({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"}}),rs=es({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"}}),as=Object.freeze({512:ts,768:ns,1024:rs}),os=e=>{const t=as[e];if(void 0===t)throw new RangeError(`unsupported ML-KEM parameter set: ${String(e)}`);return t},is=(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`)},ss=(e,t,n,r)=>{const a=e._malloc(n);if(0===a)throw new Error(`${t.standardName}: failed to allocate ${r}`);return a},cs=(e,t,n)=>new Uint8Array(e.wasmMemory.buffer,t,n),ls=(e,t)=>{void 0!==t&&e._free(t)},ds=(e,t,n)=>{void 0!==t&&ha(e,cs(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=ss(e,t,t.publicKeyBytes,"public key"),r=ss(e,t,t.secretKeyBytes,"secret key"),a=ss(e,t,t.keyPairRandomBytes,"key-generation randomness");const o=cs(e,a,t.keyPairRandomBytes);oa(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(cs(e,n,t.publicKeyBytes)),Uint8Array.from(cs(e,r,t.secretKeyBytes)))}finally{ls(e,n),ds(e,r,t.secretKeyBytes),ds(e,a,t.keyPairRandomBytes)}}async encapsulate(e){await Promise.resolve();const t=this.#e,n=this.suite;let r,a,o,i;is(e,`${n.standardName} public key`,n.publicKeyBytes);try{r=ss(t,n,n.ciphertextBytes,"ciphertext"),a=ss(t,n,n.sharedSecretBytes,"shared secret"),o=ss(t,n,n.publicKeyBytes,"public key"),i=ss(t,n,n.encapsRandomBytes,"encapsulation randomness"),cs(t,o,n.publicKeyBytes).set(e);const s=cs(t,i,n.encapsRandomBytes);oa(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(cs(t,r,n.ciphertextBytes)),Uint8Array.from(cs(t,a,n.sharedSecretBytes)))}finally{ls(t,r),ds(t,a,n.sharedSecretBytes),ls(t,o),ds(t,i,n.encapsRandomBytes)}}async decapsulate(e,t){await Promise.resolve();const n=this.#e,r=this.suite;let a,o,i;is(e,`${r.standardName} ciphertext`,r.ciphertextBytes),is(t,`${r.standardName} secret key`,r.secretKeyBytes);try{a=ss(n,r,r.sharedSecretBytes,"shared secret"),o=ss(n,r,r.ciphertextBytes,"ciphertext"),i=ss(n,r,r.secretKeyBytes,"secret key"),cs(n,o,r.ciphertextBytes).set(e),cs(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(cs(n,a,r.sharedSecretBytes)))}finally{ds(n,a,r.sharedSecretBytes),ls(n,o),ds(n,i,r.secretKeyBytes)}}}const hs=(e,t)=>{const n=os(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)},fs=32,ps=32,ms=64,ys=new Uint8Array([80,50,81,72]),gs=(new TextEncoder).encode("p2party/pq-healing/root/v1\0"),ws=(1n<<64n)-1n;class bs extends Error{code;constructor(e,t){super(`pqHealing: ${t}`),this.name="PqHealingError",this.code=e}}const vs=(e,t)=>{throw new bs(e,t)},ks=(e,t,n)=>e instanceof Uint8Array?e.length!==n?vs("invalid-record",`${t} must be exactly ${String(n)} bytes`):e:vs("invalid-record",`${t} must be a Uint8Array`),Is=(e,t)=>{("bigint"!=typeof e||e<0n||e>ws)&&vs("overflow",`${t} is outside the unsigned 64-bit range`)},Ss=(e,t)=>{Is(e,t),e===ws&&vs("overflow",`${t} cannot advance beyond uint64`)},As=e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return vs("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")||vs("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 vs("invalid-record","advance acknowledgement fields must be enumerable data properties");const o=r.value,i=a.value;return"bigint"!=typeof o||"bigint"!=typeof i?vs("invalid-record","advance acknowledgement fields must be bigint values"):(Is(o,"advance acknowledgement epoch"),Is(i,"advance acknowledgement counter"),{epoch:o,advanceCounter:i})},Cs=(e,t,n)=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return vs("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 vs("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||vs("invalid-record",`${t}.${e} must be an enumerable data property`)}return r},Es=(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},Ps=e=>768===e?1:512===e?2:1024===e?3:vs("suite-mismatch","unsupported ML-KEM parameter set"),xs=e=>1===e?768:2===e?512:3===e?1024:vs("invalid-record","record has an unknown ML-KEM suite tag"),Rs=(e,t)=>Reflect.get(e,t),Ms=e=>{const t=os(e.parameterSet);e.standardName===t.standardName&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes&&Rs(e,"sharedSecretBytes")===t.sharedSecretBytes&&Rs(e,"keyPairRandomBytes")===t.keyPairRandomBytes&&Rs(e,"encapsRandomBytes")===t.encapsRandomBytes||vs("suite-mismatch","selected suite does not match its canonical FIPS 203 descriptor")},Ks=(e,t)=>{Ms(e),Ms(t),e.parameterSet===t.parameterSet&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes||vs("suite-mismatch","room-selected suite does not exactly match the ML-KEM backend")},Us=e=>ms+e.publicKeyBytes,_s=e=>ms+Us(e)+e.ciphertextBytes,Ds=(e,t,n)=>{Ms(t),ks(n,"binding",fs),ks(e,"ACK",64),Es(e.subarray(0,4),ys)||vs("invalid-record","ACK magic is invalid"),1!==e[4]&&vs("invalid-record","ACK version is unsupported"),3!==e[5]&&vs("invalid-record","ACK type is unexpected"),0!==e[7]&&vs("invalid-record","ACK reserved flags must be zero");xs(e[6])!==t.parameterSet&&vs("suite-mismatch","ACK suite differs from the authenticated room suite"),Es(e.subarray(8,40),n)||vs("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)&&vs("invalid-record","ACK reserved bytes must be zero"),{advanceCounter:r.getBigUint64(40,!1),epoch:r.getBigUint64(48,!1)}},Ts=(e,t,n,r,a,o,i)=>{ks(n,"binding",fs),Is(r,"sender counter"),Is(a,"from epoch"),Is(o,"to epoch"),a!==ws&&o===a+1n||vs("invalid-record","record must advance exactly one PQ epoch");const s=new Uint8Array(i);s.set(ys,0),s[4]=1,s[5]=e,s[6]=Ps(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},Os=(e,t,n,r)=>{e instanceof Uint8Array||vs("invalid-record","record must be a Uint8Array"),e.length<ms&&vs("invalid-record","record is shorter than its canonical header"),Es(e.subarray(0,4),ys)||vs("invalid-record","record magic is invalid"),1!==e[4]&&vs("invalid-record","record version is unsupported"),e[5]!==t&&vs("invalid-record","record type is unexpected"),0!==e[7]&&vs("invalid-record","record reserved flags must be zero");xs(e[6])!==n.parameterSet&&vs("suite-mismatch","record suite differs from the authenticated room suite");const a=e.subarray(8,40);void 0===r||Es(a,r)||vs("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!==ws&&c===s+1n||vs("invalid-record","record must advance exactly one PQ epoch"),{senderCounter:i,fromEpoch:s,toEpoch:c}},Ns=(e,t,n)=>{const r=Os(e,1,t,n);return e.length!==Us(t)&&vs("invalid-record","OFFER length is not canonical for its suite"),{...r,bytes:Uint8Array.from(e),publicKey:e.slice(ms)}},Bs=(e,t,n)=>{const r=Os(e,2,t,n);e.length!==_s(t)&&vs("invalid-record","ADVANCE length is not canonical for its suite");const a=Us(t),o=e.slice(ms,ms+a),i=Ns(o,t,n);return i.fromEpoch===r.fromEpoch&&i.toEpoch===r.toEpoch||vs("fork","ADVANCE epoch does not exactly match its embedded OFFER"),{...r,bytes:Uint8Array.from(e),offer:i,ciphertext:e.slice(ms+a)}},qs=(e,t)=>{if(Ms(t),!(e instanceof Uint8Array))return vs("invalid-record","record must be a Uint8Array");if(e.length<ms)return vs("invalid-record","record is shorter than its canonical header");if(1===e[5]){const n=Ns(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=Bs(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 vs("invalid-record","record type is unknown")},Ls=(e,t,n,r)=>{ks(e,"PQ root",ps);const a=po(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})(gs,n);try{return mo(a,o,ps,r)}finally{a.fill(0)}},Fs=(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)}}},zs=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)}}},js=(e,t)=>"bigint"!=typeof e?vs("invalid-record",`${t} must be a bigint`):(Is(e,t),e),Hs=(e,t,n)=>{const r=(e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return vs("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:vs("invalid-record","snapshot.phase.kind must be an enumerable string data property")})(e);switch(r){case"idle":return Cs(e,"snapshot.phase",["kind"]),{kind:"idle"};case"outbound-offer-prepared":case"outbound-offer-dispatched":{const a=Cs(e,"snapshot.phase",["kind","offer","secretKey"]),o=Ns(ks(a.offer,"snapshot.phase.offer",Us(t)),t,n),i=ks(a.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes);return{kind:"outbound-offer",dispatched:"outbound-offer-dispatched"===r,offer:o,keyPair:Fs(o.publicKey,i)}}case"inbound-offer":{const r=Cs(e,"snapshot.phase",["kind","offer"]);return{kind:"inbound-offer",offer:Ns(ks(r.offer,"snapshot.phase.offer",Us(t)),t,n)}}case"outbound-advance-prepared":{const r=Cs(e,"snapshot.phase",["kind","advance","nextRoot"]),a=Bs(ks(r.advance,"snapshot.phase.advance",_s(t)),t,n);return{kind:"outbound-advance-prepared",offer:a.offer,advance:a,nextRoot:Uint8Array.from(ks(r.nextRoot,"snapshot.phase.nextRoot",ps))}}case"outbound-advance-awaiting-ack":{const r=Cs(e,"snapshot.phase",["kind","advance"]),a=Bs(ks(r.advance,"snapshot.phase.advance",_s(t)),t,n);return{kind:"outbound-advance-awaiting-ack",offer:a.offer,advance:a}}case"inbound-advance-prepared":{const r=Cs(e,"snapshot.phase",["kind","advance","secretKey","nextRoot"]),a=Bs(ks(r.advance,"snapshot.phase.advance",_s(t)),t,n),o=ks(r.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes),i=Uint8Array.from(ks(r.nextRoot,"snapshot.phase.nextRoot",ps));return{kind:"inbound-advance-prepared",offer:a.offer,advance:a,keyPair:Fs(a.offer.publicKey,o),nextRoot:i}}case"inbound-advance-awaiting-ack-dispatch":{const r=Cs(e,"snapshot.phase",["kind","advance"]);return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Bs(ks(r.advance,"snapshot.phase.advance",_s(t)),t,n)}}default:return vs("invalid-record","snapshot phase is unknown")}},Vs=(e,t)=>{e||vs("invalid-record",`snapshot ${t}`)},$s=(e,t)=>{Ks(t.suite,t.backend.suite),ks(t.binding,"binding",fs);const n=Cs(e,"snapshot",["formatVersion","parameterSet","binding","rootKey","epoch","localCounter","remoteCounter","nextOfferer","phase","lastInboundOffer","lastInboundAdvance"]);1!==n.formatVersion&&vs("invalid-record","snapshot format version is unsupported"),n.parameterSet!==t.suite.parameterSet&&vs("suite-mismatch","snapshot suite differs from the authenticated room suite");const r=ks(n.binding,"snapshot.binding",fs);Es(r,t.binding)||vs("binding-mismatch","snapshot belongs to a different authenticated edge");const a=ks(n.rootKey,"snapshot.rootKey",ps),o=js(n.epoch,"snapshot.epoch"),i=js(n.localCounter,"snapshot.localCounter"),s=js(n.remoteCounter,"snapshot.remoteCounter");if("local"!==n.nextOfferer&&"remote"!==n.nextOfferer)return vs("invalid-record","snapshot.nextOfferer must be local or remote");const c=Uint8Array.from(a);let l;try{l=Hs(n.phase,t.suite,t.binding);const e=null===n.lastInboundOffer?null:Ns(ks(n.lastInboundOffer,"snapshot.lastInboundOffer",Us(t.suite)),t.suite,t.binding),r=null===n.lastInboundAdvance?null:Bs(ks(n.lastInboundAdvance,"snapshot.lastInboundAdvance",_s(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&&(Vs(i.toEpoch<=t,"last inbound OFFER is from a future epoch"),Vs(i.senderCounter<r,"last inbound OFFER counter was not consumed")),null!==s&&(Vs(s.toEpoch<=t,"last inbound ADVANCE is from a future epoch"),Vs(s.senderCounter<r,"last inbound ADVANCE counter was not consumed")),o.kind){case"idle":return;case"outbound-offer":return void Vs("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 Vs("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 Vs("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 Vs("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 Vs(null!==i&&Es(i.bytes,o.offer.bytes),"outbound ADVANCE is missing its exact inbound OFFER replay record");case"inbound-advance-prepared":return void Vs("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":Vs("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"),Vs(null!==s&&Es(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 Qs{#e;#n;#r;#a;#o;#i;#s;#c;#l;#d={kind:"idle"};#u=null;#h=null;#f=!1;#p=!1;constructor(e){Ks(e.suite,e.backend.suite),ks(e.binding,"binding",fs),ks(e.rootKey,"PQ root",ps);const t=e.nextOfferer;"local"!==t&&"remote"!==t&&vs("invalid-state","nextOfferer must be local or remote");const n=e.epoch??0n,r=e.localCounter??0n,a=e.remoteCounter??0n;Is(n,"epoch"),Is(r,"local counter"),Is(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=$s(e,t);try{const e=new Qs({...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:zs(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 Qs.restore(e,{module:this.#e,backend:this.#n,suite:this.#r,binding:this.#a})}finally{Ws(e)}}adopt(e){this.#y(),e.#y(),e===this&&vs("invalid-state","cannot adopt a machine into itself"),this.#r.parameterSet===e.#r.parameterSet&&Es(this.#a,e.#a)||vs("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(ps),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):vs("invalid-state","there is no pending outbound record")}async prepareOffer(){let e;this.#w();try{"idle"!==this.#d.kind&&vs("invalid-state","cannot prepare an OFFER while another transition is pending"),"local"!==this.#l&&vs("wrong-turn","the remote peer owns the next OFFER turn"),this.#b(),e=await this.#n.generateKeyPair(),this.#m(),ks(e.publicKey,"ML-KEM public key",this.#r.publicKeyBytes),ks(e.secretKey,"ML-KEM secret key",this.#r.secretKeyBytes);const t=((e,t,n,r,a)=>{ks(a,"ML-KEM public key",e.publicKeyBytes);const o=Ts(1,e,t,n,r,r+1n,Us(e));return o.set(a,ms),o})(this.#r,this.#a,this.#s,this.#i,e.publicKey),n=Ns(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 vs("invalid-state","there is no outbound OFFER to dispatch");e.dispatched&&vs("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 vs("invalid-state","only an undispatched OFFER can be aborted");e.keyPair.destroy(),this.#d={kind:"idle"}}acceptAuthenticatedOffer(e){this.#y();const t=Ns(e,this.#r,this.#a);this.#k(t),"idle"!==this.#d.kind&&vs("invalid-state","another PQ healing transition is pending"),"remote"!==this.#l&&vs("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 vs("invalid-state","an authenticated inbound OFFER is required");Ss(this.#s,"local counter"),e=await this.#n.encapsulate(t.offer.publicKey),this.#m(),ks(e.ciphertext,"ML-KEM ciphertext",this.#r.ciphertextBytes),ks(e.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const n=((e,t,n,r,a)=>{ks(a,"ML-KEM ciphertext",e.ciphertextBytes);const o=Ts(2,e,t,n,r.fromEpoch,r.toEpoch,_s(e));return o.set(r.bytes,ms),o.set(a,ms+r.bytes.length),o})(this.#r,this.#a,this.#s,t.offer,e.ciphertext),r=Bs(n,this.#r,this.#a),a=Ls(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?vs("invalid-state","there is no prepared outbound ADVANCE"):(this.#A(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=As(e),n=this.#d;if("outbound-advance-awaiting-ack"!==n.kind)return vs("invalid-state","no outbound ADVANCE is awaiting acknowledgement");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||vs("invalid-record","advance acknowledgement does not bind the pending transition"),this.#d={kind:"idle"}}async acceptAuthenticatedAdvance(e){let t;this.#w();try{const n=Bs(e,this.#r,this.#a);this.#C(n);const r=this.#d;if("outbound-offer"!==r.kind||!r.dispatched)return vs("invalid-state","a dispatched outbound OFFER is required before ADVANCE");this.#I(n.senderCounter),this.#S(n.fromEpoch),Es(n.offer.bytes,r.offer.bytes)||vs("fork","ADVANCE answers a different OFFER"),t=await this.#n.decapsulate(n.ciphertext,r.keyPair.secretKey),this.#m(),ks(t.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const a=Ls(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?vs("invalid-state","there is no accepted ADVANCE to commit"):(e.keyPair.destroy(),this.#A(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=As(e),n=this.#d;if("inbound-advance-awaiting-ack-dispatch"!==n.kind)return vs("invalid-state","no advance acknowledgement is pending dispatch");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||vs("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&&vs("destroyed","state machine is destroyed")}#y(){this.#m(),this.#f&&vs("invalid-state","another asynchronous transition is in flight")}#w(){this.#y(),this.#f=!0}#v(){this.#f=!1}#b(){Ss(this.#i,"epoch"),Ss(this.#s,"local counter"),Ss(this.#c,"remote counter")}#I(e){e<this.#c&&vs("replay","record sender counter was already consumed"),e>this.#c&&vs("counter-gap","record sender counter skips an expected transition")}#S(e){e<this.#i&&vs("replay","record PQ epoch was already consumed"),e>this.#i&&vs("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))&&(Es(e.bytes,t.bytes)&&vs("replay","OFFER is an exact replay"),vs("fork","different OFFER bytes reuse an authenticated slot"))}#C(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))&&(Es(e.bytes,t.bytes)&&vs("replay","ADVANCE is an exact replay"),vs("fork","different ADVANCE bytes reuse an authenticated slot"))}#A(e){ks(e,"candidate PQ root",ps),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 Ws=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)}},Xs=j-69-S,Gs=(1n<<64n)-1n,Js=(new TextEncoder).encode("p2party/pq-control-frame/key/v1\0");class Ys extends Error{code;constructor(e,t){super(`pqHealingFrame: ${t}`),this.name="PqControlFrameError",this.code=e}}const Zs=(e,t)=>{throw new Ys(e,t)},ec=(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},tc=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&Zs("invalid-frame",`${t} must be exactly ${String(n)} bytes`),e):Zs("invalid-frame",`${t} must be a Uint8Array`),nc=(e,t)=>"bigint"!=typeof e||e<0n||e>Gs?Zs("invalid-frame",`${t} must be an unsigned 64-bit bigint`):e,rc=(e,t,n,r,a,o)=>{tc(n,"PQ root",ps),tc(r,"binding",fs);const i=(e=>{const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t})(nc(o,"keyEpoch")),s=new Uint8Array(Js.length+1+1+r.length+i.length);s.set(Js,0),s[Js.length]=(e=>{const t=os(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?Zs("invalid-frame","ML-KEM suite descriptor is not canonical"):768===e.parameterSet?1:512===e.parameterSet?2:1024===e.parameterSet?3:Zs("invalid-frame","ML-KEM suite is unsupported")})(t),s[Js.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:Zs("invalid-direction","control direction is unknown"))(a),s.set(r,Js.length+2),s.set(i,Js.length+2+r.length);const c=po(n,r,e);try{return mo(c,s,k,e)}finally{c.fill(0),i.fill(0)}},ac=(e,t,n)=>{if(tc(e,"control record"),64===e.length){const r=Ds(e,t,n);return{counter:r.advanceCounter,keyEpoch:r.epoch}}const r=qs(e,t);return ec(r.binding,n)?{counter:r.senderCounter,keyEpoch:r.fromEpoch}:Zs("binding-mismatch","control record belongs to another authenticated edge")},oc=e=>{const t=tc(e.binding,"binding",fs),n=nc(e.keyEpoch,"keyEpoch"),r=ac(e.record,e.suite,t);r.keyEpoch!==n&&Zs("epoch-mismatch","control record is not authenticated under its required epoch"),e.record.length>Xs-4&&Zs("invalid-frame","control record does not fit the uniform cell");const a=(()=>{const e=new Uint8Array(I);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(Xs);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e.record.length,!1),s.set(e.record,4);const c=rc(e.module,e.suite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+S,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)?Zs("invalid-frame","control-frame AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{ha(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),ha(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),ha(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,c,a,s,o),n=new Uint8Array(j);return n.set(o,0),n.set(t,69),n}finally{c.fill(0),s.fill(0)}},ic=e=>{const t=tc(e.frame,"control frame",j),n=tc(e.binding,"binding",fs),r=nc(e.keyEpoch,"keyEpoch");5!==t[0]&&Zs("invalid-frame","frame type is not PQ control"),ec(t.subarray(1,33),n)||Zs("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)&&Zs("invalid-frame","control-frame reserved header must be zero"),o.getBigUint64(49,!1)!==r&&Zs("epoch-mismatch","control-frame epoch is not the expected epoch");const s=t.subarray(57,69),c=t.subarray(69),l=rc(e.module,e.suite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-S,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)?Zs("authentication-failed","control-frame authentication failed"):Uint8Array.from(u)}finally{ha(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),ha(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>Xs-4)&&Zs("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&&Zs("invalid-padding","encrypted control padding must be all zero");const h=d.slice(4,o),f=ac(h,e.suite,n);return f.keyEpoch!==r&&Zs("epoch-mismatch","decrypted control record does not match its frame epoch"),f.counter!==i&&Zs("record-mismatch","decrypted control counter does not match its public header"),h}finally{l.fill(0),d?.fill(0)}},sc=new Uint8Array([80,50,69,68,71,69,52,0]),cc=(1n<<64n)-1n,lc=262144,dc=Math.min(G,256),uc=/^[0-9a-f]{64}:[0-9]+:[0-9]+$/,hc=new TextEncoder,fc=new TextDecoder("utf-8",{fatal:!0}),pc=e=>{throw new Error(`pqHealingRuntime: ${e}`)},mc=(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},yc=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&pc(`${t} must be exactly ${String(n)} bytes`),e):pc(`${t} must be a Uint8Array`),gc=(e,t)=>"number"!=typeof e||!Number.isSafeInteger(e)||e<0?pc(`${t} must be a non-negative safe integer`):e,wc=e=>1===e?"local":2===e?"remote":pc("checkpoint has an invalid next-offerer turn");class bc{#E=[];#P=0;bytes(e){const t=Uint8Array.from(e);this.#E.push(t),this.#P+=t.length,this.#P>lc&&pc("checkpoint exceeds the encrypted edge-state budget")}u8(e){(!Number.isInteger(e)||e<0||e>255)&&pc("u8 value is out of range"),this.bytes(Uint8Array.of(e))}u16(e){(!Number.isInteger(e)||e<0||e>65535)&&pc("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)&&pc("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>cc)&&pc(`${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&&pc("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 vc{#x;#R=0;constructor(e){(0===e.length||e.length>lc)&&pc("checkpoint length is invalid"),this.#x=Uint8Array.from(e)}take(e){if(!Number.isSafeInteger(e)||e<0||this.#R+e>this.#x.length)return pc("checkpoint is truncated");const t=this.#x.slice(this.#R,this.#R+e);return this.#R+=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?pc("checkpoint field exceeds its budget"):this.take(t)}finish(){this.#R!==this.#x.length&&pc("checkpoint contains trailing bytes")}destroy(){this.#x.fill(0),this.#R=this.#x.length}}const kc=(e,t,n)=>e.sized(t)??pc(`${n} is missing`),Ic=(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:kc(e,n,"prepared OFFER"),secretKey:kc(e,t.secretKeyBytes,"prepared OFFER secret key")};case 2:return{kind:"outbound-offer-dispatched",offer:kc(e,n,"dispatched OFFER"),secretKey:kc(e,t.secretKeyBytes,"dispatched OFFER secret key")};case 3:return{kind:"inbound-offer",offer:kc(e,n,"inbound OFFER")};case 4:return{kind:"outbound-advance-prepared",advance:kc(e,r,"prepared ADVANCE"),nextRoot:kc(e,32,"candidate PQ root")};case 5:return{kind:"outbound-advance-awaiting-ack",advance:kc(e,r,"outbound ADVANCE")};case 6:return{kind:"inbound-advance-prepared",advance:kc(e,r,"inbound ADVANCE"),secretKey:kc(e,t.secretKeyBytes,"inbound ADVANCE secret key"),nextRoot:kc(e,32,"candidate PQ root")};case 7:return{kind:"inbound-advance-awaiting-ack-dispatch",advance:kc(e,r,"acknowledged ADVANCE")};default:return pc("checkpoint has an unknown PQ phase")}},Sc=e=>{for(const t of e.values())t.fill(0);e.clear()};class Ac{#e;#M;#K;#r;#n;#a;#U;#_;#D;#T;#O=null;#N=null;#B=null;#q=null;#L=new Map;#F=0;#z;#p=!1;constructor(e){const t=Z(e.pqMode);ee(e.pqMode)!==e.rootSuite&&pc("authenticated root suite and room PQ mode disagree"),yc(e.binding,"edge binding",32),yc(e.rootKey,"PQ root",32),this.#e=e.module,this.#M=e.pqMode,this.#K=e.rootSuite,this.#r=os(t),this.#n=hs(e.module,this.#r),this.#a=Uint8Array.from(e.binding),this.#D=new Qs({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=gc(e.now??Date.now(),"initial healing time"),this.#U=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#_=e.amInitiator?"responder-to-initiator":"initiator-to-responder"}get pqMode(){return this.#M}get rootSuite(){return this.#K}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.#K,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&&pc("application-message counter overflow"),this.#F+=1}healingDue(e=Date.now()){return this.#j(),gc(e,"healing clock"),!this.#D.trafficBlocked&&"local"===this.#D.nextOfferer&&(this.#F>=64||e-this.#z>=864e5)}copyPendingFrame(){return this.#j(),this.#O?Uint8Array.from(this.#O.frame):null}get pendingRetryAt(){return this.#j(),this.#O?.nextRetryAt??null}get pendingAttempts(){return this.#j(),this.#O?.attempts??0}markPendingDispatched(e=Date.now()){this.#j();const t=this.#O;if(!t)return pc("there is no PQ control outbox");gc(e,"dispatch clock"),t.attempts>=8&&pc("PQ control retry budget is exhausted"),this.#O={kind:t.kind,frame:t.frame,attempts:t.attempts+1,nextRetryAt:e+5e3}}async prepareHealingOffer(e=Date.now()){this.#j(),this.healingDue(e)||pc("a local sparse-PQ healing exchange is not due");const t=await this.#D.prepareOffer(),n=this.#D.copyRootKey();try{const r=oc({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#U,keyEpoch:this.#D.epoch,record:t});return this.#D.markOfferDispatched(),this.#O?.frame.fill(0),this.#O={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(),yc(e,"PQ control frame",j),gc(t,"control clock"),this.#N&&"advance"===this.#O?.kind&&mc(e,this.#N))return{dispatch:Uint8Array.from(this.#O.frame),changed:!1};if(this.#B&&this.#q&&mc(e,this.#B))return{dispatch:Uint8Array.from(this.#q),changed:!1};const n=this.#D.copyRootKey();let r=null;try{if(r=ic({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#_,keyEpoch:this.#D.epoch,frame:e}),64===r.length){const e=this.#O;if("advance"!==e?.kind)return pc("unexpected PQ ADVANCE acknowledgement");const n=Ds(r,this.#r,this.#a);return this.#D.acceptAuthenticatedAdvanceAcknowledgement(n),e.frame.fill(0),this.#O=null,this.#H(),this.#F=0,this.#z=t,this.#V(),{dispatch:null,changed:!0}}if("offer"===qs(r,this.#r).type){this.#D.acceptAuthenticatedOffer(r);const a=await this.#D.prepareAdvance();let o;try{o=oc({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#U,keyEpoch:this.#D.epoch,record:a}),this.#D.commitPreparedAdvance()}finally{a.fill(0)}return this.#O?.frame.fill(0),this.#O={kind:"advance",frame:Uint8Array.from(o),attempts:0,nextRetryAt:t},this.#N?.fill(0),this.#N=Uint8Array.from(e),this.#B?.fill(0),this.#B=null,this.#q?.fill(0),this.#q=null,this.#V(),{dispatch:o,changed:!0}}const a=this.#O;if("offer"!==a?.kind)return pc("unexpected PQ ADVANCE without a persisted OFFER");await this.#D.acceptAuthenticatedAdvance(r);const o=this.#D.commitAcceptedAdvance(),i=((e,t,n)=>{Ms(t),ks(n,"binding",fs);const r=As(e),a=new Uint8Array(64);a.set(ys,0),a[4]=1,a[5]=3,a[6]=Ps(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=oc({module:this.#e,suite:this.#r,rootKey:s,binding:this.#a,direction:this.#U,keyEpoch:o.epoch,record:i});return this.#D.markAdvanceAcknowledgementDispatched(o),a.frame.fill(0),this.#O=null,this.#B?.fill(0),this.#B=Uint8Array.from(e),this.#q?.fill(0),this.#q=Uint8Array.from(n),this.#N?.fill(0),this.#N=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 Ac({module:this.#e,pqMode:this.#M,rootSuite:this.#K,binding:this.#a,rootKey:e,nextOfferer:this.#D.nextOfferer,amInitiator:"initiator-to-responder"===this.#U,now:this.#z}),t.#D.destroy(),t.#D=this.#D.clone(),t.#T.fill(0),t.#T=Uint8Array.from(this.#T),t.#O=null===(n=this.#O)?null:{kind:n.kind,frame:Uint8Array.from(n.frame),attempts:n.attempts,nextRetryAt:n.nextRetryAt},t.#N=null===this.#N?null:Uint8Array.from(this.#N),t.#B=null===this.#B?null:Uint8Array.from(this.#B),t.#q=null===this.#q?null:Uint8Array.from(this.#q),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&&pc("cannot adopt a PQ runtime into itself"),e.#e===this.#e&&e.#M===this.#M&&e.#K===this.#K&&e.#U===this.#U&&mc(e.#a,this.#a)||pc("cannot adopt a PQ runtime from another authenticated edge"),this.#D.destroy(),this.#T.fill(0),this.#O?.frame.fill(0),this.#N?.fill(0),this.#B?.fill(0),this.#q?.fill(0),Sc(this.#L),this.#D=e.#D,this.#T=e.#T,this.#O=e.#O,this.#N=e.#N,this.#B=e.#B,this.#q=e.#q,this.#L=e.#L,this.#F=e.#F,this.#z=e.#z,e.#T=new Uint8Array(32),e.#O=null,e.#N=null,e.#B=null,e.#q=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 bc;try{return n.bytes(sc),n.u8(1),n.u8(512===(a=this.#r.parameterSet)?1:768===a?2:1024===a?3:pc("unsupported ML-KEM suite")),n.u8("initiator-to-responder"===this.#U?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:pc("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.#O),n.sized(this.#N),n.sized(this.#B),n.sized(this.#q),((e,t)=>{t.size>dc&&pc("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)||pc("active receive cache key is non-canonical");const n=hc.encode(t);(0===n.length||n.length>160)&&pc("active receive cache key length is invalid"),yc(r,"active receive message key",32),e.u16(n.length),e.bytes(n),e.bytes(r)}})(n,e),n.finish()}finally{Ws(t)}var r,a}static readCheckpointBinding(e){yc(e,"checkpoint");const t=sc.length+1+1+1+1+8+8;return e.length<t+32?pc("checkpoint is too short to contain a binding"):e.slice(t,t+32)}static restore(e,t){yc(e,"encrypted edge checkpoint plaintext"),yc(t.binding,"expected edge binding",32);const n=new vc(e);let r=null,a=null,o=null,i=null,s=null,c=null,l=null,d=null;try{const e=n.take(sc.length),h=mc(e,sc);e.fill(0),h||pc("checkpoint magic is invalid"),1!==n.u8()&&pc("checkpoint version is unsupported");const f=1===(u=n.u8())?512:2===u?768:3===u?1024:pc("checkpoint has an unknown ML-KEM suite");f!==Z(t.pqMode)&&pc("checkpoint suite disagrees with the authenticated room policy"),ee(t.pqMode)!==t.rootSuite&&pc("authenticated root suite and room PQ mode disagree");const p=n.u8();p!==(t.amInitiator?1:2)&&pc("checkpoint belongs to the opposite edge direction"),0!==n.u8()&&pc("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))&&pc("checkpoint counters exceed the safe-integer range");const g=n.take(32);mc(g,t.binding)||pc("checkpoint belongs to another authenticated edge");const w=n.take(32),b=os(f);r={formatVersion:1,parameterSet:f,binding:g,rootKey:w,epoch:n.u64(),localCounter:n.u64(),remoteCounter:n.u64(),nextOfferer:wc(n.u8()),phase:Ic(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 pc("checkpoint outbox kind is invalid");const n=e.u8();n>8&&pc("checkpoint outbox attempts exceed the retry budget");const r=e.u64();r>BigInt(Number.MAX_SAFE_INTEGER)&&pc("checkpoint retry deadline exceeds the safe-integer range");const a=kc(e,j,"outbox frame");return yc(a,"outbox frame",j),{kind:1===t?"offer":"advance",attempts:n,nextRetryAt:Number(r),frame:a}})(n),c=n.sized(j),l=n.sized(j),d=n.sized(j);for(const e of[c,l,d])e&&yc(e,"cached control frame",j);i=(e=>{const t=e.u16();t>dc&&pc("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)&&pc("checkpoint active receive cache key length is invalid");const r=e.take(t);let a;try{a=fc.decode(r)}finally{r.fill(0)}0!==a.length&&uc.test(a)&&!n.has(a)||pc("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=hs(t.module,b);a=Qs.restore(r,{module:t.module,backend:v,suite:b,binding:t.binding});const k=a.copyRootKey();try{o=new Ac({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.#O=s,s=null,o.#N=c,c=null,o.#B=l,l=null,o.#q=d,d=null,o.#L=i,i=null,o.#F=Number(y),o.#$(),o}catch(e){throw o?.destroy(),e}finally{n.destroy(),r&&Ws(r),a?.destroy(),s?.frame.fill(0),c?.fill(0),l?.fill(0),d?.fill(0),i&&Sc(i)}var u}destroy(){this.#p||(this.#D.destroy(),this.#a.fill(0),this.#T.fill(0),this.#O?.frame.fill(0),this.#N?.fill(0),this.#B?.fill(0),this.#q?.fill(0),Sc(this.#L),this.#O=null,this.#N=null,this.#B=null,this.#q=null,this.#p=!0)}#V(){const e=this.#D.copyRootKey();this.#T.fill(0),this.#T=e}#H(){this.#N?.fill(0),this.#B?.fill(0),this.#q?.fill(0),this.#N=null,this.#B=null,this.#q=null}#$(){const e=this.#D.phase;("outbound-offer-dispatched"===e&&"offer"!==this.#O?.kind||"outbound-advance-awaiting-ack"===e&&"advance"!==this.#O?.kind||"offer"===this.#O?.kind&&"outbound-offer-dispatched"!==e||"advance"===this.#O?.kind&&"outbound-advance-awaiting-ack"!==e)&&pc("checkpoint PQ phase and sealed outbox disagree"),null!==this.#N&&"advance"!==this.#O?.kind&&pc("checkpoint cached OFFER has no matching ADVANCE outbox"),null===this.#B!=(null===this.#q)&&pc("checkpoint ADVANCE replay and ACK cache must be paired"),null!==this.#N&&null!==this.#B&&pc("checkpoint contains mutually exclusive replay caches")}#j(){this.#p&&pc("state is destroyed")}}const Cc=new TextEncoder,Ec=Cc.encode("CPaceRistretto255"),Pc=Cc.encode("CPaceRistretto255_ISK"),xc=new Uint8Array(0),Rc=(e,t,n)=>{if(t.length!==n)throw new Error(`cpace: ${e} must be ${n} bytes`)},Mc=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)},Kc=(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?ha(e,o):e._free(a)}},Uc=(e,t,n)=>{Kc(e,t,Mc(n.data.length)),Kc(e,t,n.data,n.secret)},_c=(e,t,n,r)=>{const a=Math.max(0,127-(Mc(Ec.length).length+Ec.length)-(Mc(e.length).length+e.length)),o=((e,t)=>{const n=e._malloc(y),r=e._malloc(m),a=new Uint8Array(e.wasmMemory.buffer,n,y),o=new Uint8Array(e.wasmMemory.buffer,r,m);try{if(a.fill(0),o.fill(0),0!==e._sha512_init(n))throw new Error("sha512_init failed");for(const r of t)Uc(e,n,r);if(0!==e._sha512_final(n,r))throw new Error("sha512_final failed");return Uint8Array.from(o)}finally{ha(e,a),ha(e,o)}})(r,[{data:Ec},{data:e,secret:!0},{data:new Uint8Array(a)},{data:n},{data:t}]),i=r._malloc(E),s=r._malloc(C),c=new Uint8Array(r.wasmMemory.buffer,i,E),l=new Uint8Array(r.wasmMemory.buffer,s,C);try{return c.set(o),l.fill(0),r._cpace_ristretto255_from_hash(s,i),Uint8Array.from(l)}finally{o.fill(0),ha(r,c),r._free(s)}},Dc=(new TextEncoder).encode("p2party-interactive-3dh-v2"),Tc=new Uint8Array(64),Oc=e=>{const t=new Uint8Array(H.length+e.length);return t.set(H,0),t.set(e,H.length),t},Nc=async(e,t,n)=>pa(Oc(e),t,n),Bc=async(e,t,n,r)=>ma(Oc(e),t,n,r),qc=e=>{const t=(e=>{if("hybrid-mlkem768"===e)return L;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},Lc=(new TextEncoder).encode("p2party-v4-hs-kc-transcript-v4"),Fc=(new TextEncoder).encode("p2party-v4-hs-kc-responder-v4"),zc=(new TextEncoder).encode("p2party-v4-hs-kc-initiator-ratchet-dh-v4"),jc=(new TextEncoder).encode("p2party-v4-hs-kc-responder-finish-v4"),Hc=new Uint8Array(64),Vc=(new TextEncoder).encode("p2party-v4-pq-healing-extract-v1"),$c=(new TextEncoder).encode("p2party-v4-pq-healing-root-v1"),Qc=(new TextEncoder).encode("p2party-v4-pq-healing-binding-v1\0"),Wc=64,Xc=129,Gc=e=>{const t=os(Z(e)),n=193+t.publicKeyBytes;return{suite:t,publicKeyOffset:193,ciphertextOffset:n,length:n+t.ciphertextBytes}},Jc=(e,t,n)=>{const r=n._malloc(e.length),a=n._malloc(t.length),o=n._malloc(Wc);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,Wc))}finally{ha(n,new Uint8Array(n.wasmMemory.buffer,r,e.length)),n._free(a),n._free(o)}},Yc=e=>{let t=0;for(const n of e)t|=n;return 0===t},Zc=(e,t)=>{const n=new Uint8Array(97);return n[0]=2,n.set(e,1),n.set(t,33),n},el=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=Gc(a),f=hs(n,h.suite),p=ee(a),g=crypto.getRandomValues(new Uint8Array(32)),w=uo(n);let b=new Uint8Array(32),v=null;const k=new Uint8Array(h.suite.publicKeyBytes),I=new Uint8Array(h.suite.ciphertextBytes);let S,A,E,x,R,M,K,U,_=null,D=null,T=null;const O=e=>{if("pin"!==r)return null;if(!o)throw new Error("PIN mode requires a PIN");const t=_c(o,e,i,n),a=((e,t)=>{Rc("generator",e,C);const n=t._malloc(P),r=t._malloc(C),a=t._malloc(C),o=new Uint8Array(t.wasmMemory.buffer,n,P),i=new Uint8Array(t.wasmMemory.buffer,r,C),s=new Uint8Array(t.wasmMemory.buffer,a,C);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{ha(t,o),t._free(r),t._free(a)}})(t,n);return t.fill(0),a},N=()=>((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,Xc),c.set(i,e.publicKeyOffset),c.set(s,e.ciphertextOffset),c})(h,g,w.publicKey,b,l,d,k,I);try{let t;if(s){_=await f.generateKeyPair(),k.set(_.publicKey);const n=O(g);n&&(v=n.y,b=n.Y),await e.send(N()),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),B=t.subarray(65,97),q=t.subarray(97,129),L=t.subarray(Xc,193),z=t.subarray(h.publicKeyOffset,h.publicKeyOffset+h.suite.publicKeyBytes),j=t.subarray(h.ciphertextOffset,h.ciphertextOffset+h.suite.ciphertextBytes);if(s){if(!Yc(z))throw new Error("Malformed handshake HELLO: responder ML-KEM public-key field must be zero");if(Yc(j))throw new Error("Malformed handshake HELLO: responder ML-KEM ciphertext is required")}else{if(Yc(z))throw new Error("Malformed handshake HELLO: initiator ML-KEM public key is required");if(!Yc(j))throw new Error("Malformed handshake HELLO: initiator ML-KEM ciphertext field must be zero")}if(!await Bc(q,L,u,n))throw new Error("Handshake peer X25519 identity cross-signature invalid");if(s){if(!_)throw new Error("Handshake ML-KEM initiator keypair is unavailable");D=await f.decapsulate(j,_.secretKey),_.destroy()}else{const t=await f.encapsulate(z);D=t,I.set(t.ciphertext);const n=O(a);n&&(v=n.y,b=n.Y),await e.send(N())}S=((e,t,n,r,a,o)=>{let i,s;const c=fo(n,r,o);a?(i=fo(e,r,o),s=fo(n,t,o)):(i=fo(n,t,o),s=fo(e,r,o));const l=new Uint8Array(96);l.set(i,0),l.set(s,32),l.set(c,64);const d=po(Tc,l,o),u=mo(d,Dc,32,o);return l.fill(0),i.fill(0),s.fill(0),c.fill(0),d.fill(0),u})(c,q,w.secretKey,o,s,n);const H=s?g:a,V=s?a:g,$=s?w.publicKey:o,Q=s?o:w.publicKey,W=s?b:B,X=s?B:b,G=s?l:q,J=s?d:L,Y=s?q:l,Z=s?L:d,ee=s?k:z,te=s?I:j,ne=s?z:k,re=s?j:I;if("pin"===r){if(!v)throw new Error("Handshake CPace scalar is unavailable");A=((e,t)=>{const{y:n,peerShare:r,sid:a,initiatorShare:o,responderShare:i,initiatorAssociatedData:s=xc,responderAssociatedData:c=xc}=e;Rc("private scalar",n,P),Rc("peer share",r,C),Rc("initiator share",o,C),Rc("responder share",i,C);const l=t._malloc(P),d=t._malloc(C),u=t._malloc(C),h=t._malloc(y),f=t._malloc(m),p=new Uint8Array(t.wasmMemory.buffer,l,P),g=new Uint8Array(t.wasmMemory.buffer,d,C),w=new Uint8Array(t.wasmMemory.buffer,u,C),b=new Uint8Array(t.wasmMemory.buffer,h,y),v=new Uint8Array(t.wasmMemory.buffer,f,m);try{if(p.set(n),g.set(r),w.fill(0),b.fill(0),v.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(Uc(t,h,{data:Pc}),Uc(t,h,{data:a}),Kc(t,h,Mc(C)),0!==t._sha512_update(h,u,C))throw new Error("sha512_update failed");if(Uc(t,h,{data:o}),Uc(t,h,{data:s}),Uc(t,h,{data:i}),Uc(t,h,{data:c}),0!==t._sha512_final(h,f))throw new Error("sha512_final failed");return Uint8Array.from(v)}finally{ha(t,p),t._free(d),ha(t,w),ha(t,b),ha(t,v)}})({y:v,peerShare:B,sid:H,initiatorShare:W,responderShare:X},n)}const ae=((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);E=await Br("pin"===r?[A,S,D.sharedSecret]:[S,D.sharedSecret]),x=po(Hc,E,n);const oe=await Br([ae,i,G,J,Y,Z,ee,re]);R=mo(x,oe,32,n);const ie=await Br([Qc,i,H,V,$,Q,G,J,Y,Z,ee,re]);try{U=new Uint8Array(await crypto.subtle.digest("SHA-256",ie.slice().buffer))}finally{ie.fill(0)}M=po(Vc,R,n);const se=await Br([$c,U]);try{K=mo(M,se,32,n)}finally{se.fill(0),M.fill(0),M=void 0}S.fill(0),A?.fill(0),E.fill(0),x.fill(0),D.destroy();const ce=(e,t,n,r=[])=>Br([Lc,e,H,V,$,Q,W,X,G,J,Y,Z,ee,te,ne,re,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);T=So(R,!0,r,n,p);const o=T.dhSelfPub,i=await ce(zc,r,o,[a]),s=Jc(R,i,n);try{await e.send(Zc(o,s));const t=await ce(Fc,r),i=Jc(R,t,n),c=await qr(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 ce(jc,r,o,[a,s]),h=Jc(R,u,n),f=await qr(d,h);if(h.fill(0),!f)throw new Error("Handshake final confirmation failed")}finally{s.fill(0)}}else{T=So(R,!1,null,n,p);const t=T.dhSelfPub,r=await ce(Fc,t),a=Jc(R,r,n);try{await e.send(Zc(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 ce(zc,t,o,[a]),c=Jc(R,s,n),l=await qr(i,c);if(c.fill(0),!l)throw new Error("Handshake key-confirmation failed");((e,t,n)=>{if(t.length!==F)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");Eo(e,{dhPub:t},n)})(T,o,n);const d=await ce(jc,t,o,[a,i]),u=Jc(R,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(!T)throw new Error("Handshake ratchet initialization failed");if(!K||!U)throw new Error("Handshake PQ-healing bootstrap failed");const le=T;T=null;const de={rootKey:K,binding:U,nextOfferer:s?"local":"remote"};return K=void 0,U=void 0,{state:le,secret:R,pqHealing:de}}catch(e){throw R?.fill(0),K?.fill(0),U?.fill(0),e}finally{w.secretKey.fill(0),v?.fill(0),S?.fill(0),A?.fill(0),E?.fill(0),x?.fill(0),M?.fill(0),K?.fill(0),U?.fill(0),D?.destroy(),_?.destroy(),T&&_o(T)}},tl=/a=fingerprint:sha-256\s+([0-9A-Fa-f:]+)/,nl=e=>{const t=tl.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)},rl=e=>e.replace(/:/g,"").toLowerCase(),al=new Map,ol=(e,t)=>`${e}\0${t}`,il=(e,t,n=new Error("Handshake channel closed"),r)=>{const a=ol(e,t),o=al.get(a);if(!o||r&&o.lease!==r)return!1;al.delete(a);for(const e of o.waiters)e.reject(n);return!0},sl=(e,t,n,r)=>{const a=al.get(ol(e,t));if(!a||a.lease!==r)return!1;if(null===a.nextStep||!((e,t,n="hybrid-mlkem768")=>1===t?e.length===Gc(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 il(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},cl=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=rl(Lr(nl(t))),a=rl(Lr(nl(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=rl(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}=Pu.getState().keyPair,p=ba(f,e.withPeerPublicKey),m=await Fa();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=Fr(e.withPeerPublicKey),b=((e,t,n)=>{const r=ol(e,t),a=al.get(r);if(!a||a.lease!==n)throw new Error(`No owned handshake channel registered for ${t}`);const o=()=>{if(al.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 el(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 Ac({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),!xi(t,e.withPeerId,c))throw new Error("Handshake transport lease is stale");ci(e,t),await(async(e,t,n,r,a,o)=>{const i=()=>n.pqRuntime.serialize();e.serializeEdgeCryptoState=i;try{await hi(e,n.state,t,()=>{r(),e.ratchetState&&_o(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(!xi(t,e.withPeerId,c))throw new Error("Handshake transport lease was replaced during persistence");if(!((e,t,n)=>{const r=Ei(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 Mi(t,e.withPeerId,n,c),n}finally{d?.fill(0),l?.fill(0),u&&_o(u),h?.destroy(),il(t,e.withPeerId,new Error("Handshake attempt finished"),s)}},ll=new WeakMap,dl=(e,t,n,r)=>(async(e,t,n,r)=>si(n,e.withPeerPublicKey,async()=>{li(e,n);const a=r?.()??e.serializeEdgeCryptoState?.()??null;try{await di(t,n,e.withPeerPublicKey,e.withPeerId,a)}finally{a?.fill(0)}li(e,n)}))(e,t,n,r),ul=e=>{throw new Error(`pqHealingOrchestrator: ${e}`)};class hl extends Error{constructor(e){super("pqHealingOrchestrator: edge checkpoint persistence failed",{cause:e}),this.name="PqPersistenceError"}}const fl=e=>{const t=ll.get(e);return!(!t||!t.inboundBlocked&&!t.failed)||(e.pqHealingState?.trafficBlocked??!1)},pl=(e,t)=>0===(e.messageChannels?.size??0)&&!((e,t)=>{const n=Vi(e,t);return(zi.get(n)??0)>0||Fi.has(n)})(t,e.withPeerId),ml=async(e,t,n)=>pi(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 hl(e)}if(e.pqHealingState!==r)throw new hl(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))}),yl=e=>{const t=ll.get(e);t&&(t.destroyed=!0,null!==t.interval&&clearInterval(t.interval),t.interval=null,ll.delete(e))},gl=(e,t)=>{e.failed||(e.failed=!0,e.hooks.failEdge(t))},wl=async e=>{const t=ll.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 gl(t,new Error("pqHealingOrchestrator: control retry budget exhausted; failing the authenticated edge")):void await ml(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&&pl(e,t.roomId)&&await ml(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}}},bl=async(e,t,n)=>{const r=ll.get(e),a=e.pqHealingState;if(r&&!r.destroyed&&!r.failed&&a)if(n.length===j){r.inboundBlocked=!0;try{await(async(e,t)=>{const n=Vi(e,t);for(;;){const e=Fi.get(n);if(!e&&0===(zi.get(n)??0))return;e?await e.catch(()=>{}):await new Promise(e=>setTimeout(e,10))}})(t,e.withPeerId);const a=r.now();await ml(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 hl)return void console.error("pqHealingOrchestrator: inbound transition not durable",e);gl(r,new Error("pqHealingOrchestrator: unauthenticated or forked control cell; failing the authenticated edge",{cause:e}))}finally{r.inboundBlocked=!1}}else gl(r,new Error("pqHealingOrchestrator: malformed control cell length"))},vl=(e,t)=>{if(!Number.isSafeInteger(t))throw new Error(`coverScheduler: ${e} must be a safe integer`)},kl=(e,t)=>{if(!(t instanceof Uint8Array))throw new Error(`coverScheduler: ${e} must return a Uint8Array`);return t},Il=e=>e.cancelRequested?0:"control"===e.job.kind?1:2,Sl=(e,t)=>{const n=Il(e)-Il(t);if(0!==n)return n;return(t.job.priority??0)-(e.job.priority??0)||e.sequence-t.sequence},Al=e=>({id:e.job.id,kind:e.job.kind,declaredCellCount:e.job.declaredCellCount});class Cl{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(Pl(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>=El(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(Sl).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(vl("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&&vl("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 vl("cycle index",t),t}sortQueue(){this.queued.sort(Sl)}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?Al(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??kl("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:kl("nextCell",r),source:n.job.kind,slot:t,jobId:n.job.id,jobCellIndex:n.sentCells}}}}return{cell:kl("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 El=e=>e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell),Pl=e=>{if(null===e||"object"!=typeof e)throw new Error("coverScheduler: schedule must be an object");if(vl("phase offset",e.phaseOffsetMs),vl("cover cadence",e.coverCadenceMs),vl("cover lanes",e.coverLanes),vl("cover frames per cell",e.coverFramesPerCell),vl("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(El(e)<25)throw new Error("coverScheduler: schedule requires at least 25ms per staggered slot")},xl=j-69-S,Rl=m,Ml=xl-1-4,Kl=(1n<<64n)-1n,Ul=(new TextEncoder).encode("p2party/cover-cell/key/v1\0");class _l extends Error{code;constructor(e,t){super(`coverCell: ${t}`),this.name="CoverCellError",this.code=e}}const Dl=(e,t)=>{throw new _l(e,t)},Tl=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&Dl("invalid-cell",`${t} must be exactly ${String(n)} bytes`),e):Dl("invalid-cell",`${t} must be a Uint8Array`),Ol=(e,t)=>"bigint"!=typeof e||e<0n||e>Kl?Dl("invalid-cell",`${t} must be an unsigned 64-bit bigint`):e,Nl=(e,t,n,r,a,o)=>{Tl(n,"PQ message root",32),Tl(r,"edge binding",32);const i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,Ol(o,"keyEpoch"),!1);const s=new Uint8Array(Ul.length+1+1+r.length+i.length);s.set(Ul,0),s[Ul.length]=(e=>e===$?1:e===V?2:e===Q?3:Dl("invalid-cell","authenticated room suite is unsupported"))(t),s[Ul.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:Dl("invalid-direction","cover-cell direction is unknown"))(a),s.set(r,Ul.length+2),s.set(i,Ul.length+2+r.length);const c=po(n,r,e);try{return mo(c,s,k,e)}finally{c.fill(0),i.fill(0)}},Bl=e=>{const t=Tl(e.binding,"edge binding",32),n=Ol(e.keyEpoch,"keyEpoch"),r=Ol(e.counter,"counter"),a=(e=>{if("dummy"===e.subtype)return new Uint8Array(0);if("cancel"===e.subtype)return Uint8Array.from(Tl(e.merkleRoot,"cancel transfer root",Rl));const t=Tl(e.merkleRoot,"receipt transfer root",Rl),n=Tl(e.token,"receipt token",Rl),r=new Uint8Array(t.length+n.length);return r.set(t,0),r.set(n,t.length),r})(e.content);a.length>Ml&&Dl("invalid-cell","cover payload does not fit the uniform cell");const o=(()=>{const e=new Uint8Array(I);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(xl);var l;c[0]="dummy"===(l=e.content.subtype)?1:"cancel"===l?2:"receipt"===l?3:Dl("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=Nl(e.module,e.rootSuite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+S,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)?Dl("invalid-cell","cover-cell AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{ha(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),ha(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),ha(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,d,o,c,i),n=new Uint8Array(j);return n.set(i,0),n.set(t,69),n}finally{d.fill(0),c.fill(0),a.fill(0)}},ql=e=>{const t=Tl(e.frame,"cover cell",j),n=Tl(e.binding,"edge binding",32),r=Ol(e.keyEpoch,"keyEpoch");4!==t[0]&&Dl("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)||Dl("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)&&Dl("invalid-cell","cover-cell reserved header must be zero"),o.getBigUint64(49,!1)!==r&&Dl("epoch-mismatch","cover-cell epoch is not the expected epoch"),void 0!==e.counterAbove&&(Ol(e.counterAbove,"counterAbove"),i<=e.counterAbove&&Dl("replayed-counter","cover-cell counter is not strictly newer"));const s=t.subarray(57,69),c=t.subarray(69),l=Nl(e.module,e.rootSuite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-S,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)?Dl("authentication-failed","cover-cell authentication failed"):Uint8Array.from(u)}finally{ha(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),ha(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>Ml&&Dl("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&&Dl("invalid-padding","encrypted cover padding must be all zero");return{content:(u=d[0],h=d.subarray(n,r),1===u?(0!==h.length&&Dl("invalid-cell","dummy cover cells carry no payload"),{subtype:"dummy"}):2===u?(h.length!==Rl&&Dl("invalid-cell","CANCEL payload must be one 64-byte transfer root"),{subtype:"cancel",merkleRoot:Uint8Array.from(h)}):3===u?(h.length!==2*Rl&&Dl("invalid-cell","receipt payload must be root ‖ token"),{subtype:"receipt",merkleRoot:h.slice(0,Rl),token:h.slice(Rl)}):Dl("invalid-cell","cover-cell subtype is unknown")),counter:i}}finally{l.fill(0),d?.fill(0)}var u,h},Ll={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Fl=(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 zl{#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.#U=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#_=e.amInitiator?"responder-to-initiator":"initiator-to-responder";const t={...e.schedule,phaseOffsetMs:Fl(e.policyHash,e.schedule.coverCadenceMs)},n=El(t),r=e.maxTimerDriftMs??Math.max(0,Math.min(Math.floor(n)-1,500));this.#X=(e=>new Cl(e))({schedule:t,maxTimerDriftMs:r,clock:e.clock??Ll,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!==j)return!1;const n=t.currentMessageContext();try{const t=ql({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#_,keyEpoch:n.epoch,frame:e});return!!this.#le(t.counter)&&("cancel"===t.content.subtype?this.#W.onRemoteCancel?.(Lr(t.content.merkleRoot)):"receipt"===t.content.subtype&&this.#W.onScheduledReceipt?.(Lr(t.content.merkleRoot),t.content.token),!0)}catch{return!1}}async makeDummyLaneLabel(){const e=new Uint8Array(64);return crypto.getRandomValues(e),Va(this.#W.laneLabelName,e)}#le(e){const t=this.#J;if(null!==t&&t>=zl.#Z&&e<=t-zl.#Z)return!1;if(this.#Y.has(e))return!1;if(this.#Y.add(e),(null===t||e>t)&&(this.#J=e,e>=zl.#Z)){const t=e-zl.#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,Bl({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#U,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!==j)throw new Error("coverRuntime: refusing a non-uniform cell at the lane boundary");if("open"!==n.readyState)return!1;if(n.bufferedAmount>=U)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),`${Lr(t)}~${Lr(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 jl=new WeakMap,Hl=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}},Vl=(e,t,n,r,a)=>{let o=jl.get(e);o||(o=new Map,jl.set(e,o)),o.set(r,{transferId:a,peerId:n,roomId:t})},$l=e=>{const t=e.epc.coverRuntime;if(!t)return!1;const n=Bi({runtime:t,channelMessageLabel:e.channelMessageLabel,totalChunks:e.totalChunks,sealSlotCell:e.sealSlotCell,getAckedChunks:e.getAckedChunks});return t.enqueue(n),!0},Ql=new Map,Wl=(e,t)=>{const n=Ql.get(e);n&&(n.delete(t),0===n.size&&Ql.delete(e))},Xl=(e,t)=>{e.controller.signal.aborted||e.controller.abort(t)},Gl=()=>{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},Jl=e=>/^[0-9a-f]{64}$/.test(e),Yl=(e,t=Gl())=>{if(0===e.length)throw new Error("Transfer roomId must not be empty");if(!Jl(t))throw new Error("Transfer ID must be 32-byte lowercase hex");if([...Ql.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=Ql.get(e);return r||(r=new Set,Ql.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,Wl(e,n))}}},Zl=(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&&!Jl(t.transferId))throw new Error("Transfer ID must be 32-byte lowercase hex");const n=Ql.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)Xl(e,new Error("Message transfer cancelled")),a++;return a},ed=e=>{const t=Ql.get(e);if(!t)return 0;let n=0;for(const e of t)Xl(e,new Error("Room transfers cancelled")),n++;return n},td=()=>{let e=0;for(const t of[...Ql.keys()])e+=ed(t);return e},nd=e=>{if(e?.aborted){if(e.reason instanceof Error)throw e.reason;throw new Error("Message transfer cancelled")}},rd=async(e,t)=>(nd(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),ad=e=>{e.fill(0)},od=e=>{if("string"!=typeof e||0===e.length)throw new Error("roomPinVault: room context must be a non-empty string")};const id=new class{#me=new Map;#ye;constructor(e=ad){this.#ye=e}put(e,t){od(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){od(e);const t=this.#me.get(e);return t?Uint8Array.from(t):void 0}has(e){return od(e),this.#me.has(e)}delete(e){od(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()}},sd=e=>id.delete(e),cd=()=>{id.clear()},ld=3e5,dd=new Map,ud=(e,t)=>{const n=t-ld,r=(dd.get(e)??[]).filter(e=>e>n);return 0===r.length?dd.delete(e):dd.set(e,r),r},hd=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]+ld).toISOString()}`)})(e,n);const r=await La(e,t);if(r&&r.retryAfter>n)throw new Error(`PIN retry for this peer identity is throttled until ${new Date(r.retryAfter).toISOString()}`)},fd=async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=ud(e,t);n.push(t),dd.set(e,n)})(e,n),await((e,t,n,r,a,o)=>Ea("incrementPinAttemptState",e,t,n,r,a,o))(e,t,n,3,500,3e5)},pd=(e,t)=>(void 0===t&&(e=>{dd.delete(e)})(e),((e,t)=>Ea("deletePinAttemptState",e,t))(e,t)),md=new Map,yd=(new TextEncoder).encode("p2party/room-channel/v1\0"),gd=(e,t,n)=>{const r=Fr(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(yd.length+r.length+n.length+a.length);let i=0;return o.set(yd,i),i+=yd.length,o.set(r,i),i+=r.length,o.set(n,i),i+=n.length,o.set(a,i),o},wd=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&&(y=i.publicKey,g=t.withPeerPublicKey,ba(y,g)))throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected incoming main DataChannel on the designated opener side");var y,g;if(!a&&"main"===p&&!ba(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 w="string"==typeof e?t.createDataChannel(e,{ordered:"main"===e,protocol:"raw"}):e;w.binaryType="arraybuffer";const b=w;b.withPeerId=t.withPeerId,b.roomIds=[n],"main"===b.label&&(t.mainChannel=b);const v="main"!==b.label&&void 0!==t.coverRuntime;if(v)t.coverChannels??=new Set,t.coverChannels.add(b);else if("main"!==b.label){if(t.messageChannels??=new Set,!t.messageChannels.has(b)&&t.messageChannels.size>=64)throw"closed"!==b.readyState&&b.close(),new Error("Too many message DataChannels on one peer edge");t.messageChannels.add(b)}const k=t.ratchetGateLease,I="main"===b.label?t.ratchetGateLease:void 0,S="main"===b.label?((e,t,n,r="hybrid-mlkem768",a=!1)=>{const o=ol(e,t),i=al.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 al.set(o,{lease:s,pqMode:r,expectFinish:a,channel:n,queue:[],nextStep:1,waiters:[]}),s})(n,t.withPeerId,b,s[c]?.policy.pqMode??"hybrid-mlkem768",ba(i.publicKey,t.withPeerPublicKey)):void 0;let A;try{A=await $a(p)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw t.messageChannels?.delete(b),t.mainChannel===b&&(t.mainChannel=void 0),S&&il(n,t.withPeerId,r,S),"closed"!==b.readyState&&b.close(),r}const{channelLabel:C,merkleRoot:E,merkleRootHex:P}=A;let x=!1,R=!1;const M=()=>{R||(R=!0,(e=>{if(e.released)return;e.released=!0;const t=e.pending.length;e.pending.length=0,e.seen.clear(),t>0&&Gi(e,-t)})(f),t.messageChannels?.delete(b))},K=()=>{x||(x=!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&&Wi(e,t,n,-a),r&&$i(e,r)})(l,n,t.withPeerId,u),M())};b.releaseProtocolResources=K;let U,_=!1;const D=()=>U||(_=!0,K(),U=(async()=>{await Qi(l,u),""!==P&&(await bi(t,n,P),await Ta(P))})(),U);return"main"!==b.label&&(b.cancelReceiveTransfer=D),b.onclose=async()=>{if(tt(`Channel with label ${b.label} has closed.`),v){if(t.coverChannels?.delete(b),M(),await Qi(l,u),""!==P)try{const e=await Ma(P);await vi(t,n,P,e)}catch(e){console.error(e)}K()}else if("main"===b.label){if(K(),I&&!xi(n,t.withPeerId,I))return;S&&il(n,t.withPeerId,new Error("Main data channel closed"),S),await o.dispatch(hu.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}));const e=Date.now(),r=md.get(n)??0;e-r>2e3?(md.set(n,e),o.dispatch(Me({roomId:n,connectingToPeers:!0}))):tt(`Skipping reconnection for ${n} - debounce (${String(e-r)}ms since last)`)}else{if(!r.includes(b))return;M(),await Qi(l,u);let e,a=!1;if(_)try{await U,a=!0}catch(e){console.error(e)}else if(""!==P)try{e=await Ma(P);const r="connected"===t.connectionState&&xi(n,t.withPeerId,k);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(P)&&(a=!0)}catch(e){console.error(e),a=!1}if(a)try{await D()}catch(e){console.error(e),a=!1}else{if(""!==P)try{await vi(t,n,P,e)}catch(e){console.error(e)}K()}await o.dispatch(hu.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:b.label,channel:b,alsoDeleteData:a}))}},b.onerror=async e=>{if(console.error(e),"main"===b.label){if(I&&!xi(n,t.withPeerId,I))return;await o.dispatch(hu.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}))}else{if(!r.includes(b))return K(),void("closed"!==b.readyState&&b.close());await o.dispatch(hu.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:b.label,channel:b}))}const a=Date.now(),i=md.get(n)??0;a-i>2e3?(md.set(n,a),o.dispatch(Me({roomId:n,connectingToPeers:!0}))):tt(`Skipping reconnection for ${n} - debounce (${String(a-i)}ms since last)`)},b.onmessage=async e=>{const r=new Uint8Array(e.data);if("main"!==b.label&&!Ri(n,t.withPeerId,k))return console.error("Rejected application data before peer authentication"),K(),void("closed"!==b.readyState&&b.close());const a=(e=>{const t=e.length>=1?e[0]:-1,n=3===t&&e.length!==q?-1:t;return{type:n,payload:-1===n?e.subarray(e.length):e.subarray(1)}})(r);if("main"!==b.label&&3===a.type){return void(((e,t,n)=>{if(t.released)return!1;const r=Li(e);if(t.seen.has(r))return!0;const a=Hi.get(Vi(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),Gi(t,1),t.draining||Ji(t,n),0))})(a.payload,f,async e=>{Ri(n,t.withPeerId,k)&&await no(e,b.label,b.withPeerId,n,o)})||(console.error("Closing message DataChannel: receipt queue budget exceeded"),K(),"closed"!==b.readyState&&b.close()))}if(2===a.type&&r.length===j){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=Li(e);if(n.has(p))return!0;const m=zi.get(Vi(o,i))??0;return!(t.length>=64||m+e.byteLength>16777216)&&(n.add(p),n.size>4096&&n.clear(),t.push(e),Wi(t,o,i,e.byteLength),r.value||Zi(t,n,r,a,o,i,s,c,l,d,u,h,f),!0)})(r,l,d,u,o,n,b.withPeerId,C,P,E,b,t,t.receiveMessageModule,h.signal);return void(e||(console.error("Closing message DataChannel: receive queue budget exceeded"),K(),"closed"!==b.readyState&&b.close()))}if(("main"===b.label||v)&&5===a.type&&r.length===j)return Ri(n,t.withPeerId,k)?void bl(t,n,r):void console.error("Rejected PQ control cell before peer authentication");if(4===a.type&&r.length===j&&t.coverRuntime)return Ri(n,t.withPeerId,k)?void t.coverRuntime.processInboundCoverCell(r):void console.error("Rejected cover cell before peer authentication");if("main"===b.label){const{type:e,payload:r}=a;if(1===e)return void(S&&!sl(n,t.withPeerId,r,S)&&(console.error("Closing main DataChannel: malformed or surplus handshake frame"),K(),"closed"!==b.readyState&&b.close()))}console.error(new Error("Wrong data length received"))},b.onopen=()=>{if("main"!==b.label&&!xi(n,t.withPeerId,k))return K(),void("closed"!==b.readyState&&b.close());tt(`Channel with label "${b.label}" and client ${t.withPeerId} is open.`),r.includes(b)||r.push(b),""===P&&C.length>0&&o.dispatch(Ne({roomId:n,label:p,peerId:b.withPeerId})),"main"===b.label&&(async()=>{let e,r=!1,a=!1;o.dispatch(Oe({roomId:n,peerId:t.withPeerId,status:"authenticating"}));try{if(!I||!S)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=id.get(l),!e))throw new Error("PIN room has no local PIN");r&&await hd(n,t.withPeerPublicKey);const u=ba(i.publicKey,t.withPeerPublicKey),h=Fr(i.publicKey),f=Fr(t.withPeerPublicKey),p=nl(t.localDescription?.sdp??""),m=nl(t.remoteDescription?.sdp??""),y=await Se(d.policy),g=qc({channelId:gd(d.url,b.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 cl(t,n,d.policy.authMode,d.policy.pqMode,e??null,g,t.receiveMessageModule,S,I),o.dispatch(Oe({roomId:n,peerId:t.withPeerId,status:"authenticated"})),((e,t,n)=>{e.pqHealingState||ul("cannot install an orchestrator without a PQ runtime"),yl(e);const r={roomId:t,hooks:n,now:n.now??Date.now,persistEdge:n.persistEdge??dl,interval:null,busy:!1,inboundBlocked:!1,destroyed:!1,failed:!1};ll.set(e,r);const a=n.tickMs??1e3;a>0&&(r.interval=setInterval(()=>{wl(e)},a))})(t,n,{sendControlFrame:e=>"open"===b.readyState&&(b.send(e.buffer),!0),failEdge:e=>{console.error(e),"closed"!==b.readyState&&b.close(),"closed"!==t.connectionState&&t.close()}}),(e=>{const{epc:t,roomId:n,policy:r}=e;if("scheduled"!==r.coverMode)return;Hl(t),t.coverChannels??=new Set;const a=new zl({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=jl.get(t)?.get(e);n&&Ya(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(Te({roomId:n,peerId:t.withPeerId,status:e}))},onRemoteCancel:e=>{try{Zl(n,{merkleRootHex:e})}catch(e){console.error("scheduled CANCEL abort failed",e)}}}),r&&await pd(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 fd(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 La(n,t.withPeerPublicKey);e&&e.retryAfter>Date.now()&&(s=e.retryAfter)}catch{}o.dispatch(Oe({roomId:n,peerId:t.withPeerId,status:"failed",reason:c,retryAfter:s})),I&&Mi(n,t.withPeerId,i,I),S&&il(n,t.withPeerId,i,S),console.error("protocol-v4 handshake failed:",i),"closed"!==b.readyState&&b.close(),"closed"!==t.connectionState&&t.close()}finally{e?.fill(0)}var l})(),""!==P&&"string"!=typeof e&&(async()=>{try{if(!await(async()=>!!xi(n,t.withPeerId,k)&&(await Pi(n,t.withPeerId),xi(n,t.withPeerId,k)))())return;const e=await(e=>Ea("getDBAllChunkLeafHashes",e))(P);if(0===e.length)return;let r=[];for(const{chunkIndex:t,leafHash:n}of e)if(n?.length===2*m&&(r.push(await lo(E,t,Fr(n))),32===r.length)){if(!await _i(b,r))return;r=[]}if(r.length>0&&!await _i(b,r))return;const a=await Ma(P);a&&a.totalSize>0&&a.savedSize===a.totalSize&&a.hash.length===2*m&&Ui(b,Fr(a.hash))}catch(e){console.error(e)}})()},b},bd=/(?:^|\r?\n)a=ice-ufrag:([^\r\n]+)/g,vd=/(?:^|\s)ufrag\s+([^\s]+)/i,kd=(e,t)=>{const n=(e=>{const t=new Set,n=e?.sdp;if(!n)return t;for(const e of n.matchAll(bd)){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(vd)?.[1];return n?.trim()||null})(e);return null===r||n.has(r)},Id=async(e,t)=>{if(!("closed"===e.connectionState||"closed"===e.signalingState))try{return e.restartIce(),"restarted"}catch{}return await t(),"disconnected"},Sd=(e,t,n)=>e.findIndex(e=>((e,t,n)=>e.roomId===t&&e.withPeerId===n)(e,t,n)),Ad=(e,t,n)=>{const r=Sd(e,t,n);return r<0?void 0:e[r]};class Cd{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 Ed=new Map,Pd=new Map,xd=(e,t)=>`${String(e.length)}:${e}${t}`,Rd=(e,t)=>`${String(e.length)}:${e}${t}`,Md=(e,t)=>{const n=xd(e,t);let r=Ed.get(n);return r||(r=new Cd,Ed.set(n,r)),r},Kd=(e,t)=>{const n=xd(e,t),r=Ed.get(n);r&&(async()=>{for(;;)if(await r.whenIdle(),r.isIdle())return void(Ed.get(n)===r&&Ed.delete(n))})()},Ud=async({peerId:t,peerPublicKey:n,roomId:r,peerConnections:a,rtcConfig:o},i)=>{const{keyPair:s,signalingServer:c}=i.getState();if(o??=Ce,!e.isUUID(t))throw new Error("PeerId is not a valid uuidv4");if(wa(s.publicKey,"Self Ed25519 identity"),wa(n,"Peer Ed25519 identity"),n===s.publicKey)throw new Error("Cannot connect to the same Ed25519 identity");const l=((e,t)=>{const n=Rd(e,t);let r=Pd.get(n);return r||(r=new Cd,Pd.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(hu.endpoints.disconnectFromPeer.initiate({roomId:r,peerId:t.withPeerId}));let l=Ad(a,r,t);if(l&&l.withPeerPublicKey!==n&&(await i.dispatch(hu.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=Ci(e,t),a=Ai.get(r);return a&&!a.settled&&(a.settled=!0,a.outcome="rejected",a.reject(n)),Ai.delete(r),Ei(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,ci(u,r),a.push(u);const h=()=>{if(!a.includes(u))throw new Error("WebRTC transport was replaced during initialization")},f=(async()=>{const e=Wr(),a=await ua(e);h(),u.receiveMessageModule=a,c.isConnected&&(await i.dispatch(Su.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)tt(`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(Su.endpoints.sendMessage.initiate({content:{type:"description",description:u.localDescription,fromPeerId:s.peerId,fromPeerPublicKey:s.publicKey,toPeerId:t,roomId:r,protocolVersion:4}})),tt(`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(Su.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(Su.endpoints.connectWebSocket.initiate(e.serverUrl));const n=Date.now();n-p>m&&(p=n,tt(`ICE ${u.iceConnectionState} with ${t}, restarting`),u.restartIce())}tt(`ICE candidate connection state with ${t} is ${u.iceConnectionState}.`)},u.onicegatheringstatechange=()=>{tt(`ICE gathering state with ${t} is ${u.iceGatheringState}.`)},u.onsignalingstatechange=async()=>{tt(`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&&kd(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 Id(u,()=>{}).catch(()=>{}),y&&clearTimeout(y),y=setTimeout(()=>{"disconnected"===u.connectionState&&(i.dispatch(hu.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(hu.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(Su.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(De({roomId:r,peerId:t,peerPublicKey:n})),tt(`RTC Connection status with peer ${t} is ${u.connectionState}.`))},u}finally{l.release(),((e,t)=>{const n=Rd(e,t),r=Pd.get(n);r&&r.whenIdle().then(()=>{r.isIdle()&&Pd.get(n)===r&&Pd.delete(n)})})(r,n)}},_d=async(e,t,n)=>{const r=e.createDataChannel("main",{ordered:!0,protocol:"raw"});e.mainChannel=await wd({channel:r,epc:e,roomId:e.roomId,dataChannels:t},n)},Dd=(e,t,n)=>{for(let r=e.length-1;r>=0;r--)e[r].roomId===t&&e[r].withPeerId===n&&e.splice(r,1)},Td=async({peerId:e,peerPublicKey:t,roomId:n,description:r,rtcConfig:a,peerConnections:o,iceCandidates:i,dataChannels:s},c)=>Md(n,e).runExclusive(async()=>{const{keyPair:l}=c.getState(),d=Sd(o,n,e),u=d>-1?o[d]:await Ud({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 wd({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,Dd(t,n,r)})(u.iceCandidates,i,n,e)};if(p)return m(),{data:void 0};if(h&&f)try{await u.setLocalDescription({type:"rollback"}),tt(`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===Sd(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(Su.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&&ba(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 wd({channel:e,epc:u,roomId:u.roomId,dataChannels:s},c)}return{data:void 0}}),Od=(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)))}}),Nd=async(e,t,n=!0,r=!0,a=!0)=>{if(t??=e,0===t&&e===t)return"";const o=t>e?await Od(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[Bd(0,o.length)];a(i)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}))(o,n,r,a);return i};function Bd(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 qd=(e,t)=>{const n=t._malloc(y),r=t._malloc(1+e.length),a=t._malloc(m);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,m))}finally{t._free(n),t._free(r),t._free(a)}},Ld=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)},Fd=async(e,t)=>{if(e.length%m!==0)throw new Error("Hashes were not passed");const n=e.length/m;if(0===n)throw new Error("Cannot calculate Merkle root of tree with no leaves.");if(1===n)return e;const r=t?.wasmMemory??Xr(n),a=t??await ua(r),o=a._malloc(n*m),i=new Uint8Array(r.buffer,o,n*m);i.set(e);const s=a._malloc(m),c=new Uint8Array(r.buffer,s,m),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.")}},zd=async(e,t,n,r)=>{if(e.length%m!==0)throw new Error("Hashes were not passed");const a=e.length/m;if(0===a)throw new Error("Cannot calculate Merkle proof of element of empty tree.");if(1===a){const e=new Uint8Array(m+1);if(e.set(t),r){const t=m+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??Gr(a),i=n??await ua(o),s=i._malloc(a*m),c=new Uint8Array(o.buffer,s,a*m);c.set(e);const l=i._malloc(m),d=new Uint8Array(o.buffer,l,m);d.set(t);const u=a*(m+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")}},jd=[1],Hd=(e,t=1,n=T,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>T||n<=O)throw new Error(`Chunk length needs to be between ${String(O)} and ${String(T)}`);if(!Number.isSafeInteger(e)||e<1)throw new Error("No data to split in chunks");if(e>K)throw new Error(`Message exceeds the ${String(K)} byte protocol limit`);const a=Math.ceil(n*r),o=Math.ceil(e/a);return Math.max(t,o)},Vd=async(e,t,n,r,a,o,i=1,s=T,c=.9,l=1)=>{const{keyPair:d}=t.getState();if(!jd.includes(l))throw new Error("Unknown metadata version schema.");const u=(e=>{if("string"==typeof e)return oo.Text;const t=e.name.split(".").pop()?.toLowerCase()??"";return{png:oo.ImagePNG,jpeg:oo.ImageJPEG,jpg:oo.ImageJPG,gif:oo.ImageGIF,bmp:oo.ImageBMP,tiff:oo.ImageTIFF,svg:oo.ImageSVG,webp:oo.ImageWEBP,heic:oo.ImageHEIC,pdf:oo.DocumentPDF,doc:oo.DocumentDOC,docx:oo.DocumentDOCX,xls:oo.DocumentXLS,xlsx:oo.DocumentXLSX,ppt:oo.DocumentPPT,pptx:oo.DocumentPPTX,txt:oo.DocumentTXT,rtf:oo.DocumentRTF,odt:oo.DocumentODT,mp3:oo.AudioMP3,wav:oo.AudioWAV,aac:oo.AudioAAC,flac:oo.AudioFLAC,ogg:oo.AudioOGG,m4a:oo.AudioM4A,mp4:oo.VideoMP4,avi:oo.VideoAVI,mkv:oo.VideoMKV,mov:oo.VideoMOV,wmv:oo.VideoWMV,flv:oo.VideoFLV,webm:oo.VideoWEBM,zip:oo.CompressedZIP,rar:oo.CompressedRAR,"7z":oo.Compressed7Z,tar:oo.CompressedTAR,gz:oo.CompressedGZ,html:oo.CodeHTML,css:oo.CodeCSS,js:oo.CodeJS,ts:oo.CodeTS,jsx:oo.CodeJSX,tsx:oo.CodeTSX,json:oo.CodeJSON,xml:oo.CodeXML,py:oo.CodePY,java:oo.CodeJAVA,c:oo.CodeC,cpp:oo.CodeCPP,cs:oo.CodeCS,rb:oo.CodeRB,php:oo.CodePHP,sql:oo.CodeSQL,epub:oo.EbookEPUB,mobi:oo.EbookMOBI,azw:oo.EbookAZW,ttf:oo.FontTTF,otf:oo.FontOTF,ico:oo.ImageICO,exe:oo.ExecutableEXE,dmg:oo.ExecutableDMG,apk:oo.ExecutableAPK}[t]??oo.Unknown})(e),h=u===oo.Text?await Nd(256):e.name.substring(0,255),f="string"==typeof e?(new TextEncoder).encode(e):e,p="string"==typeof e?f.length:f.size,g=Hd(p,i,s,c),w=await navigator.storage.estimate(),b=w.quota??10737418240,v=w.usage??65536,k=Math.max(0,b-v),I=((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+_+D+2048);return Number.isSafeInteger(r)?r:Number.POSITIVE_INFINITY})(p,g,s);if(I>k)throw new Error("Not enough space to stage the padded encrypted transfer in the browser.");const S=new Date;let A;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);A=new Uint8Array(e)}else A=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(y),o=t._malloc(Y),i=t._malloc(m);try{if(r(),0!==t._sha512_init(a))throw new Error("sha512_init failed");const n=new Uint8Array(t.wasmMemory.buffer,o,Y);for(let i=0;i<e.size;i+=J){r();const s=Math.min(i+J,e.size),c=new Uint8Array(await e.slice(i,s).arrayBuffer());r();for(let e=0;e<c.length;e+=Y){r();const i=Math.min(Y,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,m))}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 C=Lr(A);o.bindHash(C);const E={schemaVersion:l,messageType:u,hash:A,name:h,totalSize:p,date:S};let P=0;const x=new Uint8Array(s),R=new Uint8Array(g*m),M=Math.floor(s*(1-c)),K=Math.ceil(s*c);for(let a=0;a<g&&!o.signal.aborted;a++){window.crypto.getRandomValues(x);const i=await Od(0,M),s=p-P,c=Math.min(Math.max(s,0),K);let l=i+c;if(s>0){const t=f.slice(P,P+c);if("string"==typeof e)x.set(t,i);else{const e=await t.arrayBuffer();if(o.signal.aborted)break;x.set(new Uint8Array(e),i)}P+=c}else{const e=l+p+1,t=Number.MAX_SAFE_INTEGER-e;l+=await Od(e,t)}const y=await Ld(x),w=Lr(y);R.set(y,a*m);const b=ro({...E,chunkStartIndex:i,chunkEndIndex:l,chunkIndex:a});await Oa({transferId:o.transferId,hash:C,merkleRoot:"",chunkIndex:a,leafHash:w,receiptToken:"",data:x.slice().buffer,metadata:b.buffer,merkleProof:(new Uint8Array).buffer}),t.dispatch(qe({roomId:r.id,transferId:o.transferId,merkleRootHex:"",sha512Hex:C,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:a+1,totalChunks:g,messageType:u,filename:h,channelLabel:n,timestamp:S.getTime()}))}if(o.signal.aborted)return await Na({transferId:o.transferId}),t.dispatch(He({roomId:r.id,transferId:o.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};const U=await Fd(R,a),O=Lr(U);try{const e=so(u);for(let t=0;t<g&&!o.signal.aborted;t++){const n=await Ua(o.transferId,t);if(!n)throw new Error(`Missing staged outbound chunk ${String(t)}`);const r=ao(new Uint8Array(n.metadata)),a=r.chunkEndIndex-r.chunkStartIndex;a<=0||a>r.totalSize||await _a({merkleRoot:O,hash:C,chunkIndex:r.chunkIndex,data:n.data.slice(r.chunkStartIndex,r.chunkEndIndex),mimeType:e})}}catch(e){throw await Ta(O),e}if(o.signal.aborted)return await Na({transferId:o.transferId}),await Ta(O),t.dispatch(He({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)=>Ea("setDBRoomMessageData",e,t,n,r,a,o,i,s,c,l,d))(r.id,O,C,d.peerId,p,p,u,h,n,S.getTime(),o.transferId)}catch(e){throw await Ta(O),e}return t.dispatch(qe({roomId:r.id,transferId:o.transferId,merkleRootHex:O,sha512Hex:C,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:g,totalChunks:g,messageType:u,filename:h,channelLabel:n,timestamp:S.getTime()})),{merkleRoot:U,merkleRootHex:O,hash:A,hashHex:C,totalSize:p,totalChunks:g,messageType:u,chunkHashes:R}},$d=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},Qd=(e,t)=>`${e}\0${t}`,Wd=async e=>{let t=e.inFlight(),n=Date.now();for(;e.isOpen()&&e.inFlight()>=e.windowSize;){nd(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)),nd(e.signal)}nd(e.signal)},Xd=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f)=>{nd(u);const{merkleRootHex:p}=await $a(e.label);if(p!==Lr(i))throw new Error("Outbound channel label does not match its Merkle root");const y=f?.()??0;let g=0;const w=function(e){const t=e.slice();for(let e=t.length-1;e>0;e--){const n=Bd(0,e+1);[t[e],t[n]]=[t[n],t[e]]}return t}(Array.from({length:a},(e,t)=>t));for(let b=0;b<a;b++){nd(u);const a=w[b],v=await Ua(s,a);if(nd(u),!v)throw new Error(`Missing staged outbound chunk ${String(a)}`);const k=new Uint8Array(v.metadata),I=ao(k);if(I.chunkIndex!==a||v.chunkIndex!==a)throw new Error("Outbound chunk index does not match its staging key");const S=I.chunkEndIndex>I.chunkStartIndex&&I.chunkEndIndex-I.chunkStartIndex<=I.totalSize;if(void 0!==h&&(!S||h.has(I.chunkIndex)))continue;S&&f&&await Wd({windowSize:32,stallTimeoutMs:1e4,pollMs:25,isOpen:()=>"open"===e.readyState,inFlight:()=>g-Math.max(0,f()-y),signal:u});const A=new Uint8Array(D);if(0===v.merkleProof.byteLength){const e=await zd(o,Fr(v.leafHash),d,D);nd(u),A.set(e)}else A.set(new Uint8Array(v.merkleProof));const C=v.receiptToken.length===2*m?v.receiptToken:Lr(await lo(i,I.chunkIndex,Fr(v.leafHash)));if(nd(u),0!==v.merkleProof.byteLength&&v.merkleRoot===p&&v.receiptToken===C||await Oa({transferId:s,hash:c,merkleRoot:p,leafHash:v.leafHash,receiptToken:C,chunkIndex:a,data:v.data,metadata:v.metadata,merkleProof:A.buffer}),N!==k.length+A.length+new Uint8Array(v.data).length)throw new Error("Outbound staged chunk has invalid cell length");const E=await Br([k,A,new Uint8Array(v.data)]);for(nd(u);"open"===e.readyState&&e.bufferedAmount>=U;)await new Promise(e=>setTimeout(e,25)),nd(u);if("open"!==e.readyState){tt("Cannot send message because channel is "+e.readyState+" and bufferedAmount is "+String(e.bufferedAmount));break}let P;try{P=ei(t,n,E,i,l,r??void 0)}catch(e){throw new Error("Could not seal outbound message chunk",{cause:e})}nd(u);try{e.send(P.buffer),S&&g++}catch(t){if("open"!==e.readyState)break;throw t}}},Gd=async(e,t,n,r,a,o,i,s)=>{const c=Date.now()+i;for(;Date.now()<c;){nd(s);const i=a.find(e=>e.roomId===t&&e.withPeerId===n&&"connected"===e.connectionState);if(i)try{await Ba(Qd(t,r),n);const a=await wd({channel:r,epc:i,roomId:t,dataChannels:o},e);if(await $d(a,c-Date.now(),void 0,s))return{epc:i,channel:a};try{Jd(a)}catch(e){console.error(e)}nd(s)}catch(e){console.error(e)}else await new Promise(e=>setTimeout(e,500)),nd(s)}return null},Jd=e=>{e.releaseProtocolResources?.(),"closed"!==e.readyState&&e.close()},Yd=async(e,t)=>{if(!e.pqHealingState)return;const n=Date.now()+6e4;for(;fl(e);){if(nd(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))}},Zd=async(e,t,n,r,a=Pi,o=yi,i)=>{if(nd(i),e.epc===t)return e;if(await rd(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),nd(i)),e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),{epc:t,messageKey:s.messageKey,header:s.header,pqContext:s.pqContext}},eu=(e,t,n,r)=>"connected"===e.connectionState&&t.some(t=>t===e&&t.roomId===n&&t.withPeerId===r);class tu 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 nu=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f,p)=>{nd(p),eo(n,l,s),await Ba(Qd(n,e.label),l),nd(p);try{await rd(Pi(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 Yd(r,p);try{const e=await yi(r,n,d);p?.aborted&&(e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),nd(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 $d(w,void 0,void 0,p))throw new Error("Message DataChannel did not open before send timeout");nd(p),await Xd(w,m,y,g,a,o,i,s,c,d,u,p,void 0,()=>Ja(n,l,s));let v=0,k=0,I=!1;for(;v<5;){const e=await to(n,l,s,2e3*(v+1),p);if(nd(p),e){I=!0;break}if("closed"===w.readyState||"closing"===w.readyState){if(eu(b,h,n,l))throw new Error("Message transfer cancelled by peer");if(k>=3)break;k++;const e=await Gd(t,n,l,r,h,f,3e4,p);if(!e)break;const a=await Zd({epc:b,messageKey:m,header:y},e.epc,n,d,Pi,yi,p);b=a.epc,m=a.messageKey,y=a.header,g=a.pqContext??null,w=e.channel,v=0,t.dispatch(Fe({roomId:n,sha512Hex:c,retransmit:!0}));continue}await Xd(w,m,y,g,a,o,i,s,c,d,u,p,Ga(n,l,s),()=>Ja(n,l,s)),v++,t.dispatch(Fe({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{Jd(e())}})(()=>w,v)}finally{m.fill(0),g?.rootKey.fill(0),eo(n,l,s)}},ru=(e,t,n,r,a,o,i,s,c,l)=>async d=>{const u=await Ua(e,d);if(!u)return null;const h=new Uint8Array(u.metadata),f=ao(h),p=new Uint8Array(D);0===u.merkleProof.byteLength?p.set(await zd(n,Fr(u.leafHash),l,D)):p.set(new Uint8Array(u.merkleProof));const y=u.receiptToken.length===2*m?u.receiptToken:Lr(await lo(r,f.chunkIndex,Fr(u.leafHash)));0!==u.merkleProof.byteLength&&u.merkleRoot===a&&u.receiptToken===y||await Oa({transferId:e,hash:t,merkleRoot:a,leafHash:u.leafHash,receiptToken:y,chunkIndex:d,data:u.data,metadata:u.metadata,merkleProof:p.buffer});const g=await Br([h,p,new Uint8Array(u.data)]);return ei(o,i,g,r,c,s??void 0)},au=12e4,ou=async(e,t,n,r,a,o,i,s,c,l=1,d=T,u=.9,h=1)=>{const f=((e,t)=>{const n=[...Ql.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,Wl(e,n))}}:Yl(e,t)})(r,c);let p="",m=!1,y=!1;try{nd(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:v,merkleRootHex:k,hashHex:I,totalChunks:S,chunkHashes:A}=await Vd(e,t,n,c[g],s,f,l,d,u,h);if(f.bindMerkleRoot(k),p=k,nd(f.signal),0===v.length||0===I.length||0===S||0===A.length)return;m=!0;const C=await Va(n,k),E=c[g].channels[w].peerIds.map(e=>({peerId:e,epc:a.find(t=>t.roomId===r&&t.withPeerId===e)})),P="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 rd(Pi(e,m.peerId),u),!n.ratchetState)throw new Error("v4 scheduled send: no ratchet state");await Yd(n,u);const y=await yi(n,e,l),g=await Va(t,i),w=ru(s,c,a,o,i,y.messageKey,y.header,y.pqContext,l,d);if(!$l({epc:n,channelMessageLabel:g,totalChunks:r,sealSlotCell:w,getAckedChunks:()=>Ga(e,m.peerId,s)}))throw new Error("v4 scheduled send: edge has no cover runtime");Vl(n,e,m.peerId,i,s),p+=1,h?.();const b=await to(e,m.peerId,s,au,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,E,S,A,v,k,f.transferId,I,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*b){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)Jd(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){Jd(c),o.push({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})}}}return{outcomes:await Promise.all(o),startedTransfers:i}})(E,({epc:e})=>wd({channel:C,epc:e,roomId:r,dataChannels:o},t),({peerId:e,epc:n},c)=>nu(c,t,r,n,S,A,v,f.transferId,I,e,i,s,a,o,f.signal),f.signal,()=>{y=!0}),x={transferId:f.transferId,merkleRootHex:k,...P};nd(f.signal);const R=x.outcomes.filter(e=>"delivered"===e.status).length;if(0===x.startedTransfers)throw new tu(x,"No authenticated connected peers accepted the send");if(0===R)throw new tu(x,"Message was not delivered to any peer");return x}return}catch(e){if(((e,t,n)=>n||!e&&!t)(m,y,f.signal.aborted)&&(p.length>0&&await Ta(p),t.dispatch(He({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 Na({transferId:f.transferId}),f.finish()}},iu=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(hu.endpoints.disconnectFromPeer.initiate({peerId:e}));return e&&await Ea("deleteDB"),{data:void 0}},su=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(hu.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:e})),a.dispatch(ze({peerId:t,roomId:e}));if(t){if((await Ra()).findIndex(t=>t.roomId===e)>-1){await(e=>Ea("deleteDBUniqueRoom",e))(e);const t=await Ka(e),n=t.length;for(let r=0;r<n;r++)a.dispatch(He({roomId:e,merkleRootHex:t[r].merkleRoot}))}}return{data:void 0}},cu=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{}},lu=[],du=[],uu=[],hu=Dr({reducerPath:"webrtcApi",baseQuery:async({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:a,dataChannels:o},i)=>Md(n,e).runExclusive(async()=>{const{keyPair:s}=i.getState();if(e===s.peerId)throw new Error("Cannot create a connection with oneself.");const c=ba(s.publicKey,t);if(await xa(e))return{data:void 0};const l=Sd(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 _d(e,o,i),{data:void 0};Hl(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 Ud({peerId:e,peerPublicKey:t,roomId:n,peerConnections:a,rtcConfig:r},i);return((e,t,n)=>{e.ondatachannel=async r=>{try{const a=await wd({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 _d(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:lu,dataChannels:uu})}),setDescription:e.mutation({queryFn:(e,t,n)=>Td({...e,peerConnections:lu,iceCandidates:du,dataChannels:uu},t)}),setCandidate:e.mutation({queryFn:(e,t,n)=>(async({peerId:e,roomId:t,candidate:n,peerConnections:r,iceCandidates:a},o)=>Md(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=Sd(r,t,e);if(c>-1){const e=r[c];if(e.ignoreOffer)return{data:void 0};if(e.remoteDescription&&"stable"===e.signalingState){if(kd(s,e.remoteDescription))try{await e.addIceCandidate(s)}catch{const t=e.makingOffer||"stable"!==e.signalingState;!(i.peerId<e.withPeerId)&&t||await Id(e,async()=>{e.iceCandidates.length=0,await o.dispatch(hu.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:lu,iceCandidates:du},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 wd({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&&!ba(i.publicKey,e.withPeerPublicKey))return;const n=e.createDataChannel(t,{ordered:"main"===t,protocol:"raw"}),r=await wd({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=Ad(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:lu,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??T,f=c??.9,p="string"==typeof e?(new TextEncoder).encode(e).length:e.size,m=Hd(p,u,h,f),y=await ua(Wr()),g=await ua(Gr(m));try{return{data:await async function(){return await ou(e,d,n,r,a,o,y,g,t,u,h,f,l)}()}}catch(e){if(e instanceof tu)return{error:e};throw e}})({...e,peerConnections:lu,dataChannels:uu},t)}),disconnect:e.mutation({queryFn:(e,t,n)=>iu({...e,peerConnections:lu,dataChannels:uu},t)}),disconnectFromRoom:e.mutation({queryFn:(e,t,n)=>su({...e,peerConnections:lu,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(hu.endpoints.disconnectFromPeer.initiate(e)),a.dispatch(ze(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(He({roomId:e[r].id,merkleRootHex:e[r].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:lu,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(il(a.roomId,a.withPeerId,o),Mi(a.roomId,a.withPeerId,o),a.ratchetState&&(_o(a.ratchetState),a.ratchetState=void 0),Hl(a),Ni(a),yl(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)Dd(o,t,e),Kd(t,e);i.dispatch(ze({peerId:e,roomId:t})),i.dispatch(je({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(He({roomId:n[a].id,merkleRootHex:n[a].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:lu,dataChannels:uu,iceCandidates:du},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===m&&Ui(o[c],n),await cu(o[c]),r){const{merkleRootHex:n}=await $a(t);i.dispatch(He({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===m&&Ui(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 cu(c[h]),c.splice(h,1),await Ba(Qd(e,n),t));const{merkleRootHex:f}=await $a(n);f.length>0?a&&l.dispatch(He({roomId:e,merkleRootHex:f})):u.isConnected&&!a||l.dispatch(je({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=Sd(s,e,t);n>-1&&await l.dispatch(hu.endpoints.disconnectFromPeer.initiate({peerId:s[n].withPeerId,roomId:e}))}return{data:void 0}})({...e,peerConnections:lu,dataChannels:uu},t)})})}),fu=e=>"number"==typeof e&&Number.isInteger(e)&&4===e,pu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),mu=(e,t)=>{const n=Object.keys(e);return n.length===t.length&&n.every(e=>t.includes(e))},yu=new Map,gu=async(t,n,r)=>{try{if("PING"===t.data)return void n.send("PONG");const s=String(t.data);if(s.length>524288)return void console.error("Rejecting oversized signaling message");const c=JSON.parse(s);switch(c.type){case"ping":{const{keyPair:e}=r.getState();await r.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"pong",fromPeerId:e.peerId}}));break}case"peerId":{if(!(pu(i=c)&&mu(i,["type","peerId","challenge","protocolVersion","message"])&&"peerId"===i.type&&"string"==typeof i.peerId&&e.isUUID(i.peerId)&&"string"==typeof i.challenge&&/^[0-9a-f]{64}$/.test(i.challenge)&&"number"==typeof i.protocolVersion&&fu(i.protocolVersion)&&"string"==typeof i.message)){console.error("Rejecting malformed or incompatible auth challenge"),n.close(1002,"protocol-v4 auth required");break}const{keyPair:t}=r.getState();await(async(e,t,n,r)=>{const a=Fr(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 pa(i,a),c=[...new Uint8Array(s)].map(e=>e.toString(16).padStart(2,"0")).join("");r.dispatch(d({peerId:t,challenge:n,signature:c}))})(t,c.peerId,c.challenge,r);break}case"roomId":{if(!fu(c.protocolVersion)||!e.isUUID(c.roomId)||!/^[0-9a-f]{64}$/.test(c.roomUrl)){console.error("Rejecting incompatible or malformed room response");break}let t;c.turnCredentials&&(t={...Ce,iceServers:[...Ce.iceServers??[],{urls:c.turnCredentials.urls,username:c.turnCredentials.username,credential:c.turnCredentials.credential}]}),r.dispatch(xe({id:c.roomId,url:c.roomUrl,rtcConfig:t}));break}case"challenge":if(!(t=>{if(!pu(t))return!1;const n=Object.hasOwn(t,"username");return n===Object.hasOwn(t,"credential")&&mu(t,n?["type","challengeId","protocolVersion","username","credential"]:["type","challengeId","protocolVersion"])&&"challenge"===t.type&&"string"==typeof t.challengeId&&e.isUUID(t.challengeId)&&"number"==typeof t.protocolVersion&&fu(t.protocolVersion)&&(!n||"string"==typeof t.username&&t.username.length>0&&"string"==typeof t.credential&&t.credential.length>0)})(c)){console.error("Rejecting malformed or incompatible auth success"),n.close(1002,"protocol-v4 auth required");break}r.dispatch(u(c));break;case"peerConnection":{if(!fu(c.protocolVersion)||!e.isUUID(c.peer.id)||!ga(c.peer.publicKey))break;if(await xa(c.peer.id,c.peer.publicKey))break;const{keyPair:t,rooms:n}=r.getState(),a=n.findIndex(e=>e.id===c.roomId);if(a>-1&&n[a].onlyConnectWithKnownAddresses){if(!await Pa(c.peer.id,c.peer.publicKey))break}await r.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"peerConnection",roomId:c.roomId,fromPeerId:t.peerId,toPeerId:c.peer.id,protocolVersion:4}}));break}case"peers":{if(!fu(c.protocolVersion)||!e.isUUID(c.roomId)||!Array.isArray(c.peers)){console.error("Rejecting incompatible or malformed peer roster");break}tt("[handleWebSocketMessage] Received peers response:",{roomId:c.roomId,peersCount:c.peers.length,peers:c.peers});const{keyPair:t,rooms:n}=r.getState(),a=n.findIndex(e=>e.id===c.roomId);if(a>-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.isUUID(t.id)||!ga(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[a].peers,c.peers,t);for(const e of o)r.dispatch(De({roomId:c.roomId,...e}));const i=c.peers.length;if(0===i){const{signalingServer:n}=r.getState(),a=Date.now(),o=yu.get(c.roomId)??0;n.isConnected&&n.isVerified&&e.isUUID(t.peerId)&&a-o>5e3&&(yu.set(c.roomId,a),await r.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:t.peerId,roomId:c.roomId,protocolVersion:4}})));break}const s=n[a].onlyConnectWithKnownAddresses;for(let l=0;l<i;l++){if(c.peers[l].publicKey===t.publicKey||c.peers[l].id===t.peerId||!e.isUUID(c.peers[l].id)||!ga(c.peers[l].publicKey))continue;if(!o.some(e=>e.peerId===c.peers[l].id&&e.peerPublicKey===c.peers[l].publicKey))continue;if(!await xa(c.peers[l].id,c.peers[l].publicKey)){if(s){if(!await Pa(c.peers[l].id,c.peers[l].publicKey))continue}await r.dispatch(hu.endpoints.connectWithPeer.initiate({roomId:c.roomId,peerId:c.peers[l].id,peerPublicKey:c.peers[l].publicKey,rtcConfig:n[a].rtcConfig}))}}}break}case"description":if(!(fu(c.protocolVersion)&&e.isUUID(c.fromPeerId)&&ga(c.fromPeerPublicKey)&&e.isUUID(c.roomId)&&(o=c.description,("offer"===o.type||"answer"===o.type||"pranswer"===o.type||"rollback"===o.type)&&"string"==typeof o.sdp&&o.sdp.length<=262144))){fu(c.protocolVersion)||console.error(`Rejecting SDP from ${c.fromPeerId}: incompatible protocol version ${String(c.protocolVersion)} (expected v4). No fallback.`);break}if(!await xa(c.fromPeerId,c.fromPeerPublicKey)){const{rooms:e}=r.getState(),t=e.findIndex(e=>e.id===c.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses){if(!await Pa(c.fromPeerId,c.fromPeerPublicKey))break}await r.dispatch(hu.endpoints.setDescription.initiate({peerId:c.fromPeerId,peerPublicKey:c.fromPeerPublicKey,roomId:c.roomId,description:c.description,rtcConfig:e[t].rtcConfig}))}break;case"candidate":if(!(fu(c.protocolVersion)&&e.isUUID(c.fromPeerId)&&e.isUUID(c.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)})(c.candidate))){console.error(`Rejecting ICE from ${c.fromPeerId}: incompatible protocol version ${String(c.protocolVersion)} (expected v4). No fallback.`);break}if(!await xa(c.fromPeerId)){const{rooms:e}=r.getState(),t=e.findIndex(e=>e.id===c.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses){if(!await Pa(c.fromPeerId))break}await r.dispatch(hu.endpoints.setCandidate.initiate({peerId:c.fromPeerId,roomId:c.roomId,candidate:c.candidate}))}break;case"connection":{const{keyPair:t,rooms:n}=r.getState(),o=n.findIndex(e=>e.id===c.roomId);if(fu(c.protocolVersion)&&e.isUUID(t.peerId)&&e.isHexadecimal(t.challenge)&&e.isHexadecimal(t.signature)&&128===t.signature.length&&64===t.challenge.length&&e.isUUID(c.fromPeerId)&&ga(c.fromPeerPublicKey)&&c.fromPeerId!==t.peerId&&c.fromPeerPublicKey!==t.publicKey&&e.isUUID(c.roomId)&&o>-1&&(a=c.labels,Array.isArray(a)&&a.length<=64&&a.every(e=>"string"==typeof e&&e.length>0&&e.length<=193))){if(await xa(c.fromPeerId,c.fromPeerPublicKey))break;if(n[o].onlyConnectWithKnownAddresses){if(!await Pa(c.fromPeerId,c.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})})(c,n[o].rtcConfig,{recordPeer:e=>{r.dispatch(De(e))},recordChannel:e=>{r.dispatch(Ne(e)),tt(`Connected with ${t.peerId} on websocket channel ${e.label}`)},ensureConnection:async e=>{await r.dispatch(hu.endpoints.connectWithPeer.initiate(e))}})}else fu(c.protocolVersion)||console.error(`Rejecting peer ${c.fromPeerId}: incompatible protocol version ${String(c.protocolVersion)} (expected v4). No fallback.`);break}case"error":console.error(c);break;default:console.error("Unknown message type "+JSON.stringify(c))}}catch(e){return void console.error("[p2party] WebSocket message handling error:",e)}var a,o,i},wu=(e,t,n=10,r=20)=>{let a=0;const o=setInterval(()=>{e.readyState===WebSocket.OPEN?(clearInterval(o),t()):(a+=1,tt(`Waiting for connection... Attempt ${String(a)}`),a>=n&&(clearInterval(o),tt("WebSocket failed to connect after multiple attempts, closing..."),e.removeEventListener("message",()=>{}),e.removeEventListener("open",()=>{}),e.removeEventListener("close",()=>{}),e.close()))},r)};let bu=null;const vu=(e,t)=>(bu&&(bu.removeEventListener("message",()=>{}),bu.removeEventListener("open",()=>{}),bu.removeEventListener("close",()=>{}),bu.close(),bu=null,tt("WebSocket manually disconnected")),t.dispatch(Je.disconnect()),{data:void 0}),ku=(t,n)=>{if(bu?.readyState===WebSocket.OPEN){const{keyPair:r}=n.getState();return e.isUUID(r.peerId)&&e.isHexadecimal(r.challenge)&&e.isHexadecimal(r.signature)&&128===r.signature.length&&64===r.challenge.length&&wu(bu,()=>{bu?.send(JSON.stringify(t.content))}),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},Iu=({peerId:t,peerPublicKey:n,roomId:r},a)=>{if(bu?.readyState===WebSocket.OPEN){const{keyPair:o}=a.getState();return e.isUUID(o.peerId)&&e.isHexadecimal(o.challenge)&&e.isHexadecimal(o.signature)&&128===o.signature.length&&64===o.challenge.length&&ga(n)&&(a.dispatch(De({roomId:r,peerId:t,peerPublicKey:n})),a.dispatch(Ne({roomId:r,label:"main",peerId:t})),tt(`Connected with ${o.peerId} on channel main`),wu(bu,()=>{bu?.send(JSON.stringify({type:"connection",roomId:r,fromPeerId:o.peerId,toPeerId:t,labels:["main"],protocolVersion:4}))})),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},Su=Dr({reducerPath:"signalingServerApi",baseQuery:async({signalingServerUrl:e},t)=>{const{keyPair:n,signalingServer:r}=t.getState();if(bu||r.isConnected||r.isEstablishingConnection)return tt("WebSocket already connected"),{data:void 0};t.dispatch(Je.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 Ea("getIdentityEd25519"),l=s?Lr(new Uint8Array(s.pub)):"",d=s?new Uint8Array(s.secret):void 0,u=d?Lr(d):"";d?.fill(0);const h=/^[0-9a-f]{128}$/;if(ga(o)&&h.test(i)){if(!s||l!==o||u!==i){const e=Fr(i);await ja({pub:r(Fr(o)),secret:r(e)}),e.fill(0)}}else{if(s)o=l,i=u;else{const e=localStorage.getItem("publicKey")??"",t=localStorage.getItem("secretKey")??"";if(ga(e)&&h.test(t)){o=e,i=t;const n=Fr(i);await ja({pub:r(Fr(o)),secret:r(n)}),n.fill(0)}else{const e=await fa();o=Lr(e.publicKey),i=Lr(e.secretKey),await ja({pub:r(e.publicKey),secret:r(e.secretKey)}),e.secretKey.fill(0)}}t.dispatch(c({publicKey:o,secretKey:i}))}wa(o,"Self Ed25519 identity"),localStorage.removeItem("secretKey");const f=i.length>0?i:n.secretKey,p=o.length>0?o:n.publicKey;if(f.length>0&&p.length>0){const e=await Fa();if(!(null!=e&&await Bc(new Uint8Array(e.pub),new Uint8Array(e.crossSig),Fr(p)))){const e=await ho(),t=await Nc(e.publicKey,Fr(f));await(a={pub:r(e.publicKey),secret:r(e.secretKey),crossSig:r(t)},Ea("setIdentityX25519",a))}}const m=e+"?publickey="+o;return bu=new WebSocket(m),bu.binaryType="arraybuffer",await new Promise((e,n)=>{if(!bu)return void n(new Error("WebSocket is null"));const r=bu;try{r.onopen=()=>{tt("WebSocket connected to:",m),t.dispatch(Je.connectionEstablished()),e({data:void 0})},r.onerror=e=>{console.error("WebSocket error:",e),bu&&(bu.removeEventListener("message",()=>{}),bu.removeEventListener("open",()=>{}),bu.removeEventListener("close",()=>{}),bu.close(),bu=null),t.dispatch(Je.disconnect()),n(new Error("WebSocket connection failed"))},r.onmessage=async e=>{await gu(e,r,t)},r.onclose=()=>{bu&&(bu.removeEventListener("message",()=>{}),bu.removeEventListener("open",()=>{}),bu.removeEventListener("close",()=>{}),bu.close(),bu=null),t.dispatch(Je.disconnect()),tt("WebSocket disconnected"),e({data:void 0})}}catch(e){n(e instanceof Error?e:new Error(String(e)))}return()=>{bu&&(tt("Cleaning up WebSocket connection..."),bu.removeEventListener("message",()=>{}),bu.removeEventListener("open",()=>{}),bu.removeEventListener("close",()=>{}),bu.close(),bu=null)}})}catch(e){return bu&&(bu.removeEventListener("message",()=>{}),bu.removeEventListener("open",()=>{}),bu.removeEventListener("close",()=>{}),bu.close(),bu=null),t.dispatch(Je.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:vu}),sendMessage:e.mutation({queryFn:ku}),connectWithPeer:e.mutation({queryFn:Iu})})}),Au=new Map,Cu=t.createListenerMiddleware();Cu.startListening({matcher:t.isAnyOf(Me,xe,qe,He,Ve),effect:async(t,n)=>{try{if(Me.match(t)){const{roomId:r,connectingToPeers:a}=t.payload;if(tt("[roomListenerMiddleware] setConnectingToPeers:",{roomId:r,connectingToPeers:a}),a){const{signalingServer:t,keyPair:a,rooms:o}=n.getState(),i=o.findIndex(e=>e.id===r);if(tt("[roomListenerMiddleware] setConnectingToPeers check:",{isConnected:t.isConnected,peerId:a.peerId,isPeerIdUUID:e.isUUID(a.peerId),roomIndex:i,roomId:i>-1?o[i].id:"N/A"}),t.isConnected&&t.isVerified&&e.isUUID(a.peerId)&&i>-1&&e.isUUID(o[i].id)){const e=Date.now();e-(Au.get(r)??0)<2e3?tt("[roomListenerMiddleware] Skipping peers request - debounced"):(Au.set(r,e),tt("[roomListenerMiddleware] Sending peers request from setConnectingToPeers"),await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:a.peerId,roomId:r,protocolVersion:4}})))}n.dispatch(Me({roomId:r,connectingToPeers:!1}))}}else if(xe.match(t)){const{signalingServer:i,keyPair:s,rooms:c}=n.getState(),{url:l,id:d,onlyConnectWithKnownPeers:u}=t.payload;if(tt("[roomListenerMiddleware] setRoom:",{url:l,id:d,onlyConnectWithKnownPeers:u}),64===l.length&&null!=u&&localStorage.setItem(l+"-onlyConnectWithKnownPeers",String(u)),64===l.length&&e.isUUID(d)){tt("[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=be(c[t].policy).slice().buffer;await(r=l,a=d,o=u,Ea("setDBUniqueRoom",r,a,o));const h=await Ka(d),f=h.length;for(let e=0;e<f;e++)n.dispatch(qe({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}));tt("[roomListenerMiddleware] Checking peers request conditions:",{isConnected:i.isConnected,isPeerIdUUID:e.isUUID(s.peerId),peerId:s.peerId,roomIndex:t,roomId:t>-1?c[t].id:"N/A"}),i.isConnected&&i.isVerified&&e.isUUID(s.peerId)&&t>-1&&e.isUUID(c[t].id)&&(tt("[roomListenerMiddleware] Sending peers request for room:",c[t].id),await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:s.peerId,roomId:c[t].id,protocolVersion:4}})))}}else if(qe.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 Va(s[l].messages[t].channelLabel,s[l].messages[t].merkleRootHex),o=Fr(a);await n.dispatch(hu.endpoints.disconnectFromChannelLabel.initiate({roomId:e,label:r,messageHash:o,alsoDeleteData:!1,alsoSendFinishedMessage:!0}))}}}else if(He.match(t)){const{merkleRootHex:e,hashHex:n}=t.payload;if(!e&&!n)return;if(e&&e.length!==2*m)return;if(n&&n.length!==2*m)return;e?(await Ta(e),await Na({merkleRootHex:e})):n&&await Na({hashHex:n})}else if(Ve.match(t)){const e=t.payload;await n.dispatch(hu.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:!0}))}}catch(e){console.error("p2party: room listener effect failed",e)}var r,a,o}});const Eu=t.createListenerMiddleware();Eu.startListening({matcher:t.isAnyOf(c,l,d,u,h),effect:async(t,n)=>{if(c.match(t)){const{publicKey:e,secretKey:n}=t.payload;64===e.length&&128===n.length&&(localStorage.setItem("publicKey",t.payload.publicKey),localStorage.removeItem("secretKey"))}else if(l.match(t)){const{peerId:r,challenge:a,signature:o,challengeId:i,username:s,credential:c}=t.payload;if(e.isUUID(r)&&e.isUUID(i)&&e.isHexadecimal(a)&&e.isHexadecimal(o)&&64===a.length&&128===o.length){n.dispatch(Je.connectionVerified()),localStorage.setItem("peerId",r),localStorage.setItem("challenge",a),localStorage.setItem("signature",o),localStorage.setItem("challengeId",i);const{keyPair:l,rooms:d,commonState:u}=n.getState(),h=64===u.currentRoomUrl.length?d.findIndex(e=>e.url===u.currentRoomUrl):-1;h>-1?(t.payload.username&&t.payload.credential&&n.dispatch(Be({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:s,credential:c}]})),e.isUUID(d[h].id)&&n.dispatch(Me({roomId:d[h].id,connectingToPeers:!0}))):e.isUUID(l.peerId)&&64===u.currentRoomUrl.length&&await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:l.peerId,roomUrl:u.currentRoomUrl,protocolVersion:4}}))}}else if(d.match(t)){const{peerId:r,challenge:a,signature:o}=t.payload;e.isUUID(r)&&e.isHexadecimal(a)&&e.isHexadecimal(o)&&64===a.length&&128===o.length&&(localStorage.setItem("peerId",r),localStorage.setItem("challenge",a),localStorage.setItem("signature",o),await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"challenge",fromPeerId:r,challenge:a,signature:o,protocolVersion:4}})))}else if(u.match(t)){const{challengeId:r}=t.payload;if(e.isUUID(r)){n.dispatch(Je.connectionVerified()),localStorage.setItem("challengeId",r);const{keyPair:a,rooms:o,commonState:i}=n.getState(),s=64===i.currentRoomUrl.length?o.findIndex(e=>e.url===i.currentRoomUrl):-1;s>-1?(t.payload.username&&t.payload.credential&&n.dispatch(Be({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:t.payload.username,credential:t.payload.credential}]})),e.isUUID(o[s].id)?n.dispatch(Me({roomId:o[s].id,connectingToPeers:!0})):e.isUUID(a.peerId)&&64===i.currentRoomUrl.length&&await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:a.peerId,roomUrl:i.currentRoomUrl,protocolVersion:4}}))):e.isUUID(a.peerId)&&64===i.currentRoomUrl.length&&await n.dispatch(Su.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:a.peerId,roomUrl:i.currentRoomUrl,protocolVersion:4}}))}}else h.match(t)&&(console.trace("[keyPairListenerMiddleware] resetIdentity dispatched"),localStorage.setItem("peerId",""),localStorage.setItem("challengeId",""),localStorage.setItem("publicKey",""),localStorage.removeItem("secretKey"),localStorage.setItem("challenge",""),localStorage.setItem("signature",""))}});const Pu=t.configureStore({reducer:{commonState:o,keyPair:f,rooms:Qe,signalingServer:Ye,[Su.reducerPath]:Su.reducer,[hu.reducerPath]:hu.reducer},middleware:e=>e({serializableCheck:{ignoredPaths:[`${hu.reducerPath}.mutations`,`${hu.reducerPath}.queries`,`${Su.reducerPath}.mutations`,`${Su.reducerPath}.queries`],ignoredActionPaths:["payload","error","meta.arg.originalArgs","meta.baseQueryMeta"]}}).concat([Su.middleware,hu.middleware,Cu.middleware,Eu.middleware])}),xu=Pu.dispatch,Ru=new Uint8Array([80,50,80,83,69,83,83,0]),Mu=262144,Ku=Ru.length+4+24+32+32+32+2,Uu="p2party-session",_u=e=>Uint8Array.from(e);function Du(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 Tu=(e,t)=>{if(!Number.isSafeInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new RangeError(`${t} must be a non-negative safe integer`)},Ou=(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},Nu=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Bu=async e=>new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",e.slice().buffer)),qu=async e=>{const t=new WebAssembly.Memory({initial:32,maximum:32});return e?.wasmBinary?await na({wasmBinary:(n=e.wasmBinary,n instanceof Uint8Array?n.slice().buffer:n.slice(0)),wasmMemory:t,getRandomValue:aa}):await ua(t);var n},Lu=async(e={})=>{const t=await qu(e);let n=null,r=null,a=null;try{if(e.ed25519KeyPair)Du(e.ed25519KeyPair.publicKey,"ed25519KeyPair.publicKey",b),Du(e.ed25519KeyPair.secretKey,"ed25519KeyPair.secretKey",v),n=_u(e.ed25519KeyPair.publicKey),r=_u(e.ed25519KeyPair.secretKey);else{const e=await fa(t);n=e.publicKey,r=e.secretKey}const o=await ho(t);a=o.secretKey;const i=await Nc(o.publicKey,r,t);if(!await Bc(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)}},Fu=(e,t)=>e.N===t.N&&e.PN===t.PN&&Ou(e.dhPub,t.dhPub);class zu{protocolVersion=4;#e;#ge=new Cd;#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 te(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){Du(e,"plaintext");const t=_u(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/T)),a=[],o=[];try{for(let t=0;t<r;t++){const r=t*T,o=Math.min(T,Math.max(0,n-r)),i=globalThis.crypto.getRandomValues(new Uint8Array(T));i.set(e.subarray(r,r+o),0),a.push(i)}const i=await Bu(e),s=new Uint8Array(r*m);for(let e=0;e<a.length;e++)s.set(qd(a[e],t),e*m);const c=Uint8Array.from(await Fd(s,t));for(let e=0;e<a.length;e++){const r=await zd(s,qd(a[e],t),t,D),c=Math.min(T,Math.max(0,n-e*T)),l=ro({schemaVersion:1,messageType:oo.Unknown,hash:i,totalSize:n,date:new Date(0),name:Uu,chunkStartIndex:0,chunkEndIndex:c,chunkIndex:e}),d=new Uint8Array(N);d.set(l,0),d.set(r,_),d.set(a[e],_+D),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=Uo(this.#be);const i=Ao(n,this.#e);r=i.messageKey,a=this.#ve.currentMessageContext();const s=e.plaintexts.map(t=>ei(r,i.header,t,e.root,this.#e,a));return Do(this.#be,n),this.#ve.noteApplicationMessage(),o=!0,{protocolVersion:4,root:_u(e.root),frames:s}}finally{t.fill(0),r?.fill(0),n&&!o&&_o(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(Du(e.root,"message.root",m),!Array.isArray(e.frames)||0===e.frames.length)throw new Error("session: encrypted message has no frames");for(const t of e.frames)if(Du(t,"message frame"),t.length!==j)throw new Error("session: invalid encrypted frame length");const t=_u(e.root),n=e.frames.map(_u);return this.#ge.runExclusive(async()=>{this.#j();const e=n.map(e=>qo(e));for(let t=1;t<e.length;t++)if(!Fu(e[0].header,e[t].header))throw new Error("session: mixed ratchet headers");const r=new Set;for(const t of e){const e=Nu(t.nonce);if(r.has(e))throw new Error("session: duplicate chunk nonce");r.add(e)}const a=Uo(this.#be),o=new Map(this.#ve.activeReceiveKeys),i=[];let s=!1;try{const e=[];for(const r of n){const n=ti(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=ao(n.decrypted.subarray(0,_));e.push({metadata:s,chunk:n.decrypted.subarray(_+D)})}const r=await(async e=>{if(0===e.length)throw new Error("session: encrypted message has no frames");const t=e[0].metadata;Tu(t.totalSize,"metadata.totalSize");const n=Math.max(1,Math.ceil(t.totalSize/T));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(Tu(e.chunkIndex,"metadata.chunkIndex"),Tu(e.chunkStartIndex,"metadata.chunkStartIndex"),Tu(e.chunkEndIndex,"metadata.chunkEndIndex"),Tu(e.totalSize,"metadata.totalSize"),1!==e.schemaVersion||e.messageType!==oo.Unknown||e.name!==Uu||0!==e.date.getTime())throw new Error("session: unsupported encrypted metadata");if(e.totalSize!==t.totalSize||!Ou(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(T,Math.max(0,t.totalSize-e.chunkIndex*T));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*T)}const o=await Bu(a),i=Ou(o,t.hash);if(o.fill(0),!i)throw a.fill(0),new Error("session: plaintext hash mismatch");return a})(e);return Do(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);_o(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 ju;const e=await this.#ve.prepareHealingOffer();return this.#ve.markPendingDispatched(),{frame:e,requiresPersistBeforeSend:!0}})}async acceptControlFrame(e){Du(e,"control frame",j);const t=_u(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(),Vu(this.#be,this.#ve,this.#we)))}async destroy(){await this.#ge.runExclusive(async()=>{this.#p||(_o(this.#be),this.#ve.destroy(),this.#p=!0)})}}const ju={frame:null,requiresPersistBeforeSend:!1},Hu=(e,t,n)=>(Tu(n,"snapshot counter"),e.setBigUint64(t,BigInt(n),!1),t+8),Vu=(e,t,n)=>{(e=>{if(Du(e.rootKey,"snapshot.rootKey",32),Du(e.dhSelfPub,"snapshot.dhSelfPub",32),Du(e.dhSelfSec,"snapshot.dhSelfSec",32),e.sendingChainKey&&Du(e.sendingChainKey,"snapshot.sendingChainKey",32),e.receivingChainKey&&Du(e.receivingChainKey,"snapshot.receivingChainKey",32),e.dhRemotePub&&Du(e.dhRemotePub,"snapshot.dhRemotePub",32),Tu(e.Ns,"snapshot.Ns"),Tu(e.Nr,"snapshot.Nr"),Tu(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>G)throw new Error("snapshot: too many skipped message keys")})(e);const r=Mo(e),a=t.serialize();if(0===a.length||a.length>Mu)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(Ku+32*t+72*r.skippedMessageKeys.length+4+a.length),i=new DataView(o.buffer);let s=0;o.set(Ru,s),s+=Ru.length,o[s++]=4,o[s++]=4,o[s++]=e,o[s++]=(e=>{if(e===$)return 3;if(e===V)return 4;if(e===Q)return 5;throw new Error("snapshot: unsupported root suite")})(r.rootSuite),s=Hu(i,s,r.Ns),s=Hu(i,s,r.Nr),s=Hu(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)Du(new Uint8Array(e.dhPub),"snapshot.skipped.dhPub",32),Du(new Uint8Array(e.messageKey),"snapshot.skipped.messageKey",32),o.set(new Uint8Array(e.dhPub),s),s+=32,s=Hu(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)}},$u=e=>{Du(e,"snapshot");const t=_u(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(!Ou(o(Ru.length),Ru))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 $;if(4===e)return V;if(5===e)return Q;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>G)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=`${Nu(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>Mu)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 A=Ko({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:A,pqCheckpoint:S,amInitiator:!!(8&e)}}finally{if(t.fill(0),!r)for(const e of a)e.fill(0)}},Qu=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");Du(e.ed25519PublicKey,"identity.ed25519PublicKey",b),Du(e.x25519PublicKey,"identity.x25519PublicKey",x),Du(e.x25519SecretKey,"identity.x25519SecretKey",R),Du(e.x25519CrossSignature,"identity.x25519CrossSignature",g)})(e.identity),Du(e.peerIdentityEd25519PublicKey,"peerIdentityEd25519PublicKey",b),!e.channel||"object"!=typeof e.channel)throw new TypeError("channel binding is required");if(Du(e.channel.channelId,"channel.channelId"),0===e.channel.channelId.length)throw new RangeError("channel.channelId must not be empty");Du(e.channel.localFingerprint,"channel.localFingerprint",32),Du(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(Du(t.pin,"pin"),0===t.pin.length)throw new RangeError("pin must not be empty");a=_u(t.pin)}else if(void 0!==t.pin)throw new Error("pin must not be provided in nopin mode");const o=_u(e.identity.x25519SecretKey),i=_u(e.identity.ed25519PublicKey),s=_u(e.identity.x25519PublicKey),c=_u(e.identity.x25519CrossSignature),l=_u(e.peerIdentityEd25519PublicKey),d=_u(e.channel.channelId),u=_u(e.channel.localFingerprint),h=_u(e.channel.remoteFingerprint);let f=null,p=null,m=null,y=null,w=null;try{const t=await qu(e.crypto);await(async(e,t)=>{const n=new Uint8Array(x);n[0]=9;const r=fo(e.x25519SecretKey,n,t);try{if(!Ou(r,e.x25519PublicKey))throw new Error("identity X25519 public and secret keys do not match")}finally{r.fill(0)}if(!await Bc(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 g="initiator"===e.role,b=qc({channelId:d,ikInitiator:g?i:l,ikResponder:g?l:i,fpInitiator:g?u:h,fpResponder:g?h:u,pqMode:r}),v=await el(e.transport,{mode:n,pqMode:r,pin:a,channelInput:b,amInitiator:g,idSelfSec:o,selfIdentityX25519Pub:s,selfIdentityCrossSignature:c,peerIdentityEd25519Pub:l},t);y=v.state,f=v.secret,p=v.pqHealing.rootKey,m=v.pqHealing.binding,w=new Ac({module:t,pqMode:r,rootSuite:y.rootSuite,binding:m,rootKey:p,nextOfferer:v.pqHealing.nextOfferer,amInitiator:g});const k=new zu(y,t,w,g);return y=null,w=null,k}finally{o.fill(0),a?.fill(0),f?.fill(0),p?.fill(0),m?.fill(0),y&&_o(y),w?.destroy()}},Wu=async(e,t)=>{const n=$u(e);let r=null;try{const e=await qu(t),a=Ac.readCheckpointBinding(n.pqCheckpoint);try{r=Ac.restore(n.pqCheckpoint,{module:e,pqMode:te(n.state.rootSuite),rootSuite:n.state.rootSuite,binding:a,amInitiator:n.amInitiator})}finally{a.fill(0)}const o=new zu(n.state,e,r,n.amInitiator);return r=null,o}catch(e){throw _o(n.state),r?.destroy(),e}finally{n.pqCheckpoint.fill(0)}};var Xu=["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 Gu=e=>e.normalize("NFKD"),Ju=async e=>{try{return await(async e=>{const t=Gu(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=Xu.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}},Yu=32,Zu=`v${String(1)}.`,eh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",th=/^[0-9a-fA-F]{64}$/u,nh=/^[A-Za-z0-9_-]{43}$/u,rh=(new TextEncoder).encode("p2party/room-invite/checksum/v1\0");if(2048!==Xu.length||2048!==new Set(Xu).size)throw new Error("Room invite word list must contain 2,048 unique words");const ah=new Map(Xu.map((e,t)=>[e,t])),oh=e=>{if(!(e instanceof Uint8Array))throw new TypeError("Room capability must be a Uint8Array");if(e.length!==Yu)throw new Error("Room capability must be exactly 32 bytes");return e},ih=()=>globalThis.crypto.getRandomValues(new Uint8Array(Yu)),sh=e=>{const t=oh(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+=eh[a>>>18&63],n+=eh[a>>>12&63],r>1&&(n+=eh[a>>>6&63]),r>2&&(n+=eh[63&a])}return n},ch=e=>{if("string"!=typeof e||!nh.test(e))throw new Error("Room capability must be exactly 43 unpadded base64url characters");if(3&eh.indexOf(e.at(-1)??""))throw new Error("Room capability base64url encoding is not canonical");const t=new Uint8Array(Yu);let n=0,r=0,a=0;for(const o of e)for(n=n<<6|eh.indexOf(o),r+=6;r>=8;)r-=8,t[a]=n>>>r&255,a+=1,n&=(1<<r)-1;if(a!==Yu||sh(t)!==e)throw new Error("Room capability base64url encoding is not canonical");return t},lh=e=>{if("string"!=typeof e)throw new TypeError("Room capability must be a string");return e.startsWith(Zu)||e.startsWith(`#${Zu}`)?hh(e):64===e.length?(e=>{if(!th.test(e))throw new Error("Room capability hex must contain exactly 64 hex digits");const t=new Uint8Array(Yu);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(2*n,2*n+2),16);return t})(e):ch(e)},dh=e=>(e=>{let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t})(lh(e)),uh=e=>`${Zu}${sh(e)}`,hh=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(Zu))throw new Error("Unsupported room invite version");return ch(t.slice(Zu.length))},fh=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})(rh,e));return new Uint8Array(t)[0]},ph=async(t,n="wss://signaling.p2party.com/ws",r={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},o={})=>{if(t=dh(t),null===o||"object"!=typeof o||Array.isArray(o))throw new Error("Invalid room connection options");const{keyPair:i,signalingServer:s,rooms:c,commonState:l}=Pu.getState(),d=c.findIndex(e=>e.url===t);let u;if(-1===d){const e=(await Ra()).find(e=>e.roomUrl===t);e?.roomPolicy&&(u=ve(new Uint8Array(e.roomPolicy)))}if(u&&o.policy&&!Ie(u,o.policy))throw new Error("Persisted room policy is immutable");const h=ke(o.policy??(d>-1?c[d].policy:u??Ae));if("legacy-signaling"!==h.rendezvousMode)throw new Error("Private rendezvous room connections are not wired yet");if("pin"===h.authMode){if(void 0!==o.pin){f=t,p=o.pin,id.put(f,p);const e=d>-1?c[d].id:"";e&&await pd(e)}else if(!(e=>id.has(e))(t))throw new Error("PIN room connection requires a PIN")}else{if(void 0!==o.pin)throw new Error("PIN must not be provided for a no-PIN room");sd(t)}var f,p;xu(-1===d?xe({url:t,id:"",rtcConfig:r,policy:h}):Re({roomContext:t,policy:h})),l.currentRoomUrl!==t&&xu(a(t)),s.isConnected&&s.isVerified&&e.isUUID(i.peerId)?-1===d?await xu(Su.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:i.peerId,roomUrl:t,protocolVersion:4}})):xu(Me({roomId:c[d].id,connectingToPeers:!0})):await xu(Su.endpoints.connectWebSocket.initiate(n))},mh=3e4,yh=async(e,t={})=>{const n=dh(e),{timeoutMs:r=mh,signal:a}=t,o=()=>{const e=$e(Pu.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=Pu.subscribe(d),d()})},gh=async(e,t,n,r={})=>{const{timeoutMs:a,signal:o,...i}=r;return await ph(e,t,n,i),await yh(e,{timeoutMs:a,signal:o})},wh=async(e,t={})=>{const{count:n=1,timeoutMs:r=mh,signal:a}=t,o=()=>{const t=$e(Pu.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=Pu.subscribe(u),u()})},bh=(e,t)=>{const n=new Set,r=()=>{const r=$e(Pu.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),vh(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=Pu.subscribe(r);return r(),a},vh=async(e,t,n=!0)=>{if(!e&&!t)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"txt",category:io.Text};try{const{keyPair:r,rooms:a}=Pu.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:io.Text};const c=a[i].messages[s].messageType,l=so(c),d=(e=>{switch(e){case oo.ImagePNG:return"png";case oo.ImageJPEG:return"jpeg";case oo.ImageJPG:return"jpg";case oo.ImageGIF:return"gif";case oo.ImageBMP:return"bmp";case oo.ImageTIFF:return"tiff";case oo.ImageSVG:return"svg";case oo.ImageWEBP:return"webp";case oo.ImageHEIC:return"heic";case oo.DocumentPDF:return"pdf";case oo.DocumentDOC:return"doc";case oo.DocumentDOCX:return"docx";case oo.DocumentXLS:return"xls";case oo.DocumentXLSX:return"xlsx";case oo.DocumentPPT:return"ppt";case oo.DocumentPPTX:return"pptx";case oo.DocumentTXT:return"txt";case oo.DocumentRTF:return"rtf";case oo.DocumentODT:return"odt";case oo.AudioMP3:return"mp3";case oo.AudioWAV:return"wav";case oo.AudioAAC:return"aac";case oo.AudioFLAC:return"flac";case oo.AudioOGG:return"ogg";case oo.AudioM4A:return"m4a";case oo.VideoMP4:return"mp4";case oo.VideoAVI:return"avi";case oo.VideoMKV:return"mkv";case oo.VideoMOV:return"mov";case oo.VideoWMV:return"wmv";case oo.VideoFLV:return"flv";case oo.VideoWEBM:return"webm";case oo.CompressedZIP:return"zip";case oo.CompressedRAR:return"rar";case oo.Compressed7Z:return"7z";case oo.CompressedTAR:return"tar";case oo.CompressedGZ:return"gz";case oo.CodeHTML:return"html";case oo.CodeCSS:return"css";case oo.CodeJS:return"js";case oo.CodeTS:return"ts";case oo.CodeJSX:return"jsx";case oo.CodeTSX:return"tsx";case oo.CodeJSON:return"json";case oo.CodeXML:return"xml";case oo.CodePY:return"py";case oo.CodeJAVA:return"java";case oo.CodeC:return"c";case oo.CodeCPP:return"cpp";case oo.CodeCS:return"cs";case oo.CodeRB:return"rb";case oo.CodePHP:return"php";case oo.CodeSQL:return"sql";case oo.EbookEPUB:return"epub";case oo.EbookMOBI:return"mobi";case oo.EbookAZW:return"azw";case oo.FontTTF:return"ttf";case oo.FontOTF:return"otf";case oo.ImageICO:return"ico";case oo.ExecutableEXE:return"exe";case oo.ExecutableDMG:return"dmg";case oo.ExecutableAPK:return"apk";default:return""}})(c),u=(e=>{switch(e){case oo.Text:return io.Text;case oo.ImagePNG:case oo.ImageJPEG:case oo.ImageJPG:case oo.ImageGIF:case oo.ImageBMP:case oo.ImageTIFF:case oo.ImageSVG:case oo.ImageWEBP:case oo.ImageHEIC:case oo.ImageICO:return io.Image;case oo.DocumentPDF:case oo.DocumentDOC:case oo.DocumentDOCX:case oo.DocumentXLS:case oo.DocumentXLSX:case oo.DocumentPPT:case oo.DocumentPPTX:case oo.DocumentTXT:case oo.DocumentRTF:case oo.DocumentODT:return io.Document;case oo.AudioMP3:case oo.AudioWAV:case oo.AudioAAC:case oo.AudioFLAC:case oo.AudioOGG:case oo.AudioM4A:return io.Audio;case oo.VideoMP4:case oo.VideoAVI:case oo.VideoMKV:case oo.VideoMOV:case oo.VideoWMV:case oo.VideoFLV:case oo.VideoWEBM:return io.Video;case oo.CompressedZIP:case oo.CompressedRAR:case oo.Compressed7Z:case oo.CompressedTAR:case oo.CompressedGZ:return io.Compressed;case oo.CodeHTML:case oo.CodeCSS:case oo.CodeJS:case oo.CodeJSX:case oo.CodeTS:case oo.CodeTSX:case oo.CodeJSON:case oo.CodeXML:case oo.CodePY:case oo.CodeJAVA:case oo.CodeC:case oo.CodeCPP:case oo.CodeCS:case oo.CodeRB:case oo.CodePHP:case oo.CodeSQL:return io.Code;case oo.EbookEPUB:case oo.EbookMOBI:case oo.EbookAZW:return io.Ebook;case oo.FontTTF:case oo.FontOTF:return io.Font;case oo.ExecutableEXE:case oo.ExecutableDMG:case oo.ExecutableAPK:return io.Executable;default:return io.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!==oo.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!==oo.Text&&100===h){const e=a[i].messages[s].filename,t=a[i].messages[s].fromPeerId===r.peerId?await((e,t,n,r)=>Ea("assembleToOPFS",e,t,n,r))(a[i].messages[s].merkleRootHex,a[i].messages[s].totalSize,e,l):await((e,t,n,r)=>Ea("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)=>Ea("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===oo.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:io.Text}}},kh=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*m)throw new Error("Invalid Merkle root length");if(n&&"string"!=typeof n&&n.length!==m)throw new Error("Invalid Merkle root length");if(r&&"string"==typeof r&&r.length!==2*m)throw new Error("Invalid hash length");if(r&&"string"!=typeof r&&r.length!==m)throw new Error("Invalid hash length");const o=n&&"string"==typeof n?n:n&&"string"!=typeof n?Lr(n):"",i=r&&"string"==typeof r?r:r&&"string"!=typeof r?Lr(r):"";Zl(e,{transferId:a,merkleRootHex:o||void 0,hashHex:i||void 0});const{rooms:s}=Pu.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*m){const n=await Va(t,s[c].messages[l].merkleRootHex);await Pu.dispatch(hu.endpoints.disconnectFromChannelLabel.initiate({roomId:s[c].id,label:n,alsoDeleteData:!0})),Pu.dispatch(He({roomId:e,merkleRootHex:s[c].messages[l].merkleRootHex}))}},Ih={store:Pu,commonStateSelector:e=>e.commonState,signalingServerSelector:e=>e.signalingServer,roomSelector:$e,keyPairSelector:e=>e.keyPair,connect:ph,connectToSignalingServer:async(e,t="wss://signaling.p2party.com/ws")=>{e=dh(e);const{signalingServer:n,rooms:r,commonState:o}=Pu.getState();-1===r.findIndex(t=>t.url===e)&&xu(xe({url:e,id:""})),o.currentRoomUrl!==e&&xu(a(e)),n.serverUrl===t&&(n.isConnected||n.isEstablishingConnection)||await xu(Su.endpoints.connectWebSocket.initiate(t))},disconnectFromSignalingServer:async()=>{await xu(Su.endpoints.disconnectWebSocket.initiate(void 0))},disconnectFromRoom:async(e,t=!1)=>{await xu(hu.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:t}))},disconnectFromAllRooms:async(e=!1,t=[])=>{await xu(hu.endpoints.disconnectFromAllRooms.initiate({deleteMessages:e,exceptionRoomIds:t}))},disconnectFromPeer:async e=>{await xu(hu.endpoints.disconnectFromPeer.initiate({peerId:e}))},allowConnectionRelay:(e,t=!0)=>{const{rooms:n}=Pu.getState(),r=n.findIndex(t=>t.id===e);r>-1&&xu(Ue({roomId:n[r].id,canBeConnectionRelay:t}))},onlyAllowConnectionsFromAddressBook:async(e,t)=>{let n;try{n=dh(e)}catch{return}e=n;const{rooms:r}=Pu.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 Pa(r[a].peers[t].peerId,r[a].peers[t].peerPublicKey)||await xu(hu.endpoints.disconnectFromPeer.initiate({peerId:r[a].peers[t].peerId,roomId:r[a].id,alsoDeleteData:!1}))}}xu(xe({url:a>-1?r[a].url:e,id:a>-1?r[a].id:"",onlyConnectWithKnownPeers:t}))},addPeerToAddressBook:(e,t,n)=>Ea("setDBAddressBookEntry",e,t,n),getPeerAddressBookEntry:Pa,getAllPeersInAddressBook:()=>Ea("getAllDBAddressBookEntries"),getAllPeersInBlacklist:()=>Ea("getAllDBBlacklisted"),deletePeerFromAddressBook:async(t,n,r)=>{const a=await((e,t,n)=>Ea("deleteDBAddressBookEntry",e,t,n))(t,n,r);e.isUUID(a)&&await xu(hu.endpoints.disconnectFromPeer.initiate({peerId:a,alsoDeleteData:!1}))},blacklistPeer:async(e,t)=>{await((e,t)=>Ea("setDBPeerInBlacklist",e,t))(e,t),await xu(hu.endpoints.disconnectFromPeer.initiate({peerId:e,alsoDeleteData:!0}))},getPeerIsBlacklisted:xa,removePeerFromBlacklist:(e,t)=>Ea("deleteDBPeerFromBlacklist",e,t),getAllExistingRooms:Ra,getRoomStats:e=>Ea("getDBRoomStats",e),sendMessage:(e,t,n,r=.9,a=3,o=T,i=1,s=Gl())=>{if(!/^[0-9a-f]{64}$/.test(s))throw new Error("Invalid transfer ID");const c=Yl(n,s),l=xu(hu.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:()=>kh(n,t,void 0,void 0,s)}},readMessage:vh,getTransferAcks:(e,t)=>{const n=`${e}\0`,r=`\0${t}`,a=[];for(const[e,t]of Qa)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=>Ea("getDBAllNewChunksCount",e),cancelMessage:kh,createTransferId:Gl,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*m)throw new Error("Invalid Merkle root length");if(t&&"string"!=typeof t&&t.length!==m)throw new Error("Invalid Merkle root length");if(n&&"string"==typeof n&&n.length!==2*m)throw new Error("Invalid hash length");if(n&&"string"!=typeof n&&n.length!==m)throw new Error("Invalid hash length");const r=t&&"string"==typeof t?t:t&&"string"!=typeof t?Lr(t):"",a=n&&"string"==typeof n?n:n&&"string"!=typeof n?Lr(n):"";Zl(e,{merkleRootHex:r||void 0,hashHex:a||void 0});const{rooms:o}=Pu.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*m){const t=await Va(o[i].messages[s].channelLabel,o[i].messages[s].merkleRootHex);await Pu.dispatch(hu.endpoints.disconnectFromChannelLabel.initiate({roomId:o[i].id,label:t,alsoDeleteData:!0})),Pu.dispatch(He({roomId:e,merkleRootHex:o[i].messages[s].merkleRootHex}))}},purgeIdentity:async()=>{td(),cd(),xu(h()),await za(),await Ha();const{rooms:e}=Pu.getState(),t=e.length;for(let n=0;n<t;n++)await xu(hu.endpoints.disconnectFromRoom.initiate({roomId:e[n].id}));await xu(Su.endpoints.disconnectWebSocket.initiate(void 0))},purgeRoom:async e=>{e=dh(e),sd(e);const{rooms:t}=Pu.getState(),n=t.findIndex(t=>t.url===e);n>-1&&(ed(t[n].id),t[n].id&&await pd(t[n].id),xu(Ve(t[n].id))),await xu(Su.endpoints.disconnectWebSocket.initiate(void 0))},purge:async()=>{td(),cd(),xu(h()),await za(),await Ha(),await xu(Su.endpoints.disconnectWebSocket.initiate(void 0));const e=await Ra(),t=e.length;for(let n=0;n<t;n++)xu(Ve(e[n].roomId))},generateRandomRoomUrl:async()=>sh(ih()),generateRoomInvite:()=>uh(ih()),generateRoomCapability:ih,encodeRoomCapabilityBase64Url:sh,decodeRoomCapabilityBase64Url:ch,decodeRoomCapability:lh,normalizeRoomCapability:dh,encodeRoomInviteFragment:uh,decodeRoomInviteFragment:hh,encodeRoomCapabilityWords:async e=>{const t=oh(e),n=new Uint8Array(33);n.set(t),n[32]=await fh(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=>Xu[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=ah.get(e);if(void 0===t)throw new Error(`Unknown room invite word: ${e}`);return t})),a=r.slice(0,Yu),o=await fh(a);if(r[32]!==o)throw new Error("Room invite checksum is invalid");return a},ROOM_INVITE_WORDLIST_ID:"p2party-invite-en-v1",sign:pa,verify:ma,createSession:Qu,restoreSession:Wu,generateSessionIdentity:Lu,setWasmSourceUrl:da,DEFAULT_ROOM_POLICY_V1:Ae,encodeRoomPolicyV1:be,decodeRoomPolicyV1:ve,hashRoomPolicyV1:Se,roomPoliciesEqualV1:Ie,generateKeyPair:fa,newKeyPair:fa,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 Xu[t]}).join(" ")},keyPairFromMnemonic:async(e,t)=>{if(!await Ju(e))throw new Error("Invalid mnemonic.");const n=new Uint8Array(A),r=new TextEncoder;r.encodeInto("password12345678",n);const a=new Uint8Array(A);if(t){const e=r.encode(t),n=await window.crypto.subtle.digest("SHA-512",e);a.set(new Uint8Array(n).slice(m-A,m))}else a.set(n);const o=await(async(e,t,n)=>{const r=Gu(e),a=(new TextEncoder).encode(r).buffer,o=new Int8Array(a),i=o.length;t=t??window.crypto.getRandomValues(new Uint8Array(A));const s=n?.wasmMemory??Jr(i),c=(n=n??await ua(s))._malloc(w),l=new Uint8Array(s.buffer,c,w),d=n._malloc(i*Uint8Array.BYTES_PER_ELEMENT),u=new Int8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT),h=n._malloc(A),f=new Uint8Array(s.buffer,h,A);try{if(oa(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{ha(n,l),ha(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=Vr(),n=await ua(t),r=n._malloc(b),a=new Uint8Array(t.buffer,r,b),o=n._malloc(v),i=new Uint8Array(t.buffer,o,v),s=n._malloc(w),c=new Uint8Array(t.buffer,s,w);c.set(e);const l=n._keypair_from_seed(a.byteOffset,i.byteOffset,c.byteOffset);if(ha(n,c),0===l){const e={publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(i)};return n._free(r),ha(n,i),e}throw n._free(r),ha(n,i),new Error("An unexpected error occured.")})(o)},MIN_CHUNKS:1,MIN_CHUNK_SIZE:O+1,MAX_CHUNK_SIZE:T,WIRE_CHUNK_FRAME_LEN:j,MIN_COVER_CADENCE_MS:ne,MAX_COVER_CADENCE_MS:re,MAX_COVER_LANES:16,MAX_COVER_FRAMES_PER_CELL:ae,MIN_COVER_SLOT_MS:25,validateRoomPolicyV1:we,MessageDeliveryError:tu,joinRoom:gh,waitForRoom:yh,waitForPeers:wh,onMessage:bh,setDebugLogging:et,MIN_PERCENTAGE_FILLED_CHUNK:.1,MAX_PERCENTAGE_FILLED_CHUNK:.99,ROOM_URL_LENGTH:64,MessageType:oo,MessageCategory:io,VERSION:n};"undefined"!=typeof window&&(window.p2party=Ih),exports.DEFAULT_ROOM_POLICY_V1=Ae,exports.MAX_COVER_CADENCE_MS=re,exports.MAX_COVER_FRAMES_PER_CELL=ae,exports.MAX_COVER_LANES=16,exports.MIN_COVER_CADENCE_MS=ne,exports.MIN_COVER_SLOT_MS=25,exports.MessageDeliveryError=tu,exports.WIRE_CHUNK_FRAME_LEN=j,exports.canonicalizeRoomPolicyV1=ke,exports.createSession=Qu,exports.decodeRoomPolicyV1=ve,exports.default=Ih,exports.encodeRoomPolicyV1=be,exports.generateSessionIdentity=Lu,exports.hashRoomPolicyV1=Se,exports.joinRoom=gh,exports.onMessage=bh,exports.p2party=Ih,exports.restoreSession=Wu,exports.roomPoliciesEqualV1=Ie,exports.setDebugLogging=et,exports.setWasmSourceUrl=da,exports.validateRoomPolicyV1=we,exports.waitForPeers=wh,exports.waitForRoom=yh;
|