p2party 0.14.2 → 0.14.7
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 +230 -30
- package/docs/getting-started.md +15 -0
- package/docs/protocol-v4-security.md +40 -0
- package/docs/references.md +28 -8
- package/docs/session-api.md +10 -2
- package/lib/api/signalingServerApi.d.ts +13 -2
- package/lib/api/webrtc/applyIceConfiguration.d.ts +9 -0
- package/lib/api/webrtc/dataChannelHandler.d.ts +10 -0
- package/lib/api/webrtc/deleteRoomData.d.ts +13 -0
- package/lib/api/webrtc/disconnectFromAllRoomsQuery.d.ts +2 -1
- package/lib/api/webrtc/disconnectFromRoomQuery.d.ts +2 -1
- package/lib/api/webrtc/disconnectQuery.d.ts +2 -1
- package/lib/api/webrtc/iceRepair.d.ts +3 -1
- package/lib/api/webrtc/index.d.ts +2 -1
- package/lib/api/webrtc/interfaces.d.ts +37 -0
- package/lib/api/webrtc/negotiationLock.d.ts +24 -0
- package/lib/api/webrtc/pendingOffer.d.ts +29 -0
- package/lib/api/webrtc/rebindDeadline.d.ts +61 -0
- package/lib/api/webrtc/remoteTransportChange.d.ts +142 -0
- package/lib/api/webrtc/retiredRemoteTransports.d.ts +70 -0
- package/lib/api/webrtc/roomEdgeBudget.d.ts +10 -0
- package/lib/api/webrtc/setDescriptionQuery.d.ts +8 -1
- package/lib/api/webrtc/settleOnClose.d.ts +36 -0
- package/lib/blindRendezvous/admissionInput.d.ts +11 -0
- package/lib/blindRendezvous/admissionPolicy.d.ts +217 -0
- package/lib/blindRendezvous/canonicalSchema.d.ts +139 -0
- package/lib/blindRendezvous/carrierEnvelope.d.ts +105 -0
- package/lib/blindRendezvous/coreReduce.d.ts +199 -0
- package/lib/blindRendezvous/derivations.d.ts +381 -0
- package/lib/blindRendezvous/identityHelloAdmission.d.ts +89 -0
- package/lib/blindRendezvous/identityHelloAdmissionPersistence.d.ts +133 -0
- package/lib/blindRendezvous/identityHelloHistoricalEvidence.d.ts +52 -0
- package/lib/blindRendezvous/identityHelloOpen.d.ts +167 -0
- package/lib/blindRendezvous/identityHelloTrial.d.ts +271 -0
- package/lib/blindRendezvous/localAdmissibleProject.d.ts +101 -0
- package/lib/blindRendezvous/localPresenceKeyBinding.d.ts +108 -0
- package/lib/blindRendezvous/localStableIdentityCustody.d.ts +46 -0
- package/lib/blindRendezvous/normativeKernel.d.ts +222 -0
- package/lib/blindRendezvous/operation.d.ts +137 -0
- package/lib/blindRendezvous/operationPayload.d.ts +134 -0
- package/lib/blindRendezvous/pairBootstrapSuite.d.ts +93 -0
- package/lib/blindRendezvous/pairCrypto.d.ts +122 -0
- package/lib/blindRendezvous/pairLedger.d.ts +154 -0
- package/lib/blindRendezvous/pairOpenBudget.d.ts +67 -0
- package/lib/blindRendezvous/pairOpenReservation.d.ts +157 -0
- package/lib/blindRendezvous/pairPlaintext.d.ts +240 -0
- package/lib/blindRendezvous/pairStepEnvelope.d.ts +60 -0
- package/lib/blindRendezvous/plannerState.d.ts +61 -0
- package/lib/blindRendezvous/projections.d.ts +71 -0
- package/lib/blindRendezvous/publicWindow.d.ts +330 -0
- package/lib/blindRendezvous/retainedOperationStore.d.ts +187 -0
- package/lib/blindRendezvous/roomInviteV2.d.ts +92 -0
- package/lib/blindRendezvous/roomPolicyV4.d.ts +90 -0
- package/lib/blindRendezvous/schemas.d.ts +221 -0
- package/lib/blindRendezvous/storeDescriptor.d.ts +160 -0
- package/lib/cryptography/aeadWasm.d.ts +18 -0
- package/lib/cryptography/byteInput.d.ts +12 -0
- package/lib/cryptography/carrierAead.d.ts +23 -0
- package/lib/cryptography/chacha20poly1305.d.ts +7 -0
- package/lib/cryptography/fips202.d.ts +10 -0
- package/lib/cryptography/hpke.d.ts +84 -0
- package/lib/cryptography/hpkeSuite.d.ts +39 -0
- package/lib/cryptography/hybridKem.d.ts +42 -0
- package/lib/cryptography/hybridKemSuite.d.ts +22 -0
- package/lib/cryptography/interfaces.d.ts +3 -0
- package/lib/cryptography/mlkem.d.ts +27 -1
- package/lib/cryptography/mnemonic.d.ts +65 -1
- package/lib/cryptography/ownedEd25519KeyMaterial.d.ts +27 -0
- package/lib/cryptography/webCryptoSha256.d.ts +20 -0
- package/lib/cryptography/x25519.d.ts +18 -0
- package/lib/cryptography/xchacha20poly1305.d.ts +7 -0
- package/lib/db/api.d.ts +6 -3
- package/lib/db/identityEd25519ClientBoundary.d.ts +13 -0
- package/lib/db/src/getDB.d.ts +2 -2
- package/lib/db/types.d.ts +52 -4
- package/lib/db.worker.js +1 -1
- package/lib/handlers/coverChannelRegistry.d.ts +22 -0
- package/lib/handlers/edgeTeardownFollowUp.d.ts +35 -0
- package/lib/handlers/handleChallenge.d.ts +2 -1
- package/lib/handlers/handleConnectToPeer.d.ts +1 -1
- package/lib/handlers/handleHandshake.d.ts +2 -6
- package/lib/handlers/handleSendMessage.d.ts +60 -7
- package/lib/handlers/handleWebSocketMessage.d.ts +1 -1
- package/lib/handlers/handshakeCore.d.ts +2 -7
- package/lib/handlers/handshakeFrame.d.ts +25 -0
- package/lib/handlers/ratchetGateWait.d.ts +13 -0
- package/lib/handlers/reconcile.d.ts +24 -0
- package/lib/handlers/requestRoom.d.ts +30 -0
- package/lib/handlers/roomResponse.d.ts +53 -0
- package/lib/index.d.ts +99 -12
- package/lib/index.js +1 -1
- package/lib/index.min.js +1 -1
- package/lib/index.mjs +1 -1
- package/lib/libcrypto.provenance.json +5 -5
- package/lib/libcrypto.wasm +0 -0
- package/lib/middleware/roomListenerMiddleware.d.ts +4 -1
- package/lib/reducers/commonSlice.d.ts +3 -2
- package/lib/reducers/keyPairSlice.d.ts +3 -6
- package/lib/reducers/roomSlice.d.ts +81 -5
- package/lib/reducers/signalingServerSlice.d.ts +3 -2
- package/lib/session.d.ts +6 -3
- package/lib/session.js +1 -1
- package/lib/session.mjs +1 -1
- package/lib/store.d.ts +4 -2
- package/lib/utils/constants.d.ts +12 -0
- package/lib/utils/correlationId.d.ts +4 -0
- package/lib/utils/identityRestore.d.ts +108 -0
- package/lib/utils/interfaces.d.ts +25 -6
- package/lib/utils/roomConnectAdmission.d.ts +15 -0
- package/lib/utils/roomLeaveCoordinator.d.ts +38 -0
- package/lib/utils/roomRequestCoordinator.d.ts +104 -0
- package/lib/utils/roomRosterReconciler.d.ts +83 -0
- package/lib/utils/sdpFingerprint.d.ts +6 -0
- package/lib/utils/signalingAttemptLifecycle.d.ts +33 -0
- package/lib/utils/signalingAuth.d.ts +21 -2
- package/lib/utils/signalingBounds.d.ts +6 -0
- package/lib/utils/signalingFrame.d.ts +21 -0
- package/lib/utils/signalingHeartbeatWatchdog.d.ts +45 -0
- package/lib/utils/signalingIngressQueue.d.ts +49 -0
- package/lib/utils/signalingPeerRequestDebouncer.d.ts +13 -0
- package/lib/utils/signalingRoomLifecycle.d.ts +7 -0
- package/lib/utils/signalingRoomOperationLifecycle.d.ts +14 -0
- package/lib/utils/signalingServerBoundary.d.ts +11 -0
- package/lib/utils/terminalSettlement.d.ts +53 -0
- package/lib/utils/transportIdentity.d.ts +5 -0
- 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.7";const r=t.createSlice({name:"commonState",initialState:{currentRoomUrl:""},reducers:{setCurrentRoomUrl:(e,t)=>{e.currentRoomUrl=t.payload}}}),{setCurrentRoomUrl:o}=r.actions;var a=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:o,signature:a,challengeId:i}=n.payload;e.isUUID(r,4)&&e.isUUID(i)&&e.isHexadecimal(o)&&e.isHexadecimal(a)&&64===o.length&&128===a.length&&(t.peerId=r,t.challenge=o,t.signature=a,t.challengeId=i)},setPeerData:(t,n)=>{const{peerId:r,challenge:o,signature:a}=n.payload;e.isUUID(r,4)&&e.isHexadecimal(o)&&e.isHexadecimal(a)&&64===o.length&&128===a.length&&(t.peerId=r,t.challenge=o,t.signature=a)},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,f=e=>e.keyPair;var m=s.reducer;const p=64*Uint8Array.BYTES_PER_ELEMENT,y=64*Uint8Array.BYTES_PER_ELEMENT,g=208,w=64*Uint8Array.BYTES_PER_ELEMENT,b=32*Uint8Array.BYTES_PER_ELEMENT,v=32*Uint8Array.BYTES_PER_ELEMENT,k=64*Uint8Array.BYTES_PER_ELEMENT,I=32*Uint8Array.BYTES_PER_ELEMENT,S=12*Uint8Array.BYTES_PER_ELEMENT,C=16*Uint8Array.BYTES_PER_ELEMENT,A=16*Uint8Array.BYTES_PER_ELEMENT,E=32*Uint8Array.BYTES_PER_ELEMENT,P=64*Uint8Array.BYTES_PER_ELEMENT,x=32*Uint8Array.BYTES_PER_ELEMENT,R=32*Uint8Array.BYTES_PER_ELEMENT,M=32*Uint8Array.BYTES_PER_ELEMENT,K=256,U=65536,_=10737418240,D=1048576,T=9+y+8+8+256+8+8+8,L=4+48*(y+1),q=65405-(T+L),O=U-q,N=65405,B=y,F=1+B,j=new Uint8Array([1]),z=32,$=12,H=65474+C,V=(new TextEncoder).encode("p2party-x25519-idsig-v1"),W="hybrid-3dh-mlkem512-cpace21-v4",Q="hybrid-3dh-mlkem768-cpace21-v4",G="hybrid-3dh-mlkem1024-cpace21-v4",X=[W,Q,G],J=Q,Y=2e3,Z=1048576,ee=65536,te=[5e3,1e4,2e4,4e4,6e4],ne=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")},re=e=>{if("hybrid-mlkem512"===e)return W;if("hybrid-mlkem768"===e)return Q;if("hybrid-mlkem1024"===e)return G;throw new Error("roomPolicy: unsupported PQ mode")},oe=e=>{if(e===W)return"hybrid-mlkem512";if(e===Q)return"hybrid-mlkem768";if(e===G)return"hybrid-mlkem1024";throw new Error("roomPolicy: unsupported ratchet root suite")},ae=1e3,ie=36e5,se=1024,ce=new Uint8Array([80,50,82,80]),le=(new TextEncoder).encode("p2party/room-policy/v1\0"),de=new Set(["version","revision","wireVersion","authMode","pqMode","rendezvousMode","coverMode","coverCadenceMs","coverLanes","coverFramesPerCell","coverDurationEpochs"]),ue={nopin:0,pin:1},he={"hybrid-mlkem768":1,"hybrid-mlkem512":2,"hybrid-mlkem1024":3},fe={"legacy-signaling":0,"opaque-token":1,"blind-meeting-point":2},me={immediate:0,scheduled:1},pe=e=>{if(0===e)return"nopin";if(1===e)return"pin";throw new Error("roomPolicy: unsupported auth mode")},ye=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")},ge=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")},we=e=>{if(0===e)return"immediate";if(1===e)return"scheduled";throw new Error("roomPolicy: unsupported cover mode")},be=(e,t,n)=>{if(!Number.isSafeInteger(t)||t<0||t>n)throw new Error(`roomPolicy: ${e} is out of range`)};function ve(e,t,n){if("string"!=typeof t||!Object.hasOwn(n,t))throw new Error(`roomPolicy: unsupported ${e}`)}const ke=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!==de.size||n.some(e=>"string"!=typeof e||!de.has(e)))throw new Error("roomPolicy: policy has missing or unexpected fields (PIN bytes are never policy fields)");for(const t of de){const n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n||!("value"in n)||!n.enumerable)throw new Error("roomPolicy: policy fields must be enumerable data properties")}})(e),1!==e.version)throw new Error("roomPolicy: unsupported policy version");if(4!==e.wireVersion)throw new Error("roomPolicy: unsupported wire version");if(be("revision",e.revision,4294967295),ve("auth mode",e.authMode,ue),ve("PQ mode",e.pqMode,he),ve("rendezvous mode",e.rendezvousMode,fe),ve("cover mode",e.coverMode,me),be("cover cadence",e.coverCadenceMs,4294967295),be("cover lanes",e.coverLanes,65535),be("cover frames per cell",e.coverFramesPerCell,65535),be("cover duration epochs",e.coverDurationEpochs,65535),"immediate"!==e.coverMode){if(e.coverCadenceMs<ae||e.coverCadenceMs>ie)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>se)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")},Ie=e=>{ke(e);const t=new Uint8Array(32);t.set(ce,0),t[4]=1,t[5]=e.wireVersion,t[6]=ue[e.authMode],t[7]=he[e.pqMode],t[8]=fe[e.rendezvousMode],t[9]=me[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},Se=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<ce.length;t++)if(e[t]!==ce[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:pe(e[6]),pqMode:ye(e[7]),rendezvousMode:ge(e[8]),coverMode:we(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 ke(n),n},Ce=e=>Se(Ie(e)),Ae=(e,t)=>{const n=Ie(e),r=Ie(t);let o=0;for(let e=0;e<n.length;e++)o|=n[e]^r[e];return 0===o},Ee=async e=>{const t=Ie(e),n=new Uint8Array(le.length+t.length);n.set(le,0),n.set(t,le.length);const r=await globalThis.crypto.subtle.digest("SHA-256",n);return new Uint8Array(r)},Pe=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}),xe=524288,Re=64,Me=e=>(e=>Array.isArray(e)&&e.length<=64&&e.every(e=>"string"==typeof e&&e.length>0&&e.length<=193))(e)&&1===e.length&&"main"===e[0],Ke={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},Ue=e=>Array.isArray(e.urls)?[...e.urls]:[e.urls],_e=e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls}),De=e=>({...e,iceServers:e.iceServers?.map(_e),certificates:e.certificates?[...e.certificates]:e.certificates}),Te=(e,t)=>{if(e.bundlePolicy!==t.bundlePolicy||e.iceCandidatePoolSize!==t.iceCandidatePoolSize||e.iceTransportPolicy!==t.iceTransportPolicy||e.rtcpMuxPolicy!==t.rtcpMuxPolicy)return!1;const n=e.certificates??[],r=t.certificates??[];if(n.length!==r.length||n.some((e,t)=>e!==r[t]))return!1;const o=e.iceServers??[],a=t.iceServers??[];return o.length===a.length&&o.every((e,t)=>{const n=a[t];if(e.username!==n.username||e.credential!==n.credential)return!1;return((e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]))(Ue(e),Ue(n))})},Le=(e,t)=>{let n=(e??[]).map(_e);for(const e of t){const t=new Set(Ue(e)),r=[];for(const e of n){const n=Ue(e).filter(e=>!t.has(e));0!==n.length&&r.push({...e,urls:Array.isArray(e.urls)?n:n[0]})}r.push(_e(e)),n=r}return n},qe=(e,t)=>{const n=De(e);if(!t)return n;const r={urls:Array.isArray(t.urls)?[...t.urls]:t.urls,username:t.username,credential:t.credential};return n.iceServers=Le(n.iceServers,[r]),n},Oe=e=>De(e??Ke),Ne=(e,t)=>{e.callerRtcConfig=De(t),e.rtcConfig=qe(e.callerRtcConfig,e.signalingTurnCredentials)},Be=(e,t)=>{const n=Ce(t);if(!Ae(e,n))throw new Error("roomSlice: room policy is immutable after creation")},Fe=(e,t)=>{if((-1===t||!1===e[t].signalingActive)&&e.filter(e=>!1!==e.signalingActive).length>=K)throw new Error(`roomSlice: cannot activate more than ${String(K)} rooms`)},je=(e,{roomId:t,transferId:n,merkleRootHex:r,hashHex:o})=>{if(!n&&!r&&!o)return;if(n&&!/^[0-9a-f]{64}$/.test(n))return;if(r&&r.length!==2*y)return;if(o&&o.length!==2*y)return;const a=e.findIndex(e=>e.id===t);if(-1!==a)if(n){const t=e[a].messages.findIndex(e=>e.transferId===n);t>-1&&e[a].messages.splice(t,1)}else if(r){const t=e[a].messages.findIndex(e=>e.merkleRootHex===r);t>-1&&e[a].messages.splice(t,1)}else if(o){const t=e[a].messages.findLastIndex(e=>e.sha512Hex===o);t>-1&&e[a].messages.splice(t,1)}},ze=t.createSlice({name:"rooms",initialState:[],reducers:{setRoom:(t,n)=>{const{url:r,id:o,canBeConnectionRelay:a,rtcConfig:i,onlyConnectWithKnownPeers:s,policy:c}=n.payload;if(/^[0-9a-f]{64}$/.test(r)&&e.isUUID(o)){const e=t.findIndex(e=>e.url===r);if(t.findIndex(e=>e.url!==r&&e.id===o)>-1)return;if(Fe(t,e),e>-1)t[e].callerRtcConfig??=De(t[e].rtcConfig??Ke),t[e].signalingTurnCredentials??=null,t[e].roomResponseGeneration??=0,c&&Be(t[e].policy,c),t[e].url=r,t[e].id=o,t[e].signalingActive=!0,null!=a&&(t[e].canBeConnectionRelay=a),i&&Ne(t[e],i),t[e].onlyConnectWithKnownAddresses=null!=s?s:"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers");else{const e=Oe(i);t.push({url:r,id:o,connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:a??!0,onlyConnectWithKnownAddresses:s??"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers"),callerRtcConfig:e,signalingTurnCredentials:null,rtcConfig:qe(e,null),roomResponseGeneration:0,signalingActive:!0,policy:Ce(c??Pe),peers:[],channels:[],messages:[]})}}else if(/^[0-9a-f]{64}$/.test(r)){const e=t.findIndex(e=>e.url===r);if(Fe(t,e),e>-1)t[e].callerRtcConfig??=De(t[e].rtcConfig??Ke),t[e].signalingTurnCredentials??=null,t[e].roomResponseGeneration??=0,c&&Be(t[e].policy,c),t[e].url=r,t[e].id="",t[e].signalingActive=!0,null!=a&&(t[e].canBeConnectionRelay=a),i&&Ne(t[e],i),t[e].onlyConnectWithKnownAddresses=null!=s?s:"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers");else{const e=Oe(i);t.push({url:r,id:"",connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:a??!0,onlyConnectWithKnownAddresses:s??"true"===localStorage.getItem(r+"-onlyConnectWithKnownPeers"),callerRtcConfig:e,signalingTurnCredentials:null,rtcConfig:qe(e,null),roomResponseGeneration:0,signalingActive:!0,policy:Ce(c??Pe),peers:[],channels:[],messages:[]})}}},applyRoomResponse:(t,n)=>{const{roomUrl:r,roomId:o,roomRequestId:a,requestGeneration:i,turnCredentials:s}=n.payload;if(!/^[0-9a-f]{64}$/.test(r)||!e.isUUID(o)||!e.isUUID(a,4)||!Number.isSafeInteger(i)||i<=0)return;const c=t.findIndex(e=>e.url===r);if(-1===c)return;const l=t[c];!1===l.signalingActive||i<=(l.roomResponseGeneration??0)||e.isUUID(l.id)&&l.id!==o||t.some((e,t)=>t!==c&&e.id===o)||(l.id=o,l.signalingTurnCredentials=s?{...s,urls:Array.isArray(s.urls)?[...s.urls]:s.urls}:null,l.rtcConfig=qe(l.callerRtcConfig,l.signalingTurnCredentials),l.roomResponseGeneration=i)},rollbackRoomResponse:(e,t)=>{const n=e.find(e=>e.url===t.payload.roomUrl);if(!n||n.id!==t.payload.failedRoomId||n.roomResponseGeneration!==t.payload.failedRequestGeneration)return;n.id=t.payload.previousRoomId,n.roomResponseGeneration=t.payload.previousRequestGeneration,n.signalingActive=t.payload.previousSignalingActive;const r=t.payload.previousTurnCredentials;n.signalingTurnCredentials=r?{...r,urls:[...r.urls]}:null,n.rtcConfig=qe(n.callerRtcConfig,n.signalingTurnCredentials)},expireRoomTurnCredentials:(e,t)=>{const n=e.find(e=>e.url===t.payload.roomUrl);n&&n.roomResponseGeneration===t.payload.requestGeneration&&n.signalingTurnCredentials?.expiresAtUnixSeconds===t.payload.expiresAtUnixSeconds&&(n.signalingTurnCredentials=null,n.rtcConfig=qe(n.callerRtcConfig,null))},setRoomPolicy:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload.roomContext||e.id===t.payload.roomContext);n>-1&&Be(e[n].policy,t.payload.policy)},setConnectingToPeers:(e,t)=>{const{roomId:n,connectingToPeers:r}=t.payload,o=e.findIndex(e=>e.id===n);o>-1&&(e[o].connectingToPeers=r)},setConnectedToPeers:(e,t)=>{const{roomId:n,connectedToPeers:r}=t.payload,o=e.findIndex(e=>e.id===n);o>-1&&(e[o].connectingToPeers=!1,e[o].connectedToPeers=r)},setConnectionRelay:(e,t)=>{const{roomId:n,canBeConnectionRelay:r}=t.payload,o=e.findIndex(e=>e.id===n);o>-1&&(e[o].canBeConnectionRelay=r)},setPeer:(e,t)=>{const{roomId:n,peerId:r,peerPublicKey:o}=t.payload,a=e.findIndex(e=>e.id===n);if(a>-1){-1===e[a].peers.findIndex(e=>e.peerId===r||e.peerPublicKey===o)&&e[a].peers.length<Re&&e[a].peers.push({peerId:r,peerPublicKey:o})}},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 o=e[r].coverStatusByPeer;o&&delete o[t.payload.peerId];const a=e[r].handshakeStatusByPeer;a&&"failed"!==a[t.payload.peerId]?.status&&delete a[t.payload.peerId]}},setPeerCoverStatus:(e,t)=>{const{roomId:n,peerId:r,status:o}=t.payload,a=e.findIndex(e=>e.id===n);if(a>-1){const t=e[a];t.callerRtcConfig??=De(t.rtcConfig??Ke),t.coverStatusByPeer??={},t.coverStatusByPeer[r]=o}},setPeerHandshakeStatus:(e,t)=>{const{roomId:n,peerId:r,status:o,reason:a,retryAfter:i,peerPublicKey:s}=t.payload,c=e.findIndex(e=>e.id===n);if(c>-1){const t=e[c];t.handshakeStatusByPeer??={},t.handshakeStatusByPeer[r]={status:o,reason:a,retryAfter:i,peerPublicKey:s}}},setChannel:(e,t)=>{const{roomId:n,label:r,peerId:o}=t.payload;if(0===r.length||r.length>193)return;const a=e.findIndex(e=>e.id===n);if(a>-1){const t=e[a].channels.findIndex(e=>e.label===r);if(t>-1){-1===e[a].channels[t].peerIds.findIndex(e=>e===o)&&e[a].channels[t].peerIds.length<Re&&e[a].channels[t].peerIds.push(o)}else e[a].channels.length<4096&&e[a].channels.push({label:r,peerIds:[o]})}},deleteChannel:(e,t)=>{const{roomId:n,peerId:r,label:o}=t.payload,a=e.length;for(let t=0;t<a;t++)if(void 0===n||e[t].id===n)if(o&&!r){const n=e[t].channels.findIndex(e=>e.label===o);n>-1&&e[t].channels.splice(n,1)}else if(!o&&r)for(let n=e[t].channels.length-1;n>=0;n--){const o=e[t].channels[n].peerIds.findIndex(e=>e===r);o>-1&&(e[t].channels[n].peerIds.splice(o,1),0===e[t].channels[n].peerIds.length&&e[t].channels.splice(n,1))}else if(r&&o){const n=e[t].channels.findIndex(e=>e.label===o&&e.peerIds.includes(r));if(n>-1){const o=e[t].channels[n].peerIds.findIndex(e=>e===r);e[t].channels[n].peerIds.splice(o,1),0===e[t].channels[n].peerIds.length&&e[t].channels.splice(n,1)}}},setIceServers:(e,t)=>{const{roomId:n,iceServers:r}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){const t=e[o];t.callerRtcConfig.iceServers=Le(t.callerRtcConfig.iceServers,r),t.rtcConfig=qe(t.callerRtcConfig,t.signalingTurnCredentials)}},setMessage:(t,n)=>{const{roomId:r,transferId:o,merkleRootHex:a,sha512Hex:i,filename:s,channelLabel:c,fromPeerId:l,messageType:d,chunkSize:u,totalSize:h,chunksCreated:f,totalChunks:m,timestamp:p}=n.payload,g=t.findIndex(e=>e.id===r);if(g>-1){const n=t[g].messages.findLastIndex(e=>(void 0!==o?e.transferId===o:e.merkleRootHex===a)||void 0===o&&e.sha512Hex===i&&0===e.merkleRootHex.length);-1===n?c&&l&&e.isUUID(l)&&d&&h&&t[g].messages.push({transferId:o,merkleRootHex:a,sha512Hex:i,channelLabel:c,filename:s.length>0?s:"txt",messageType:d,fromPeerId:l,timestamp:p??Date.now(),savedSize:u>0?u:0,totalSize:h,chunksCreated:f??0,totalChunks:m??0}):t[g].messages[n].timestamp!==p&&t[g].messages[n].sha512Hex===i&&t[g].messages[n].savedSize===t[g].messages[n].totalSize?t[g].messages.push({transferId:o,merkleRootHex:a,sha512Hex:i,channelLabel:c,filename:s.length>0?s:"txt",messageType:d,fromPeerId:l,timestamp:p??Date.now(),savedSize:u,totalSize:h,chunksCreated:f??0,totalChunks:m??0}):(a.length===2*y&&""===t[g].messages[n].merkleRootHex&&(t[g].messages[n].merkleRootHex=a),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:o,merkleRootHex:a,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===a);-1===n&&s&&d&&e.isUUID(d)&&l&&h||n>-1&&t[f].messages[n].timestamp<u?t[f].messages.push({transferId:o,merkleRootHex:a,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)=>{je(e,t.payload)},deleteMessageStateOnly:(e,t)=>{je(e,t.payload)},setOnlyConnectWithKnownPeers:(e,t)=>{const{roomId:n,roomUrl:r,onlyConnectWithKnownPeers:o}=t.payload,a=e.findIndex(e=>void 0!==r&&e.url===r||void 0===r&&e.id===n);a>-1&&(e[a].onlyConnectWithKnownAddresses=o)},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,o=Oe(void 0);e[n]={url:t,id:"",connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:!0,onlyConnectWithKnownAddresses:!1,callerRtcConfig:o,signalingTurnCredentials:null,rtcConfig:qe(o,null),roomResponseGeneration:0,signalingActive:!1,policy:Ce(r),peers:[],channels:[],messages:[]}}},purgeAllRooms:()=>[],incrementMessageStats:(e,t)=>{const{roomId:n,merkleRootHex:r,sha512Hex:o,real:a,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!==o&&e.sha512Hex===o);if(c<0)return;const l=e[s].messages[c];i?l.retransmits=(l.retransmits??0)+1:(l.chunksReceivedTotal=(l.chunksReceivedTotal??0)+1,a&&(l.chunksReceivedReal=(l.chunksReceivedReal??0)+1))}}}),{setRoom:$e,applyRoomResponse:He,rollbackRoomResponse:Ve,expireRoomTurnCredentials:We,setRoomPolicy:Qe,setConnectingToPeers:Ge,setConnectedToPeers:Xe,setConnectionRelay:Je,setOnlyConnectWithKnownPeers:Ye,setPeer:Ze,setPeerCoverStatus:et,setPeerHandshakeStatus:tt,setChannel:nt,setIceServers:rt,setMessage:ot,setMessageAllChunks:at,incrementMessageStats:it,deletePeer:st,deleteChannel:ct,deleteMessage:lt,deleteMessageStateOnly:dt,deleteRoom:ut,purgeAllRooms:ht}=ze.actions,ft=e=>e.rooms;var mt=ze.reducer;const pt="wss://signaling.p2party.com/ws",yt={isEstablishingConnection:!1,isConnected:!1,isVerified:!1,serverUrl:pt},gt=t.createSlice({name:"signalingServer",initialState:yt,reducers:{startConnecting:(e,t)=>{e.isEstablishingConnection=!0,e.serverUrl=t.payload??pt},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}}}),wt=gt.actions;var bt=gt.reducer;let vt=!1;vt=(()=>{try{return"1"===globalThis.localStorage?.getItem("p2party:debug")}catch{return!1}})();const kt=e=>{vt=e},It=(...e)=>{vt&&console.log(...e)};var St=Symbol.for("immer-nothing"),Ct=Symbol.for("immer-draftable"),At=Symbol.for("immer-state");function Et(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Pt=Object,xt=Pt.getPrototypeOf,Rt="constructor",Mt="prototype",Kt="configurable",Ut="enumerable",_t="writable",Dt="value",Tt=e=>!!e&&!!e[At];function Lt(e){return!!e&&(Nt(e)||Ht(e)||!!e[Ct]||!!e[Rt]?.[Ct]||Vt(e)||Wt(e))}var qt=Pt[Mt][Rt].toString(),Ot=new WeakMap;function Nt(e){if(!e||!Qt(e))return!1;const t=xt(e);if(null===t||t===Pt[Mt])return!0;const n=Pt.hasOwnProperty.call(t,Rt)&&t[Rt];if(n===Object)return!0;if(!Gt(n))return!1;let r=Ot.get(n);return void 0===r&&(r=Function.toString.call(n),Ot.set(n,r)),r===qt}function Bt(e,t,n=!0){if(0===Ft(e)){(n?Reflect.ownKeys(e):Pt.keys(e)).forEach(n=>{t(n,e[n],e)})}else e.forEach((n,r)=>t(r,n,e))}function Ft(e){const t=e[At];return t?t.type_:Ht(e)?1:Vt(e)?2:Wt(e)?3:0}var jt=(e,t,n=Ft(e))=>2===n?e.has(t):Pt[Mt].hasOwnProperty.call(e,t),zt=(e,t,n=Ft(e))=>2===n?e.get(t):e[t],$t=(e,t,n,r=Ft(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n};var Ht=Array.isArray,Vt=e=>e instanceof Map,Wt=e=>e instanceof Set,Qt=e=>"object"==typeof e,Gt=e=>"function"==typeof e,Xt=e=>"boolean"==typeof e;var Jt=e=>e.copy_||e.base_,Yt=e=>e.modified_?e.copy_:e.base_;function Zt(e,t){if(Vt(e))return new Map(e);if(Wt(e))return new Set(e);if(Ht(e))return Array[Mt].slice.call(e);const n=Nt(e);if(!0===t||"class_only"===t&&!n){const t=Pt.getOwnPropertyDescriptors(e);delete t[At];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const o=n[r],a=t[o];!1===a[_t]&&(a[_t]=!0,a[Kt]=!0),(a.get||a.set)&&(t[o]={[Kt]:!0,[_t]:!0,[Ut]:a[Ut],[Dt]:e[o]})}return Pt.create(xt(e),t)}{const t=xt(e);if(null!==t&&n)return{...e};const r=Pt.create(t);return Pt.assign(r,e)}}function en(e,t=!1){return nn(e)||Tt(e)||!Lt(e)||(Ft(e)>1&&Pt.defineProperties(e,{set:tn,add:tn,clear:tn,delete:tn}),Pt.freeze(e),t&&Bt(e,(e,t)=>{en(t,!0)},!1)),e}var tn={[Dt]:function(){Et(2)}};function nn(e){return null===e||!Qt(e)||Pt.isFrozen(e)}var rn="MapSet",on="Patches",an="ArrayMethods",sn={};function cn(e){const t=sn[e];return t||Et(0),t}var ln,dn=e=>!!sn[e];var un=()=>ln;function hn(e,t){t&&(e.patchPlugin_=cn(on),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function fn(e){mn(e),e.drafts_.forEach(yn),e.drafts_=null}function mn(e){e===ln&&(ln=e.parent_)}var pn=e=>ln={drafts_:[],parent_:ln,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:dn(rn)?cn(rn):void 0,arrayMethodsPlugin_:dn(an)?cn(an):void 0};function yn(e){const t=e[At];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function gn(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[At].modified_&&(fn(t),Et(4)),Lt(e)&&(e=wn(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[At].base_,e,t)}else e=wn(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&en(t,n)}(t,e,!0),fn(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==St?e:void 0}function wn(e,t){if(nn(t))return t;const n=t[At];if(!n){return Cn(t,e.handledSet_,e)}if(!vn(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)}Sn(n,e)}return n.copy_}function bn(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var vn=(e,t)=>e.scope_===t,kn=[];function In(e,t,n,r){const o=Jt(e),a=e.type_;if(void 0!==r){if(zt(o,r,a)===t)return void $t(o,r,n,a)}if(!e.draftLocations_){const t=e.draftLocations_=new Map;Bt(o,(e,n)=>{if(Tt(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const i=e.draftLocations_.get(t)??kn;for(const e of i)$t(o,e,n,a)}function Sn(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)}bn(e)}}function Cn(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||Tt(e)||t.has(e)||!Lt(e)||nn(e)||(t.add(e),Bt(e,(r,o)=>{if(Tt(o)){const t=o[At];if(vn(t,n)){const n=Yt(t);$t(e,r,n,e.type_),bn(t)}}else Lt(o)&&Cn(o,t,n)})),e}var An={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 o=Jt(e);if(!jt(o,t,e.type_))return function(e,t,n){const r=xn(t,n);return r?Dt in r?r[Dt]:r.get?.call(e.draft_):void 0}(e,o,t);const a=o[t];if(e.finalized_||!Lt(a))return a;if(r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&function(e){const t=+e;return Number.isInteger(t)&&String(t)===e}(t))return a;if(a===Pn(e.base_,t)||function(e,t,n){if(1!==e.type_||!e.allIndicesReassigned_||e.assigned_?.get(t)||!Lt(n)||n[At])return!1;return e.baseRefs_.has(n)}(e,t,a)){Mn(e);const n=1===e.type_?+t:t,r=Kn(e.scope_,a,e,n);return e.copy_[n]=r}return a},has:(e,t)=>t in Jt(e),ownKeys:e=>Reflect.ownKeys(Jt(e)),set(e,t,n){const r=xn(Jt(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=Pn(Jt(e),t),i=r?.[At];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(((o=n)===(a=r)?0!==o||1/o==1/a:o!=o&&a!=a)&&(void 0!==n||jt(e.base_,t,e.type_)))return!0;Mn(e),Rn(e)}var o,a;return e.copy_[t]===n&&(void 0!==n||jt(e.copy_,t,e.type_))||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),function(e,t,n){const{scope_:r}=e;if(Tt(n)){const o=n[At];vn(o,r)&&o.callbacks_.push(function(){Mn(e);const r=Yt(o);In(e,n,r,t)})}else Lt(n)&&e.callbacks_.push(function(){const o=Jt(e);3===e.type_?o.has(n)&&Cn(n,r.handledSet_,r):zt(o,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&Cn(zt(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(Mn(e),void 0!==Pn(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),Rn(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=Jt(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[_t]:!0,[Kt]:1!==e.type_||"length"!==t,[Ut]:r[Ut],[Dt]:n[t]}:r},defineProperty(){Et(11)},getPrototypeOf:e=>xt(e.base_),setPrototypeOf(){Et(12)}},En={};for(let e in An){let t=An[e];En[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function Pn(e,t){const n=e[At];return(n?Jt(n):e)[t]}function xn(e,t){if(!(t in e))return;let n=xt(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=xt(n)}}function Rn(e){e.modified_||(e.modified_=!0,e.parent_&&Rn(e.parent_))}function Mn(e){e.copy_||(e.assigned_=new Map,e.copy_=Zt(e.base_,e.scope_.immer_.useStrictShallowCopy_))}En.deleteProperty=function(e,t){return En.set.call(this,e,t,void 0)},En.set=function(e,t,n){return An.set.call(this,e[0],t,n,e[0])};function Kn(e,t,n,r){const[o,a]=Vt(t)?cn(rn).proxyMap_(t,n):Wt(t)?cn(rn).proxySet_(t,n):function(e,t){const n=Ht(e),r={type_:n?1:0,scope_:t?t.scope_:un(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let o=r,a=An;n&&(o=[r],a=En);const{revoke:i,proxy:s}=Proxy.revocable(o,a);return r.draft_=s,r.revoke_=i,[s,r]}(t,n);return(n?.scope_??un()).drafts_.push(o),a.callbacks_=n?.callbacks_??[],a.key_=r,n&&void 0!==r?function(e,t,n){e.callbacks_.push(function(r){const o=t;if(!o||!vn(o,r))return;r.mapSetPlugin_?.fixSetContents(o);const a=Yt(o);In(e,o.draft_??o,a,n),Sn(o,r)})}(n,a,r):a.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(a);const{patchPlugin_:t}=e;a.modified_&&t&&t.generatePatches_(a,[],e)}),o}function Un(e){return Tt(e)||Et(10),_n(e)}function _n(e){if(!Lt(e)||nn(e))return e;const t=e[At];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Zt(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=Zt(e,!0);return Bt(n,(e,t)=>{$t(n,e,_n(t))},r),t&&(t.finalized_=!1),n}function Dn(){const e="replace",t="add",n="remove";function r(e){if(!Lt(e))return e;if(Ht(e))return e.map(r);if(Vt(e))return new Map(Array.from(e.entries()).map(([e,t])=>[e,r(t)]));if(Wt(e))return new Set(Array.from(e).map(r));const t=Object.create(xt(e));for(const n in e)t[n]=r(e[n]);return jt(e,Ct)&&(t[Ct]=e[Ct]),t}function o(e){return Tt(e)?r(e):e}var a,i;i={applyPatches_:function(o,a){return a.forEach(a=>{const{path:i,op:s}=a;let c=o;for(let e=0;e<i.length-1;e++){const t=Ft(c);let n=i[e];"string"!=typeof n&&"number"!=typeof n&&(n=""+n),0!==t&&1!==t||"__proto__"!==n&&n!==Rt||Et(19),Gt(c)&&n===Mt&&Et(19),c=zt(c,n),null!==c&&Qt(c)||Et(18,i.join("/"))}const l=Ft(c),d=r(a.value),u=i[i.length-1];switch(s){case e:switch(l){case 2:return c.set(u,d);case 3:Et(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(a.value);default:return delete c[u]}default:Et(17)}}),o},generatePatches_:function(r,a,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,a,i,s){const{base_:c,copy_:l,type_:d}=r;Bt(r.assigned_,(r,u)=>{const h=zt(c,r,d),f=zt(l,r,d),m=u?jt(c,r)?e:t:n;if(h===f&&m===e)return;const p=a.concat(r);i.push(m===n?{op:m,path:p}:{op:m,path:p,value:o(f)}),s.push(m===t?{op:n,path:p}:m===n?{op:t,path:p,value:o(h)}:{op:e,path:p,value:o(h)})})}(r,a,s,c);case 1:return function(r,a,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=a.concat([t]);i.push({op:e,path:l,value:o(n)}),s.push({op:e,path:l,value:o(r)})}}for(let e=c.length;e<d.length;e++){const n=a.concat([e]);i.push({op:t,path:n,value:o(d[e])})}for(let e=d.length-1;c.length<=e;--e){const t=a.concat([e]);s.push({op:n,path:t})}}(r,a,s,c);case 3:return function(e,r,o,a){let{base_:i,copy_:s}=e,c=0;i.forEach(e=>{if(!s.has(e)){const i=r.concat([c]);o.push({op:n,path:i,value:e}),a.unshift({op:t,path:i,value:e})}c++}),c=0,s.forEach(e=>{if(!i.has(e)){const i=r.concat([c]);o.push({op:t,path:i,value:e}),a.unshift({op:n,path:i,value:e})}c++})}(r,a,s,c)}},generateReplacementPatches_:function(t,n,r){const{patches_:o,inversePatches_:a}=r;o.push({op:e,path:[],value:n===St?void 0:n}),a.push({op:e,path:[],value:t})},getPath:function e(t,n=[]){if(void 0!==t.key_){const e=t.parent_.copy_??t.parent_.base_,o=(r=zt(e,t.key_),Qt(r)?r?.[At]:null),a=zt(e,t.key_);if(void 0===a)return null;if(a!==t.draft_&&a!==t.base_&&a!==t.copy_)return null;if(null!=o&&o.base_!==t.base_)return null;const i=3===t.parent_.type_;let s;if(i){const e=t.parent_;s=Array.from(e.drafts_.keys()).indexOf(t.key_)}else s=t.key_;if(!(i&&e.size>s||jt(e,s)))return null;n.push(s)}var r;if(t.parent_)return e(t.parent_,n);n.reverse();try{!function(e,t){let n=e;for(let e=0;e<t.length-1;e++){const r=t[e];if(n=zt(n,r),!Qt(n)||null===n)throw new Error(`Cannot resolve path at '${t.join("/")}'`)}}(t.copy_,n)}catch(e){return null}return n}},sn[a=on]||(sn[a]=i)}var Tn=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(Gt(e)&&!Gt(t)){const n=t;t=e;const r=this;return function(e=n,...o){return r.produce(e,e=>t.call(this,e,...o))}}let r;if(Gt(t)||Et(6),void 0===n||Gt(n)||Et(7),Lt(e)){const o=pn(this),a=Kn(o,e,void 0);let i=!0;try{r=t(a),i=!1}finally{i?fn(o):mn(o)}return hn(o,n),gn(r,o)}if(!e||!Qt(e)){if(r=t(e),void 0===r&&(r=e),r===St&&(r=void 0),this.autoFreeze_&&en(r,!0),n){const t=[],o=[];cn(on).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:o}),n(t,o)}return r}Et(1)},this.produceWithPatches=(e,t)=>{if(Gt(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},Xt(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),Xt(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),Xt(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Lt(e)||Et(8),Tt(e)&&(e=Un(e));const t=pn(this),n=Kn(t,e,void 0);return n[At].isManual_=!0,mn(t),n}finishDraft(e,t){const n=e&&e[At];n&&n.isManual_||Et(9);const{scope_:r}=n;return hn(r,t),gn(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=cn(on).applyPatches_;return Tt(e)?r(e,t):this.produce(e,e=>r(e,t))}};Tn.produce;var Ln=Tn.produceWithPatches.bind(Tn),qn=Tn.applyPatches.bind(Tn),On=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}};var Nn=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 Fn="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function jn(){return{s:0,v:void 0,o:null,p:null}}function zn(e,t={}){let n={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:r}=t;let o,a=0;function i(){let t=n;const{length:i}=arguments;for(let e=0,n=i;e<n;e++){const n=arguments[e];if("function"==typeof n||"object"==typeof n&&null!==n){let e=t.o;null===e&&(t.o=e=new WeakMap);const r=e.get(n);void 0===r?(t=jn(),e.set(n,t)):t=r}else{let e=t.p;null===e&&(t.p=e=new Map);const r=e.get(n);void 0===r?(t=jn(),e.set(n,t)):t=r}}const s=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),a++,r){const e=o?.deref?.()??o;null!=e&&r(e,c)&&(c=e,0!==a&&a--);o="object"==typeof c&&null!==c||"function"==typeof c?new Fn(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=()=>a,i.resetResultsCount=()=>{a=0},i}function $n(e,...t){const n="function"==typeof e?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t,r=0,o=0,a={},i=e.pop();"object"==typeof i&&(a=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,...a},{memoize:c,memoizeOptions:l=[],argsMemoize:d=zn,argsMemoizeOptions:u=[]}=s,h=Nn(l),f=Nn(u),m=Bn(e),p=c(function(){return r++,i.apply(null,arguments)},...h),y=d(function(){o++;const e=function(e,t){const n=[],{length:r}=e;for(let o=0;o<r;o++)n.push(e[o].apply(null,t));return n}(m,arguments);return t=p.apply(null,e),t},...f);return Object.assign(y,{resultFunc:i,memoizedResultFunc:p,dependencies:m,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>t,recomputations:()=>r,resetRecomputations:()=>{r=0},memoize:c,argsMemoize:d})};return Object.assign(r,{withTypes:()=>r}),r}var Hn=$n(zn),Vn=Object.assign((e,t=Hn)=>{!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:()=>Vn}),Wn="uninitialized",Qn="pending",Gn="fulfilled",Xn="rejected";function Jn(e){return{status:e,isUninitialized:e===Wn,isLoading:e===Qn,isSuccess:e===Gn,isError:e===Xn}}var Yn=t.isPlainObject;function Zn(e,t){if(e===t||!(Yn(e)&&Yn(t)||Array.isArray(e)&&Array.isArray(t)))return t;const n=Object.keys(t),r=Object.keys(e);let o=n.length===r.length;const a=Array.isArray(t)?[]:{};for(const r of n)a[r]=Zn(e[r],t[r]),o&&(o=e[r]===a[r]);return o?e:a}function er(e,t,n){return e.reduce((e,r,o)=>(t(r,o)&&e.push(n(r,o)),e),[]).flat()}function tr(e){return null!=e}function nr(e){return[...e?.values()??[]].filter(tr)}function rr(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var or=()=>new Map,ar=class{constructor(e,t=void 0){this.value=e,this.meta=t}value;meta},ir="__rtkq/",sr="focused",cr=t.createAction(`${ir}${sr}`),lr=t.createAction(`${ir}un${sr}`),dr=t.createAction(`${ir}online`),ur=t.createAction(`${ir}offline`),hr="query",fr="mutation",mr="infinitequery";function pr(e){return e.type===hr}function yr(e){return e.type===mr}function gr(e){return pr(e)||yr(e)}function wr(e,t,n,r,o,a){const i="function"==typeof e?e(t,n,r,o):e;return i?er(i,tr,e=>a(br(e))):[]}function br(e){return"string"==typeof e?{type:e}:e}var vr=(e,t)=>e.endpointDefinitions[t],kr=Symbol("forceQueryFn"),Ir=e=>"function"==typeof e[kr];var Sr=class extends On{constructor(e,t,n,r){super(e),this.value=t,this.schemaName=n,this._bqMeta=r}value;schemaName;_bqMeta},Cr=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function Ar(e,t,n,r){const o=await e["~standard"].validate(t);if(o.issues)throw new Sr(o.issues,t,n,r);return o.value}function Er(e){return e}var Pr=(e={})=>({...e,[t.SHOULD_AUTOBATCH]:!0});function xr(e,{pages:t,pageParams:n},r){const o=t.length-1;return e.getNextPageParam(t[o],t,n[o],n,r)}function Rr(e,{pages:t,pageParams:n},r){return e.getPreviousPageParam?.(t[0],t,n[0],n,r)}function Mr(e,n,r,o){return wr(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,o)}function Kr(e){return Tt(e)?Un(e):e}function Ur(e,t,n){const r=e[t];r&&n(r)}function _r(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function Dr(e,t,n){const r=e[_r(t)];r&&n(r)}var Tr={};function Lr({reducerPath:e,queryThunk:n,mutationThunk:r,serializeQueryArgs:o,context:{endpointDefinitions:a,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:Wn,endpointName:t.endpointName},Ur(e,t.queryCacheKey,e=>{e.status=Qn,e.requestId=n&&e.requestId?e.requestId:r.requestId,void 0!==t.originalArgs&&(e.originalArgs=t.originalArgs),e.startedTimeStamp=r.startedTimeStamp;yr(a[r.arg.endpointName])&&"direction"in t&&(e.direction=t.direction)})}function f(e,n,r,o){Ur(e,n.arg.queryCacheKey,e=>{if(e.requestId!==n.requestId&&!o)return;const{merge:i}=a[n.arg.endpointName];if(e.status=Gn,i)if(void 0!==e.data){const{fulfilledTimeStamp:o,arg:a,baseQueryMeta:s,requestId:c}=n;let l=t.createNextState(e.data,e=>i(e,r,{arg:a.originalArgs,baseQueryMeta:s,fulfilledTimeStamp:o,requestId:c}));e.data=l}else e.data=r;else e.data=a[n.arg.endpointName].structuralSharing??1?Zn(Tt(e.data)?(s=e.data,Tt(s)||Et(15),s[At].base_):e.data,r):r;var s;delete e.error,e.fulfilledTimeStamp=n.fulfilledTimeStamp})}const m=t.createSlice({name:`${e}/queries`,initialState:Tr,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:o}=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:{}},o,!0)}},prepare:e=>({payload:e.map(e=>{const{endpointName:t,arg:n,value:r}=e,i=a[t];return{queryDescription:{type:hr,endpointName:t,originalArgs:e.arg,queryCacheKey:o({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=qn(e.data,n.concat())})},prepare:t.prepareAutoBatched()}},extraReducers(e){e.addCase(n.pending,(e,{meta:t,meta:{arg:n}})=>{h(e,n,Ir(n),t)}).addCase(n.fulfilled,(e,{meta:t,payload:n})=>{f(e,t,n,Ir(t.arg))}).addCase(n.rejected,(e,{meta:{condition:t,arg:n,requestId:r},error:o,payload:a})=>{Ur(e,n.queryCacheKey,e=>{if(t);else{if(e.requestId!==r)return;e.status=Xn,e.error=a??o}})}).addMatcher(c,(e,t)=>{const{queries:n}=s(t);for(const[t,r]of Object.entries(n))r?.status!==Gn&&r?.status!==Xn||(e[t]=r)})}}),p=t.createSlice({name:`${e}/mutations`,initialState:Tr,reducers:{removeMutationResult:{reducer(e,{payload:t}){const n=_r(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:o}})=>{r.track&&(e[_r(t)]={requestId:n,status:Qn,endpointName:r.endpointName,startedTimeStamp:o})}).addCase(r.fulfilled,(e,{payload:t,meta:n})=>{n.arg.track&&Dr(e,n,e=>{e.requestId===n.requestId&&(e.status=Gn,e.data=t,e.fulfilledTimeStamp=n.fulfilledTimeStamp)})}).addCase(r.rejected,(e,{payload:t,error:n,meta:r})=>{r.arg.track&&Dr(e,r,e=>{e.requestId===r.requestId&&(e.status=Xn,e.error=t??n)})}).addMatcher(c,(e,t)=>{const{mutations:n}=s(t);for(const[t,r]of Object.entries(n))r?.status!==Gn&&r?.status!==Xn||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:o}of r){const r=(e.tags[t]??={})[o||"__internal_without_id"]??=[];r.includes(n)||r.push(n)}e.keys[n]=r}},prepare:t.prepareAutoBatched()}},extraReducers(e){e.addCase(m.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[o,a]of Object.entries(r)){const r=(e.tags[t]??={})[o||"__internal_without_id"]??=[];for(const t of a){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(m.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=Kr(e.keys[t]??[]);for(const r of n){const n=r.type,o=r.id??"__internal_without_id",a=e.tags[n]?.[o];a&&(e.tags[n][o]=Kr(a).filter(e=>e!==t))}delete e.keys[t]}function w(e,t){const n=t.map(e=>{const t=Mr(e,"providesTags",a,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:Tr,reducers:{updateSubscriptionOptions(e,t){},unsubscribeQueryResult(e,t){},internal_getRTKQSubscriptions(){}}}),v=t.createSlice({name:`${e}/internalSubscriptions`,initialState:Tr,reducers:{subscriptionsUpdated:{reducer:(e,t)=>qn(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(dr,e=>{e.online=!0}).addCase(ur,e=>{e.online=!1}).addCase(cr,e=>{e.focused=!0}).addCase(lr,e=>{e.focused=!1}).addMatcher(c,e=>({...e}))}}),I=t.combineReducers({queries:m.reducer,mutations:p.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,...m.actions,...b.actions,...v.actions,...p.actions,...y.actions,resetApiState:u}}}var qr=Symbol.for("RTKQ/skipToken"),Or={status:Wn},Nr=t.createNextState(Or,()=>{}),Br=t.createNextState(Or,()=>{});var Fr=WeakMap?new WeakMap:void 0,jr=({endpointName:e,queryArgs:n})=>{let r="";const o=Fr?.get(n);if("string"==typeof o)r=o;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)&&Fr?.set(n,e),r=e}return`${e}(${r})`};function zr(...e){return function(n){const r=zn(e=>n.extractRehydrationInfo?.(e,{reducerPath:n.reducerPath??"api"})),o={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...n,extractRehydrationInfo:r,serializeQueryArgs(e){let t=jr;if("serializeQueryArgs"in e.endpointDefinition){const n=e.endpointDefinition.serializeQueryArgs;t=e=>{const t=n(e);return"string"==typeof t?t:jr({...e,queryArgs:t})}}else n.serializeQueryArgs&&(t=n.serializeQueryArgs);return t(e)},tagTypes:[...n.tagTypes||[]]},a={endpointDefinitions:{},batch(e){e()},apiUid:t.nanoid(),extractRehydrationInfo:r,hasRehydrationInfo:zn(e=>null!=r(e))},i={injectEndpoints:function(e){const n=e.endpoints({query:e=>({...e,type:hr}),mutation:e=>({...e,type:fr}),infiniteQuery:e=>({...e,type:mr})});for(const[r,o]of Object.entries(n))if(!0!==e.overrideExisting&&r in a.endpointDefinitions){if("throw"===e.overrideExisting)throw new Error(t.formatProdErrorMessage(39))}else{a.endpointDefinitions[r]=o;for(const e of s)e.injectEndpoint(r,o)}return i},enhanceEndpoints({addTagTypes:e,endpoints:t}){if(e)for(const t of e)o.tagTypes.includes(t)||o.tagTypes.push(t);if(t)for(const[e,n]of Object.entries(t))"function"==typeof n?n(vr(a,e)):Object.assign(vr(a,e)||{},n);return i}},s=e.map(e=>e.init(i,o,a));return i.injectEndpoints({endpoints:n.endpoints})}}function $r(e,...t){return Object.assign(e,...t)}var Hr=({api:e,queryThunk:t,internalState:n,mwApi:r})=>{const o=`${e.reducerPath}/subscriptions`;let a=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(a||(a=u(n.currentSubscriptions)),e.util.resetApiState.match(r))return a={},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:o}=r.payload,a=n.get(e);return a?.has(t)&&a.set(t,o),!0}if(c.match(r)){const{queryCacheKey:e,requestId:t}=r.payload,o=n.get(e);return o&&o.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,o=rr(n,e.queryCacheKey,or);return e.subscribe&&o.set(t,e.subscriptionOptions??o.get(t)??{}),!0}let o=!1;if(t.rejected.match(r)){const{meta:{condition:e,arg:t,requestId:a}}=r;if(e&&t.subscribe){const e=rr(n,t.queryCacheKey,or);e.set(a,t.subscriptionOptions??e.get(a)??{}),o=!0}}return o})(n.currentSubscriptions,r);let f=!0;if(h){i||(i=setTimeout(()=>{const t=u(n.currentSubscriptions),[,r]=Ln(a,()=>t);l.next(e.internalActions.subscriptionsUpdated(r)),a=t,i=null},500));const s="string"==typeof r.type&&!!r.type.startsWith(o),c=t.rejected.match(r)&&r.meta.condition&&!!r.meta.arg.subscribe;f=!s&&!c}return[f,!1]}},Vr=({reducerPath:e,api:n,queryThunk:r,context:o,internalState:a,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 m(e){const t=a.currentSubscriptions.get(e);if(!t)return!1;return t.size>0}const p={};function y(e){for(const t of e.values())t?.abort?.()}function g(e,t,n){const r=t.getState();for(const o of e){const e=i(r,o);e?.endpointName&&w(o,e.endpointName,t,n)}}function w(e,t,n,r){const a=vr(o,t),s=a?.keepUnusedDataFor??r.keepUnusedDataFor;if(s===1/0)return;const l=Math.max(0,Math.min(s,2147482.647));if(!m(e)){const t=p[e];t&&clearTimeout(t),p[e]=setTimeout(()=>{if(!m(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 p[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(p))t&&clearTimeout(t),delete p[e];y(a.runningQueries),y(a.runningMutations)}if(o.hasRehydrationInfo(e)){const{queries:n}=o.extractRehydrationInfo(e);g(Object.keys(n),t,i)}}},Wr=new Error("Promise never resolved before cacheEntryRemoved."),Qr=({api:e,reducerPath:n,context:r,queryThunk:o,mutationThunk:a,internalState:i,selectors:{selectQueryEntry:s,selectApiState:c}})=>{const l=t.isAsyncThunkAction(o),d=t.isAsyncThunkAction(a),u=t.isFulfilled(o,a),h={},{removeQueryResult:f,removeMutationResult:m,cacheEntriesUpserted:p}=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:o}=t;return[r,o,n]}function b(t,n,o,a,i){const s=vr(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 Wr})]);u.catch(()=>{}),h[o]=l;const f=e.endpoints[t].select(gr(s)?n:o),m=a.dispatch((e,t,n)=>n),p={...a,getCacheEntry:()=>f(a.getState()),requestId:i,extra:m,updateCachedData:gr(s)?r=>a.dispatch(e.util.updateQueryData(t,n,r)):void 0,cacheDataLoaded:u,cacheEntryRemoved:d},y=c(n,p);Promise.resolve(y).catch(e=>{if(e!==Wr)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:m.match(e)?_r(e.payload):""}(t);function v(e,t,n,o){const a=s(i,t),c=s(r.getState(),t);!a&&c&&b(e,o,t,r,n)}if(o.pending.match(t)){const[e,n,r]=w(t);v(e,c,r,n)}else if(p.match(t))for(const{queryDescription:e,value:n}of t.payload){const{endpointName:r,originalArgs:o,queryCacheKey:a}=e;v(r,a,t.meta.requestId,o),y(a,n,{})}else if(a.pending.match(t)){if(r.getState()[n].mutations[c]){const[e,n,o]=w(t);b(e,n,c,r,o)}}else if(u(t))y(c,t.payload,t.meta.baseQueryMeta);else if(f.match(t)||m.match(t))g(c);else if(e.util.resetApiState.match(t))for(const e of Object.keys(h))g(e)}},Gr=({api:e,context:{apiUid:t},reducerPath:n})=>(n,r)=>{e.util.resetApiState.match(n)&&r.dispatch(e.internalActions.middlewareRegistered(t))},Xr=({reducerPath:e,context:n,context:{endpointDefinitions:r},mutationThunk:o,queryThunk:a,api:i,assertTagType:s,refetchQuery:c,internalState:l})=>{const{removeQueryResult:d}=i.internalActions,u=t.isAnyOf(t.isFulfilled(o),t.isRejectedWithValue(o)),h=t.isAnyOf(t.isFulfilled(a,o),t.isRejected(a,o));let f=[],m=0;function p(t,r){const o=r.getState(),a=o[e];if(f.push(...t),"delayed"===a.config.invalidationBehavior&&m>0)return;const s=f;if(f=[],0===s.length)return;const u=i.util.selectInvalidatedBy(o,s);n.batch(()=>{const e=Array.from(u.values());for(const{queryCacheKey:t}of e){const e=a.queries[t],n=rr(l.currentSubscriptions,t,or);e&&(0===n.size?r.dispatch(d({queryCacheKey:t})):e.status!==Wn&&r.dispatch(c(e)))}})}return(e,t)=>{(a.pending.match(e)||o.pending.match(e))&&m++,h(e)&&(m=Math.max(0,m-1)),u(e)?p(Mr(e,"invalidatesTags",r,s),t):h(e)?p([],t):i.util.invalidateTags.match(e)&&p(wr(e.payload,void 0,void 0,void 0,void 0,s),t)}},Jr=({reducerPath:e,queryThunk:t,api:n,refetchQuery:r,internalState:o})=>{const{currentPolls:a,currentSubscriptions:i}=o,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 o=n.getState()[e],s=o.queries[t],c=i.get(t);if(!s||s.status===Wn)return;const{lowestPollingInterval:l,skipPollingIfUnfocused:u}=f(c);if(!Number.isFinite(l))return;const h=a.get(t);h?.timeout&&(clearTimeout(h.timeout),h.timeout=void 0);const m=Date.now()+l;a.set(t,{nextPollTimestamp:m,pollingInterval:l,timeout:setTimeout(()=>{!o.config.focused&&u||n.dispatch(r(s)),d({queryCacheKey:t},n)},l)})}function u({queryCacheKey:t},n){const r=n.getState()[e].queries[t],o=i.get(t);if(!r||r.status===Wn)return;const{lowestPollingInterval:s}=f(o);if(!Number.isFinite(s))return void h(t);const c=a.get(t),l=Date.now()+s;(!c||l<c.nextPollTimestamp)&&d({queryCacheKey:t},n)}function h(e){const t=a.get(e);t?.timeout&&clearTimeout(t.timeout),a.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 a.keys())h(e)}(),c&&(clearTimeout(c),c=null),s.clear())}},Yr=({api:e,context:n,queryThunk:r,mutationThunk:o})=>{const a=t.isPending(r,o),i=t.isRejected(r,o),s=t.isFulfilled(r,o),c={};return(t,r)=>{if(a(t)){const{requestId:o,arg:{endpointName:a,originalArgs:i}}=t.meta,s=vr(n,a),l=s?.onQueryStarted;if(l){const t={},n=new Promise((e,n)=>{t.resolve=e,t.reject=n});n.catch(()=>{}),c[o]=t;const d=e.endpoints[a].select(gr(s)?i:o),u=r.dispatch((e,t,n)=>n),h={...r,getCacheEntry:()=>d(r.getState()),requestId:o,extra:u,updateCachedData:gr(s)?t=>r.dispatch(e.util.updateQueryData(a,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 Zr(e){const{reducerPath:n,queryThunk:r,api:o,context:a,getInternalState:i}=e,{apiUid:s}=a,c={invalidateTags:t.createAction(`${n}/invalidateTags`)},l=e=>e.type.startsWith(`${n}/`),d=[Gr,Vr,Xr,Jr,Qr,Yr];return{middleware:r=>{let c=!1;const h=i(r.dispatch),f={...e,internalState:h,refetchQuery:u,isThisApiSliceAction:l,mwApi:r},m=d.map(e=>e(f)),p=Hr(f),y=(({reducerPath:e,context:t,api:n,refetchQuery:r,internalState:o})=>{const{removeQueryResult:a}=n.internalActions;function i(n,i){const s=n.getState()[e],c=s.queries,l=o.currentSubscriptions;t.batch(()=>{for(const e of l.keys()){const t=c[e],o=l.get(e);if(!o||!t)continue;const d=[...o.values()];(d.some(e=>!0===e[i])||d.every(e=>void 0===e[i])&&s.config[i])&&(0===o.size?n.dispatch(a({queryCacheKey:e})):t.status!==Wn&&n.dispatch(r(t)))}})}return(e,t)=>{cr.match(e)&&i(t,"refetchOnFocus"),dr.match(e)&&i(t,"refetchOnReconnect")}})(f);return e=>i=>{if(!t.isAction(i))return e(i);c||(c=!0,r.dispatch(o.internalActions.middlewareRegistered(s)));const d={...r,next:e},u=r.getState(),[h,f]=p(i,d,u);let g;if(g=h?e(i):f,r.getState()[n]&&(y(i,d,u),l(i)||a.hasRehydrationInfo(i)))for(const e of m)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 eo=Symbol(),to=zr((({createSelector:e=t.createSelector}={})=>({name:eo,init(n,{baseQuery:r,tagTypes:o,reducerPath:a,serializeQueryArgs:i,keepUnusedDataFor:s,refetchOnMountOrArgChange:c,refetchOnFocus:l,refetchOnReconnect:d,invalidationBehavior:u,onSchemaFailure:h,catchSchemaFailure:f,skipSchemaValidation:m},p){Dn();const y=e=>e;Object.assign(n,{reducerPath:a,endpoints:{},internalActions:{onOnline:dr,onOffline:ur,onFocus:cr,onFocusLost:lr},util:{}});const g=function({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=e=>Nr,o=e=>Br;return{buildQuerySelector:function(e,t){return l(e,t,a)},buildInfiniteQuerySelector:function(e,t){const{infiniteQueryOptions:n}=t;return l(e,t,function(e){const t={...e,...Jn(e.status)},{isLoading:r,isError:o,direction:a}=t,i="forward"===a,s="backward"===a;return{...t,hasNextPage:d(n,t.data,t.originalArgs),hasPreviousPage:u(n,t.data,t.originalArgs),isFetchingNextPage:r&&i,isFetchingPreviousPage:r&&s,isFetchNextPageError:o&&i,isFetchPreviousPageError:o&&s}})},buildMutationSelector:function(){return e=>{let t;return t="object"==typeof e?_r(e)??qr:e,n(t===qr?o:e=>i(e)?.mutations?.[t]??Br,a)}},selectInvalidatedBy:function(e,n){const r=e[t],o=new Set,a=er(n,tr,br);for(const e of a){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)o.add(e)}return Array.from(o.values()).flatMap(e=>{const t=r.queries[e];return t?{queryCacheKey:e,endpointName:t.endpointName,originalArgs:t.originalArgs}:[]})},selectCachedArgsForQuery:function(e,t){return er(Object.values(s(e)),e=>e?.endpointName===t&&e.status!==Wn,e=>e.originalArgs)},selectApiState:i,selectQueries:s,selectMutations:function(e){return i(e)?.mutations},selectQueryEntry:c,selectConfig:function(e){return i(e)?.config}};function a(e){return{...e,...Jn(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,o,a){return i=>{if(i===qr)return n(r,a);const s=e({queryArgs:i,endpointDefinition:o,endpointName:t});return n(e=>c(e,s)??Nr,a)}}function d(e,t,n){return!!t&&null!=xr(e,t,n)}function u(e,t,n){return!(!t||!e.getPreviousPageParam)&&null!=Rr(e,t,n)}}({serializeQueryArgs:i,reducerPath:a,createSelector:e}),{selectInvalidatedBy:w,selectCachedArgsForQuery:b,buildQuerySelector:v,buildInfiniteQuerySelector:k,buildMutationSelector:I}=g;$r(n.util,{selectInvalidatedBy:w,selectCachedArgsForQuery:b});const{queryThunk:S,infiniteQueryThunk:C,mutationThunk:A,patchQueryData:E,updateQueryData:P,upsertQueryData:x,prefetch:R,buildMatchThunkActions:M}=function({reducerPath:e,baseQuery:n,context:{endpointDefinitions:r},serializeQueryArgs:o,api:a,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]:Er,m=async(e,{signal:t,abort:o,rejectWithValue:a,fulfillWithValue:i,dispatch:m,getState:y,extra:g})=>{const w=r[e.endpointName],{metaSchema:b,skipSchemaValidation:v=d}=w,k=e.type===hr;try{let I=Er;const S={signal:t,abort:o,dispatch:m,getState:y,extra:g,endpoint:e.endpointName,type:e.type,forced:k?p(e,y()):void 0,queryCacheKey:k?e.queryCacheKey:void 0},C=k?e[kr]:void 0;let A;const E=async(t,n,r,o)=>{if(null==n&&t.pages.length)return Promise.resolve({data:t});const a={queryArg:e.originalArgs,pageParam:n},i=await P(a),s=o?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:o,rawResponseSchema:a,responseSchema:i}=w;if(o&&!Cr(v,"arg")&&(e=await Ar(o,e,"argSchema",{})),C?t=C():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 ar(t.error,t.meta);let{data:s}=t;a&&!Cr(v,"rawResponse")&&(s=await Ar(a,t.data,"rawResponseSchema",t.meta));let c=await I(s,t.meta,e);return i&&!Cr(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=p(e,y())&&!e.direction||!_?U:_;if("direction"in e&&e.direction&&D.pages.length){const T="backward"===e.direction,L=(T?Rr:xr)(x,D,e.originalArgs);K=await E(D,L,R,T)}else{const{initialPageParam:q=x.initialPageParam}=e,O=_?.pageParams??[],N=O[0]??q,B=O.length;if(K=await E(D,N,R),C&&(K={data:K.data.pages[0]}),M)for(let F=1;F<B;F++){const j=xr(x,K.data,e.originalArgs);K=await E(K.data,j,R)}}A=K}else A=await P(e.originalArgs);return b&&!Cr(v,"meta")&&A.meta&&(A.meta=await Ar(b,A.meta,"metaSchema",A.meta)),i(A.data,Pr({fulfilledTimeStamp:Date.now(),baseQueryMeta:A.meta}))}catch(z){let $=z;if($ instanceof ar){let H=f(w,"transformErrorResponse");const{rawErrorResponseSchema:V,errorResponseSchema:W}=w;let{value:Q,meta:G}=$;try{V&&!Cr(v,"rawErrorResponse")&&(Q=await Ar(V,Q,"rawErrorResponseSchema",G)),b&&!Cr(v,"meta")&&(G=await Ar(b,G,"metaSchema",G));let X=await H(Q,G,e.originalArgs);return W&&!Cr(v,"errorResponse")&&(X=await Ar(W,X,"errorResponseSchema",G)),a(X,Pr({baseQueryMeta:G}))}catch(J){$=J}}try{if($ instanceof Sr){const Y={endpoint:e.endpointName,arg:e.originalArgs,type:e.type,queryCacheKey:k?e.queryCacheKey:void 0};w.onSchemaFailure?.($,Y),c?.($,Y);const{catchSchemaFailure:Z=l}=w;if(Z)return a(Z($,Y),Pr({baseQueryMeta:$._bqMeta}))}}catch(ee){$=ee}throw console.error($),$}};function p(e,t){const n=s.selectQueryEntry(t,e.queryCacheKey),r=s.selectConfig(t).refetchOnMountOrArgChange,o=n?.fulfilledTimeStamp,a=e.forceRefetch??(e.subscribe&&r);return!!a&&(!0===a||(Number(new Date)-Number(o))/1e3>=a)}const y=()=>t.createAsyncThunk(`${e}/executeQuery`,m,{getPendingMeta({arg:e}){const t=r[e.endpointName];return Pr({startedTimeStamp:Date.now(),...yr(t)?{direction:e.direction}:{}})},condition(e,{getState:t}){const n=t(),o=s.selectQueryEntry(n,e.queryCacheKey),a=o?.fulfilledTimeStamp,i=e.originalArgs,c=o?.originalArgs,l=r[e.endpointName],d=e.direction;return!(!Ir(e)&&("pending"===o?.status||!p(e,n)&&(!pr(l)||!l?.forceRefetch?.({currentArg:i,previousArg:c,endpointState:o,state:n}))&&a&&!d))},dispatchConditionRejection:!0}),g=y(),w=y(),b=t.createAsyncThunk(`${e}/executeMutation`,m,{getPendingMeta:()=>Pr({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,o)=>{const i=(e=>"force"in e)(n)&&n.force,s=(e=>"ifOlderThan"in e)(n)&&n.ifOlderThan,c=(n=!0)=>{const r={forceRefetch:n,subscribe:!1};return a.endpoints[e].initiate(t,r)},l=a.endpoints[e].select(t)(o());if(i)r(c());else if(s){const e=l?.fulfilledTimeStamp;if(!e)return void r(c());(Number(new Date)-Number(new Date(e)))/1e3>=s&&r(c())}else r(c(!1))},updateQueryData:(e,t,n,r=!0)=>(o,i)=>{const s=a.endpoints[e].select(t)(i()),c={patches:[],inversePatches:[],undo:()=>o(a.util.patchQueryData(e,t,c.inversePatches,r))};if(s.status===Wn)return c;let l;if("data"in s)if(Lt(s.data)){const[e,t,r]=Ln(s.data,n);c.patches.push(...t),c.inversePatches.push(...r),l=e}else l=n(s.data),c.patches.push({op:"replace",path:[],value:l}),c.inversePatches.push({op:"replace",path:[],value:s.data});return 0===c.patches.length||o(a.util.patchQueryData(e,t,c.patches,r)),c},upsertQueryData:(e,t,n)=>r=>r(a.endpoints[e].initiate(t,{subscribe:!1,forceRefetch:!0,[kr]:()=>({data:n})})),patchQueryData:(e,t,n,s)=>(c,l)=>{const d=r[e],u=o({queryArgs:t,endpointDefinition:d,endpointName:e});if(c(a.internalActions.queryResultPatched({queryCacheKey:u,patches:n})),!s)return;const h=a.endpoints[e].select(t)(l()),f=wr(d.providesTags,h.data,void 0,t,{},i);c(a.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:a,context:p,api:n,serializeQueryArgs:i,assertTagType:y,selectors:g,onSchemaFailure:h,catchSchemaFailure:f,skipSchemaValidation:m}),{reducer:K,actions:U}=Lr({context:p,queryThunk:S,mutationThunk:A,serializeQueryArgs:i,reducerPath:a,assertTagType:y,config:{refetchOnFocus:l,refetchOnReconnect:d,refetchOnMountOrArgChange:c,keepUnusedDataFor:s,reducerPath:a,invalidationBehavior:u}});$r(n.util,{patchQueryData:E,updateQueryData:P,upsertQueryData:x,prefetch:R,resetApiState:U.resetApiState,upsertQueryEntries:U.cacheEntriesUpserted}),$r(n.internalActions,U);const _=new WeakMap,D=e=>rr(_,e,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:T,buildInitiateInfiniteQuery:L,buildInitiateMutation:q,getRunningMutationThunk:O,getRunningMutationsThunk:N,getRunningQueriesThunk:B,getRunningQueryThunk:F}=function({serializeQueryArgs:e,queryThunk:t,infiniteQueryThunk:n,mutationThunk:r,api:o,context:a,getInternalState:i}){const s=e=>i(e)?.runningQueries,c=e=>i(e)?.runningMutations,{unsubscribeQueryResult:l,removeMutationResult:d,updateSubscriptionOptions:u}=o.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:o}={})=>(a,i)=>{const s=r({type:"mutation",endpointName:e,originalArgs:t,track:n,fixedCacheKey:o}),l=a(s),{requestId:u,abort:h,unwrap:f}=l,m=(p=e=>({error:e}),l.unwrap().then(e=>({data:e})).catch(p));var p;const y=Object.assign(m,{arg:l.arg,requestId:u,abort:h,unwrap:f,reset:()=>{a(d({requestId:u,fixedCacheKey:o}))}}),g=c(a);return g.set(u,y),y.then(()=>{g.delete(u)}),o&&(g.set(o,y),y.then(()=>{g.get(o)===y&&g.delete(o)})),y}},getRunningQueryThunk:function(t,n){return r=>{const o=vr(a,t),i=e({queryArgs:n,endpointDefinition:o,endpointName:t});return s(r)?.get(i)}},getRunningMutationThunk:function(e,t){return e=>c(e)?.get(t)},getRunningQueriesThunk:function(){return e=>nr(s(e))},getRunningMutationsThunk:function(){return e=>nr(c(e))}};function h(r,a){const i=(c,{subscribe:d=!0,forceRefetch:h,subscriptionOptions:f,[kr]:m,...p}={})=>(y,g)=>{const w=e({queryArgs:c,endpointDefinition:a,endpointName:r});let b;const v={...p,type:hr,subscribe:d,forceRefetch:h,subscriptionOptions:f,endpointName:r,originalArgs:c,queryCacheKey:w,[kr]:m};if(pr(a))b=t(v);else{const{direction:e,initialPageParam:t,refetchCachedPages:r}=p;b=n({...v,direction:e,initialPageParam:t,refetchCachedPages:r})}const k=o.endpoints[r].select(c),I=y(b),S=k(g()),{requestId:C,abort:A}=I,E=S.requestId!==C,P=s(y)?.get(w),x=()=>k(g()),R=Object.assign(m?I.then(x):E&&!P?Promise.resolve(S):Promise.all([P,I]).then(x),{arg:c,requestId:C,subscriptionOptions:f,queryCacheKey:w,abort:A,async unwrap(){const e=await 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:C}))},updateSubscriptionOptions(e){R.subscriptionOptions=e,y(u({endpointName:r,requestId:C,queryCacheKey:w,options:e}))}});if(!P&&!E&&!m){const e=s(y);e.set(w,R),R.then(()=>{e.delete(w)})}return R};return i}}({queryThunk:S,mutationThunk:A,infiniteQueryThunk:C,api:n,serializeQueryArgs:i,context:p,getInternalState:D});$r(n.util,{getRunningMutationThunk:O,getRunningMutationsThunk:N,getRunningQueryThunk:F,getRunningQueriesThunk:B});const{middleware:j,actions:z}=Zr({reducerPath:a,context:p,queryThunk:S,mutationThunk:A,infiniteQueryThunk:C,api:n,assertTagType:y,selectors:g,getRunningQueryThunk:F,getInternalState:D});return $r(n.util,z),$r(n,{reducer:K,middleware:j}),{name:eo,injectEndpoint(e,t){const r=n,o=r.endpoints[e]??={};pr(t)&&$r(o,{name:e,select:v(e,t),initiate:T(e,t)},M(S,e)),t.type===fr&&$r(o,{name:e,select:I(),initiate:q(e)},M(A,e)),yr(t)&&$r(o,{name:e,select:k(e,t),initiate:L(e,t)},M(S,e))}}}}))());const no="0123456789abcdef",ro=new Array(64),oo=new Array(128),ao=e=>new Promise(t=>{let n=0;const r=e.length;for(let t=0;t<r;t++)n+=e[t].length;const o=new Uint8Array(n);let a=0;for(const t of e)o.set(t,a),a+=t.length;t(o)}),io=(e,t)=>new Promise(n=>{const r=e.length;if(r!==t.length)return void n(!1);let o=0;for(let n=0;n<r;n++)o|=e[n]^t[n];n(0===o)}),so=e=>{const t=e.length,n=t===y?oo:32===t?ro:new Array(2*t);let r=0;for(let o=0;o<t;o++){const t=e[o];n[r++]=no[t>>4],n[r++]=no[15&t]}return n.join("")},co=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,o=new Uint8Array(r);for(let e=0;e<r;e++)o[e]=parseInt(n[e],16);return o},lo=(e,t,n)=>{t=t??32,n=n??16384;const r=65536,o=Math.ceil((e+1048576)/r);if(o>n)throw new Error(`Memory required is ${String(o*r)} bytes while declared maximum is ${String(n*r)} bytes`);return o<t?t:o};var uo=()=>{const e=(v+k)*Uint8Array.BYTES_PER_ELEMENT,t=lo(e);return new WebAssembly.Memory({initial:t,maximum:t})},ho=()=>{const e=(R+M)*Uint8Array.BYTES_PER_ELEMENT,t=lo(e);return new WebAssembly.Memory({initial:t,maximum:t})},fo=()=>{const e=(v+k+b)*Uint8Array.BYTES_PER_ELEMENT,t=lo(e);return new WebAssembly.Memory({initial:t,maximum:t})},mo=e=>{const t=(e+w+k+y)*Uint8Array.BYTES_PER_ELEMENT,n=lo(t);return new WebAssembly.Memory({initial:n,maximum:n})},po=e=>{const t=(e+w+v)*Uint8Array.BYTES_PER_ELEMENT,n=lo(t);return new WebAssembly.Memory({initial:n,maximum:n})},yo=()=>{const e=lo(0);return new WebAssembly.Memory({initial:e,maximum:e})},go=e=>{const t=lo((2*e+3)*y);return new WebAssembly.Memory({initial:t,maximum:t})},wo=e=>{const t=lo(e*y+e*(y+1)+3*y);return new WebAssembly.Memory({initial:t,maximum:t})},bo=e=>{const t=(78643200+e+b+A)*Uint8Array.BYTES_PER_ELEMENT,n=lo(t);return new WebAssembly.Memory({initial:n,maximum:n})};function vo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ko,Io={exports:{}};var So=(ko||(ko=1,function(e){var t,n=(t=globalThis.document?.currentScript?.src,async function(e={}){var n=e,r=!!globalThis.window,o=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process,o&&(t=self.location.href);var a,i,s="";if(r||o){try{s=new URL(".",t).href}catch{}o&&(i=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),a=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,o=t*r;if(t<=0&&I(`segmentation fault ${n} ${r} bytes at address ${o}`),v){var a=_(0);o+r>a&&I(`segmentation fault, exceeded the top of the available dynamic heap when ${n} ${r} bytes at address ${o}. DYNAMICTOP=${a}`),a<D()&&I(`brk >= _emscripten_stack_get_base() (brk=${a}, _emscripten_stack_get_base()=${D()})`),a>b.buffer.byteLength&&I(`brk <= wasmMemory.buffer.byteLength (brk=${a}, wasmMemory.buffer.byteLength=${b.buffer.byteLength})`)}return t}var h,f,m,p,y,g,w,b,v=!1;function k(){if(!p?.buffer?.resizable){var e=b.buffer;p=new Int8Array(e),w=new Uint8Array(e),f=new Int32Array(e),g=new Uint32Array(e),y=new Float64Array(e),m=new BigInt64Array(e),new BigUint64Array(e)}}function I(e){throw l(e=`Aborted(${e})`),d=!0,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}function S(){return s+"libcrypto.wasm"}async function C(e){if(!c)try{var t=await a(e);return new Uint8Array(t)}catch{}return function(e){if(e==h&&c)return new Uint8Array(c);if(i)return i(e);throw"both async and sync fetching of the wasm failed"}(e)}async function A(e,t,n){if(!e)try{var r=fetch(t,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(r,n)}catch(e){l(`wasm streaming compile failed: ${e}`),l("falling back to ArrayBuffer instantiation")}return async function(e,t){try{var n=await C(e);return await WebAssembly.instantiate(n,t)}catch(e){l(`failed to asynchronously prepare wasm: ${e}`),I(e)}}(t,n)}var E=globalThis.TextDecoder&&new TextDecoder,P=(e,t,n)=>e?((e,t=0,n)=>{var r=((e,t,n)=>{for(var r=t+n;e[t]&&!(t>=r);)++t;return t})(e,t,n);if(r-t>16&&e.buffer&&E)return E.decode(e.subarray(t,r));for(var o="";t<r;){var a=e[t++];if(128&a){var i=63&e[t++];if(192!=(224&a)){var s=63&e[t++];if((a=224==(240&a)?(15&a)<<12|i<<6|s:(7&a)<<18|i<<12|s<<6|63&e[t++])<65536)o+=String.fromCharCode(a);else{var c=a-65536;o+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else o+=String.fromCharCode((31&a)<<6|i)}else o+=String.fromCharCode(a)}return o})(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?m[u(m,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 L[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,L={38180:()=>n.getRandomValue(),38216:()=>{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?o:t;var r=function(){var e=new Uint32Array(1);return t.getRandomValues(e),e[0]>>>0};r(),n.getRandomValue=r}catch(e){try{var o=require("crypto"),a=function(){var e=o.randomBytes(4);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0};a(),n.getRandomValue=a}catch(e){throw"No secure random number generator found"}}}},q={e:(e,t,n,r)=>I(`Assertion failed: ${P(e)}, at: `+[t?P(t):"unknown filename",n,r?P(r):"unknown function"]),g:()=>I(""),c:function(){I("alignment fault")},d:(e,t,n)=>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 o=t*(1+.2/r);o=Math.min(o,e+100663296);var a=Math.min(n,K(Math.max(e,o),65536));if(U(a))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._carrier_aead_xchacha20poly1305_encrypt=e.k,n._carrier_aead_xchacha20poly1305_decrypt=e.l,n._keypair_from_seed=e.m,n._keypair_from_secret_key=e.n,n._sign=e.o,n._verify=e.p,n._get_merkle_root=e.q,n._get_merkle_proof=e.r,n._get_merkle_root_from_proof=e.s,n._verify_merkle_proof=e.t,n._cpace_ristretto255_from_hash=e.u,n._cpace_ristretto255_scalarmult=e.v,n._cpace_ristretto255_scalar_random=e.w,n._x25519_keypair=e.x,n._x25519_dh=e.y,n._hkdf_sha512_extract=e.z,n._hkdf_sha512_expand=e.A,n._encrypt_chachapoly_symmetric=e.B,n._decrypt_chachapoly_symmetric=e.C,n._receive_message_with_key=e.D,n._sha512_init=e.E,n._sha512_update=e.F,n._sha512_final=e.G,n._mlkem512_keypair=e.H,n._mlkem512_encaps=e.I,n._mlkem512_decaps=e.J,n._fips202_shake256=e.K,n._fips202_sha3_256=e.L,n._mlkem768_keypair=e.M,n._mlkem768_encaps=e.N,n._mlkem768_decaps=e.O,n._mlkem1024_keypair=e.P,n._mlkem1024_encaps=e.Q,n._mlkem1024_decaps=e.R,n._free=e.S,n._malloc=e.T,_=e.U,D=e.V,e.__indirect_function_table}(T=e.exports),T}var t={a:q};h??=S();var r=function(t){return e(t.instance)}(await A(c,h,t));return r}(),await async function(){d||(v=!0,T.h())}(),n});e.exports=n,e.exports.default=n}(Io)),Io.exports),Co=vo(So);const Ao=new Uint32Array(1),Eo=()=>{const e=globalThis.crypto;if("function"!=typeof e?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");try{return e.getRandomValues(Ao),Ao[0]>>>0}finally{Ao[0]=0}},Po=(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 xo="0.14.7";let Ro=new URL(`https://cdn.p2party.com/@${xo}/libcrypto.wasm`),Mo=!1;const Ko={integrity:"sha384-K0QqktkF2/8IHMDEgDIcyDl/ywcUXUO8fF1ZzcwhVrUYfGn8jN8Foohn1+bw4HmZ"},Uo=e=>{if(Mo)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:");Ro=t},_o=async e=>{Mo=!0;const t=await(async()=>{const e=await fetch(Ro,Ko);if(!e.ok)throw new Error(`Unable to load p2party ${xo} WASM: HTTP ${String(e.status)}`);return await e.arrayBuffer()})();return await Co({wasmBinary:t,wasmMemory:e,getRandomValue:Eo})},Do=(e,t)=>{t.fill(0),e._free(t.byteOffset)},To=async e=>{const t=e?.wasmMemory??uo(),n=e??await _o(t),r=n._malloc(v),o=new Uint8Array(t.buffer,r,v),a=n._malloc(k),i=new Uint8Array(t.buffer,a,k),s=n._malloc(b),c=new Uint8Array(t.buffer,s,b);try{Po(c);if(0!==n._keypair_from_seed(o.byteOffset,i.byteOffset,c.byteOffset))throw new Error("An unexpected error occured.");return{publicKey:Uint8Array.from(o),secretKey:Uint8Array.from(i)}}finally{n._free(r),Do(n,i),Do(n,c)}},Lo=async(e,t)=>{const n=t?.wasmMemory??fo(),r=t??await _o(n),o=r._malloc(v),a=new Uint8Array(n.buffer,o,v),i=r._malloc(k),s=new Uint8Array(n.buffer,i,k),c=r._malloc(b),l=new Uint8Array(n.buffer,c,b);l.set(e);const d=r._keypair_from_seed(a.byteOffset,s.byteOffset,l.byteOffset);if(Do(r,l),0===d){const e={publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(s)};return r._free(o),Do(r,s),e}throw r._free(o),Do(r,s),new Error("An unexpected error occured.")},qo=async(e,t,n)=>{if(t.length!==k)throw new Error(`Ed25519 secret key must be ${String(k)} bytes`);const r=e.length,o=n?n.wasmMemory:mo(r),a=n??await _o(o),i=a._malloc(Math.max(r*Uint8Array.BYTES_PER_ELEMENT,1)),s=new Uint8Array(o.buffer,i,r*Uint8Array.BYTES_PER_ELEMENT);s.set(e);const c=a._malloc(w),l=new Uint8Array(o.buffer,c,w),d=a._malloc(k),u=new Uint8Array(o.buffer,d,k);u.set(t);try{if(0!==a._sign(r,s.byteOffset,u.byteOffset,l.byteOffset))throw new Error("Could not sign with Ed25519");return Uint8Array.from(l)}finally{a._free(i),a._free(c),Do(a,u)}},Oo=async(e,t,n,r)=>{const o=e.length,a=r?r.wasmMemory:po(o),i=r??await _o(a),s=i._malloc(o*Uint8Array.BYTES_PER_ELEMENT),c=new Uint8Array(a.buffer,s,o*Uint8Array.BYTES_PER_ELEMENT);c.set(e);const l=i._malloc(w),d=new Uint8Array(a.buffer,l,w);d.set(t);const u=i._malloc(v),h=new Uint8Array(a.buffer,u,v);h.set(n);const f=i._verify(o,c.byteOffset,h.byteOffset,d.byteOffset);return i._free(s),i._free(l),i._free(u),0===f},No=/^[0-9a-f]{64}$/,Bo=e=>"string"==typeof e&&No.test(e),Fo=(e,t="Ed25519 identity")=>{if(!Bo(e))throw new Error(`${t} must be 32-byte lowercase hexadecimal`)},jo=(e,t)=>{if(Fo(e,"Self Ed25519 identity"),Fo(t,"Peer Ed25519 identity"),e===t)throw new Error("Cannot assign a protocol role to the same Ed25519 identity");return e<t},zo=e=>"number"==typeof e&&Number.isInteger(e)&&4===e,$o=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ho=(e,t)=>{const n=Object.keys(e);return n.length===t.length&&n.every(e=>t.includes(e))},Vo=/^[0-9a-f]{64}$/,Wo=new Set(["type","roomId","roomUrl","roomRequestId","protocolVersion","turnCredentials"]),Qo=["type","roomId","roomUrl","roomRequestId","protocolVersion"],Go=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Xo=(t,n,r,o,a=Date.now())=>{if(!Go(t)||!(e=>Object.keys(e).every(e=>Wo.has(e))&&Qo.every(t=>Object.prototype.hasOwnProperty.call(e,t)))(t))return{accepted:!1,reason:"malformed-room-response"};const i=t;if(!("roomId"===i.type&&zo(i.protocolVersion)&&e.isUUID(i.roomId,4)&&Vo.test(i.roomUrl)&&e.isUUID(i.roomRequestId,4)&&i.roomUrl===r.roomUrl&&i.roomRequestId===r.roomRequestId))return{accepted:!1,reason:"malformed-room-response"};const s=n.find(e=>e.url===i.roomUrl);if(!s||!1===s.signalingActive)return{accepted:!1,reason:"unknown-room"};if(e.isUUID(s.id)&&s.id!==i.roomId)return{accepted:!1,reason:"room-id-reassignment"};if(n.some(e=>e.url!==i.roomUrl&&e.id===i.roomId))return{accepted:!1,reason:"room-id-collision"};if(r.requestGeneration<=(s.roomResponseGeneration??0))return{accepted:!1,reason:"stale-room-response"};const c=void 0===i.turnCredentials?null:((e,t=Date.now(),n)=>{if(!$o(e))return null;if(!Ho(e,["urls","username","credential","expiresAtUnixSeconds"]))return null;const r=Math.floor(t/1e3);if(!Array.isArray(e.urls)||0===e.urls.length||e.urls.length>16||!e.urls.every(e=>"string"==typeof e&&e.length>0&&e.length<=2048&&/^turns?:[^\s]+$/u.test(e))||new Set(e.urls).size!==e.urls.length||"string"!=typeof e.username||0===e.username.length||e.username.length>256||"string"!=typeof e.credential||0===e.credential.length||e.credential.length>256||"number"!=typeof e.expiresAtUnixSeconds||!Number.isSafeInteger(e.expiresAtUnixSeconds)||e.expiresAtUnixSeconds<r+30||e.expiresAtUnixSeconds>r+86400)return null;const o=/^([1-9][0-9]{0,10}):([0-9a-f]{64})$/u.exec(e.username);return null===o||Number(o[1])!==e.expiresAtUnixSeconds||void 0!==n&&o[2]!==n?null:{urls:[...e.urls],username:e.username,credential:e.credential,expiresAtUnixSeconds:e.expiresAtUnixSeconds}})(i.turnCredentials,a,o);return void 0!==i.turnCredentials&&null===c?{accepted:!1,reason:"malformed-turn-credentials"}:{accepted:!0,action:He({roomId:i.roomId,roomUrl:i.roomUrl,roomRequestId:i.roomRequestId,requestGeneration:r.requestGeneration,turnCredentials:c}),roomId:i.roomId,roomUrl:i.roomUrl,roomRequestId:i.roomRequestId,requestGeneration:r.requestGeneration,expiresAtUnixSeconds:c?.expiresAtUnixSeconds??null,nextRtcConfig:qe(s.callerRtcConfig??s.rtcConfig,c)}},Jo=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Yo=e=>Jo.test(e),Zo=()=>{const e=globalThis.crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=[...e].map(e=>e.toString(16).padStart(2,"0")).join("");return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20)].join("-")},ea=new Map;let ta=null;const na=new Map,ra=new Map,oa=new Map;let aa=1,ia=1;const sa=/^[0-9a-f]{64}$/,ca=e=>new Error(`roomRequest: ${e}`),la=(e,t,n,r={})=>{const o=ea.get(t);if(o)return o.promise;if(ea.size>=256)return Promise.reject(ca("pending room request bound is exhausted"));const a=((e,t)=>{if(!Yo(e))throw ca("peerId must be a UUIDv4");if(!sa.test(t))throw ca("roomUrl must be 32-byte lowercase hex");return{type:"room",fromPeerId:e,roomUrl:t,roomRequestId:Zo(),protocolVersion:4}})(e,t),i=aa++;let s,c;Number.isSafeInteger(aa)||(aa=1);const l=new Promise((e,t)=>{s=e,c=t}),d=r.timeoutMs??15e3,u=setTimeout(()=>{const e=ea.get(t);e?.roomRequestId===a.roomRequestId&&e.requestGeneration===i&&(ea.delete(t),e.reject(ca("room response timed out")))},d),h={roomUrl:t,roomRequestId:a.roomRequestId,requestGeneration:i,promise:l,resolve:s,reject:c,timeout:u,claimed:!1};ea.set(t,h);try{Promise.resolve(n(a)).catch(e=>{da(t,a.roomRequestId,e instanceof Error?e:ca(String(e)))})}catch(e){da(t,a.roomRequestId,e instanceof Error?e:ca(String(e)))}return l},da=(e,t,n)=>{const r=ea.get(e);return!(!r||r.roomRequestId!==t)&&(clearTimeout(r.timeout),ea.delete(e),r.reject(n),!0)},ua=e=>e===ia,ha=(e,t,n)=>{if(t!==ia)return Promise.reject(ca("room retry lifecycle is stale"));const r=na.get(e);if(r){if(r.lifecycleEpoch===t)return r.promise;clearTimeout(r.timeout),r.reject(ca("room retry lifecycle was replaced")),na.delete(e)}if(na.size>=256)return Promise.reject(ca("room retry waiter bound is exhausted"));let o,a;const i=new Promise((e,t)=>{o=e,a=t}),s=setTimeout(()=>{const n=na.get(e);n?.lifecycleEpoch===t&&n.promise===i&&(na.delete(e),t!==ia?a(ca("room retry lifecycle is stale")):o())},Math.max(0,n));return na.set(e,{lifecycleEpoch:t,promise:i,resolve:o,reject:a,timeout:s}),i},fa=(e,t,n,r=()=>{},o={},a=Symbol(e))=>{if(oa.has(e))throw ca("room refresh slot is reserved");if(!ma(e,t))throw ca("room refresh timer bound is exhausted");if(pa(e),null===t)return;const i={token:a,expiresAtUnixSeconds:t,refresh:n,expire:r,attempt:0},s=o.now??Date.now,c=async()=>{if(ra.get(e)===i){ra.delete(e);try{await r()}catch(e){console.warn("p2party: failed to remove expired TURN credentials",e instanceof Error?e.message:String(e))}}},l=async()=>{if(ra.get(e)!==i)return;if(1e3*t-s()<=0)await c();else try{if(await n(),ra.get(e)!==i)return;const r=1e3*t-s();if(r<=0)return void await c();i.timeout=setTimeout(()=>{l()},r)}catch(n){if(ra.get(e)!==i)return;const r=1e3*t-s();if(r<=0)return void await c();i.attempt+=1;const a=((e,t,n={})=>{if(e>(n.maxAttempts??8))return t;const r=n.retryBaseMs??1e3,o=n.maxRetryMs??3e4;return Math.min(o,r*2**Math.max(0,e-1),t)})(i.attempt,r,o);i.timeout=setTimeout(()=>{l()},a),console.warn(i.attempt<=(o.maxAttempts??8)?"p2party: scheduled TURN refresh failed; retrying":"p2party: TURN refresh retries exhausted; credentials will be removed at expiry",n instanceof Error?n.message:String(n))}};i.timeout=setTimeout(()=>{l()},((e,t=Date.now(),n=1e3)=>{const r=1e3*e;return Math.max(n,r-3e5-t)})(t,o.nowMs,o.minimumInitialDelayMs)),ra.set(e,i)};function ma(e,t){if(null===t||ra.has(e))return!0;let n=0;for(const[e,t]of oa)null===t.expiresAtUnixSeconds||ra.has(e)||(n+=1);return ra.size+n<K||oa.has(e)}const pa=e=>{const t=ra.get(e);t?.timeout&&clearTimeout(t.timeout),ra.delete(e),oa.delete(e)},ya=(e,t="room lifecycle was cancelled")=>{const n=ca(t);pa(e);const r=ea.get(e);r&&(clearTimeout(r.timeout),ea.delete(e),r.reject(n)),((e,t)=>{const n=na.get(e);n&&(clearTimeout(n.timeout),na.delete(e),n.reject(t))})(e,n)},ga=(e="signaling socket disconnected")=>{const t=ca(e);ia+=1,Number.isSafeInteger(ia)||(ia=1);for(const e of ea.values())clearTimeout(e.timeout),e.reject(t);ea.clear();for(const e of ra.values())e.timeout&&clearTimeout(e.timeout),Promise.resolve(e.expire()).catch(e=>{console.warn("p2party: failed to clear TURN credentials on signaling teardown",e instanceof Error?e.message:String(e))});ra.clear(),oa.clear();for(const[e,n]of na)clearTimeout(n.timeout),na.delete(e),n.reject(t);(e=>{const t=ta;t&&(ta=null,clearTimeout(t.timeout),t.reject(e))})(t)},wa=(t,n,r)=>{const{keyPair:o,rooms:a,signalingServer:i}=t.getState(),s=a.find(e=>e.url===n);return s&&!1!==s.signalingActive&&i.isConnected&&i.isVerified&&e.isUUID(o.peerId,4)?la(o.peerId,n,r):Promise.reject(new Error("roomRequest: signaling proof or active room is unavailable"))},ba=async(e,t,n,r={})=>{const o=r.lifecycleEpoch??ia,a=r.maxAttempts??4,i=r.retryBaseMs??250,s=r.maxRetryMs??2e3;let c=0;for(;;){if(!ua(o))throw new Error("roomRequest: room retry lifecycle is stale");try{return await wa(e,t,n)}catch(e){if(c+=1,c>=a||!ua(o))throw e;const n=Math.min(s,i*2**Math.max(0,c-1));await ha(t,o,n)}}},va=async(e,t,n={})=>{const{rooms:r}=e.getState(),o=r.filter(e=>!1!==e.signalingActive).map(e=>e.url).sort(),a=Number.isSafeInteger(n.concurrency)&&(n.concurrency??0)>0?n.concurrency:16,i=Math.max(1,Math.min(o.length||1,a)),s=[];let c=0;if(await Promise.all(Array.from({length:i},()=>(async()=>{for(;c<o.length;){const r=o[c++];try{await ba(e,r,t,n)}catch(e){s.push(e)}}})())),s.length>0)throw new AggregateError(s,`${String(s.length)} active room refresh(es) failed`)},ka=Object.getPrototypeOf(Uint8Array.prototype),Ia=Object.getOwnPropertyDescriptor(ka,"length")?.get,Sa=Uint8Array.prototype.set,Ca=(e,t)=>void 0!==t.exactLength?new RangeError(`${e} must be exactly ${String(t.exactLength)} bytes`):new RangeError(`${e} exceeds the supported length`),Aa=(e,t,n)=>{if(void 0!==n&&(!Number.isSafeInteger(n)||n<0))throw new RangeError(`${e} ${t} must be a non-negative safe integer`)},Ea=(e,t)=>{if(void 0===Ia)throw new Error(`${t}: Uint8Array length intrinsic is unavailable`);const n=Reflect.apply(Ia,e,[]);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(`${t} has an invalid length`);return n},Pa=(e,t,n={})=>{if(!(ArrayBuffer.isView(e)&&e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(Aa(t,"exactLength",n.exactLength),Aa(t,"maximumLength",n.maximumLength),void 0!==n.exactLength&&void 0!==n.maximumLength&&n.exactLength>n.maximumLength)throw new RangeError(`${t} exactLength cannot exceed maximumLength`);const r=Ea(e,t),o=n.exactLength??n.maximumLength;if(void 0!==o&&r>o)throw Ca(t,n);const a=new Uint8Array(r);try{Reflect.apply(Sa,a,[e])}catch{throw a.fill(0),new RangeError(`${t} changed while it was being copied`)}try{return((e,t,n)=>{const r=Ea(e,t);if(void 0!==n.exactLength&&r!==n.exactLength||void 0!==n.maximumLength&&r>n.maximumLength)throw Ca(t,n)})(a,t,n),a}catch(e){throw a.fill(0),e}},xa=e=>{e.secretKey.fill(0)},Ra=(e,t)=>{if(e.byteLength!==t.byteLength)return!1;let n=0;for(let r=0;r<e.byteLength;r++)n|=e[r]^t[r];return 0===n},Ma=e=>{if("object"!=typeof e||null===e||Array.isArray(e))throw new Error("Ed25519 identity is malformed");return e},Ka=e=>{if("bigint"!=typeof e||e<1n||e>18446744073709551615n)throw new Error("Ed25519 identity revision must be a non-zero uint64");return e},Ua=async e=>{const t=Ma(e),n=t.pub,r=t.secret;if(!(n instanceof ArrayBuffer&&r instanceof ArrayBuffer&&32===n.byteLength&&64===r.byteLength))throw new Error("Ed25519 identity has invalid key lengths");const o=Uint8Array.from(new Uint8Array(n)),a=await(async e=>{let t,n,r=!1;try{if(t=Pa(e.secretKey,e.inputLabel,{exactLength:k}),e.validateBeforeDerivation?.(),n=await Lo(t.subarray(0,b),e.module),!Ra(n.secretKey,t))return e.rejectInconsistentSecretKey();const o={secretKey:t,publicKey:Uint8Array.from(n.publicKey)};return r=!0,o}finally{n?.secretKey.fill(0),r||t?.fill(0)}})({secretKey:new Uint8Array(r),inputLabel:"db: Ed25519 identity secret key",rejectInconsistentSecretKey:()=>{throw new Error("Ed25519 secret key is inconsistent with its seed")}});if(!((e,t)=>{if(e.byteLength!==t.byteLength)return!1;let n=0;for(let r=0;r<e.byteLength;r++)n|=e[r]^t[r];return 0===n})(o,a.publicKey))throw xa(a),new Error("Ed25519 public key does not match the secret key");return{input:{pub:n,secret:r},material:a}},_a=e=>{if("object"!=typeof e||null===e)return;const t=Object.getOwnPropertyDescriptor(e,"secret");t&&"value"in t&&t.value instanceof ArrayBuffer&&0!==t.value.byteLength&&new Uint8Array(t.value).fill(0)},Da='const e=(e,t)=>t.some(t=>e instanceof t);let t,n;const a=new WeakMap,r=new WeakMap,o=new WeakMap;let i={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return a.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return d(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function s(e){i=e(i)}function c(e){return(n||(n=[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(n){return"function"==typeof n?c(n):(n instanceof IDBTransaction&&function(e){if(a.has(e))return;const t=new Promise((t,n)=>{const a=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",o),e.removeEventListener("abort",o)},r=()=>{t(),a()},o=()=>{n(e.error||new DOMException("AbortError","AbortError")),a()};e.addEventListener("complete",r),e.addEventListener("error",o),e.addEventListener("abort",o)});a.set(e,t)}(n),e(n,t||(t=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(n,i):n)}function d(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,n)=>{const a=()=>{e.removeEventListener("success",r),e.removeEventListener("error",o)},r=()=>{t(d(e.result)),a()},o=()=>{n(e.error),a()};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 y=["get","getKey","getAll","getAllKeys","count"],w=["put","add","delete","clear"],h=new Map;function f(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(h.get(t))return h.get(t);const n=t.replace(/FromIndex$/,""),a=t!==n,r=w.includes(n);if(!(n in(a?IDBIndex:IDBObjectStore).prototype)||!r&&!y.includes(n))return;const o=async function(e,...t){const o=this.transaction(e,r?"readwrite":"readonly");let i=o.store;return a&&(i=i.index(t.shift())),(await Promise.all([i[n](...t),r&&o.done]))[0]};return h.set(t,o),o}s(e=>({...e,get:(t,n,a)=>f(t,n)||e.get(t,n,a),has:(t,n)=>!!f(t,n)||e.has(t,n)}));const g=["continue","continuePrimaryKey","advance"],m={},p=new WeakMap,b=new WeakMap,k={get(e,t){if(!g.includes(t))return e[t];let n=m[t];return n||(n=m[t]=function(...e){p.set(this,b.get(this)[t](...e))}),n}};async function*S(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,k);for(b.set(n,t),o.set(n,u(t));t;)yield n,t=await(p.get(n)||t.continue()),p.delete(n)}function I(t,n){return n===Symbol.asyncIterator&&e(t,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===n&&e(t,[IDBIndex,IDBObjectStore])}s(e=>({...e,get:(t,n,a)=>I(t,n)?S:e.get(t,n,a),has:(t,n)=>I(t,n)||e.has(t,n)}));const v=64*Uint8Array.BYTES_PER_ELEMENT,x=65405-(9+v+8+8+256+8+8+8+(4+48*(v+1)));(new TextEncoder).encode("p2party-x25519-idsig-v1");const K=["hybrid-3dh-mlkem512-cpace21-v4","hybrid-3dh-mlkem768-cpace21-v4","hybrid-3dh-mlkem1024-cpace21-v4"],A="p2party-reassembled",R="p2party";async function C(){return function(e,t,{blocked:n,upgrade:a,blocking:r,terminated:o}={}){const i=indexedDB.open(e,t),s=d(i);return a&&i.addEventListener("upgradeneeded",e=>{a(d(i.result),e.oldVersion,e.newVersion,d(i.transaction),e)}),n&&i.addEventListener("blocked",e=>n(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,n,a){if(e.objectStoreNames.contains("addressBook")){const e=a.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=a.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=a.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=a.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=a.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=a.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=a.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&&(a.objectStore("ratchetSessions").clear(),a.objectStore("sendQueue").clear()),e.objectStoreNames.contains("meta")||e.createObjectStore("meta")}})}const P="ratchetWrapKey",D=12,E=16,L=16,B=Uint8Array.of(80,50,82,87),j=B.byteLength+1+L+D,M=262144,U=(new TextEncoder).encode("p2party-edge-crypto-at-rest-aad-v2");var N;!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"}(N||(N={}));const q=e=>e.slice(0),$=(e,t,n)=>{if(!(e instanceof ArrayBuffer))throw new Error(`${t} must be an ArrayBuffer`);if(void 0!==n&&e.byteLength!==n)throw new Error(`${t} must be ${String(n)} 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 n=(new TextEncoder).encode(e);if(n.byteLength>1048576)throw new Error(`${t} is too long`);if((new TextDecoder).decode(n)!==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},O=e=>{T(e,"ratchet wrap counter");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t},H=e=>{const t=e.reduce((e,t)=>e+t.byteLength,0),n=new Uint8Array(t);let a=0;for(const t of e)n.set(t,a),a+=t.byteLength;return n},Q=e=>H([F(e.byteLength),e]),V=e=>Q((new TextEncoder).encode(e)),W=e=>{const t=e.rootSuite;if("string"!=typeof(n=t)||!K.includes(n))throw new Error("Unsupported ratchet root suite");var n;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,n,a=0)=>{if(W(e),n.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(U),Uint8Array.of(2,t),Q(n),F(a),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(O(e.Ns),O(e.Nr),O(e.PN),O(e.updatedAt),F(e.skippedMessageKeys.length));for(const t of e.skippedMessageKeys)o.push(Q(new Uint8Array(t.dhPub)),O(t.n));return H(o)},Y=(e,t=32)=>{const n=new Uint8Array(e),a=j+1+E,r=j+M+E;if(null===t&&(n.byteLength<a||n.byteLength>r)||null!==t&&n.byteLength!==j+t+E)throw new Error("Unsupported or malformed ratchet wrap envelope");for(let e=0;e<B.byteLength;e++)if(n[e]!==B[e])throw new Error("Unsupported or malformed ratchet wrap envelope");if(2!==n[B.byteLength])throw new Error("Unsupported or malformed ratchet wrap envelope");return Uint8Array.from(n.subarray(B.byteLength+1,B.byteLength+1+L))},J=async(e,t,n,a,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(a.byteLength!==L)throw new Error("ratchet wrap: invalid record ID");const o=crypto.getRandomValues(new Uint8Array(D)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:n,tagLength:128},e,t),s=new Uint8Array(j+i.byteLength);return s.set(B,0),s[B.byteLength]=2,s.set(a,B.byteLength+1),s.set(o,B.byteLength+1+L),s.set(new Uint8Array(i),j),s.buffer},Z=async(e,t,n,a,r=32)=>{$(t,"ratchet wrapped secret");const o=Y(t,r);if(!te(o,a))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:n,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),n=[e.sendingChainKey,e.receivingChainKey,e.dhSelfSec,...e.skippedMessageKeys.map(e=>e.messageKey)];for(const e of n)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 a=[_(e,N.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)a.push(Q(new Uint8Array(t.messageKey)));a.push(Q(e.edgeCryptoState?new Uint8Array(e.edgeCryptoState):new Uint8Array));const r=H(a);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 n=0;for(let a=0;a<e.byteLength;a++)n|=e[a]^t[a];return 0===n};async function ne(){const e=await C();try{const t=await e.get("meta",P);if(t)return t;const n=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),a=e.transaction("meta","readwrite"),r=a.objectStore("meta"),o=await r.get(P);return o?(await a.done,o):(await r.put(n,P),await a.done,n)}finally{e.close()}}async function ae(e,t){const n=crypto.getRandomValues(new Uint8Array(D)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},e,t),r=new Uint8Array(D+a.byteLength);return r.set(n,0),r.set(new Uint8Array(a),D),r.buffer}async function re(e,t){const n=new Uint8Array(t);if(n.byteLength<28)throw new Error("Malformed wrapped secret");return crypto.subtle.decrypt({name:"AES-GCM",iv:n.subarray(0,D)},e,n.subarray(D))}const oe=()=>globalThis.navigator?.storage,ie=new Map,se=e=>e.createSyncAccessHandle,ce=(e,t,n,a)=>new File([e],t.length>0?t:n,{type:a});async function le(e,t,n,a){if(e.length!==2*v)return null;const r=ie.get(e);if(r)return r;const o=async function(e,t,n,a){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(A,{create:!0}),s=await i.getFileHandle(e,{create:!0}),c=await s.getFile();if(t>0&&c.size===t)return ce(c,n,e,a);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 C(),d.truncate(0);let t=0;const n=u.transaction("chunks","readonly"),a=n.objectStore("chunks").index("merkleRoot");let r=await a.openCursor(e);for(;r;){const e=new Uint8Array(r.value.data??new ArrayBuffer(0));let n=0;for(;n<e.length;){const a=d.write(e.subarray(n),{at:t+n});if(a<=0)throw new Error("OPFS short write");n+=a}t+=e.length,r=await r.continue()}await n.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(),n,e,a)}catch(e){return console.error(e),null}}(e,t,n,a);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 n=await t.getDirectory(),a=await n.getDirectoryHandle(A).catch(()=>null);a&&await a.removeEntry(e).catch(()=>{})}catch{}}const ue=new Map,ye=new Map,we=new Map,he=new Map;async function fe(e,t){const n=he.get(e)??Promise.resolve();let a;const r=new Promise(e=>{a=e}),o=n.then(()=>r);he.set(e,o),await n;try{return await t()}finally{a(),he.get(e)===o&&he.delete(e)}}async function ge(e,t){const n=ue.get(e);if(n)return n;const a=ye.get(e);if(a)return a;if(ue.size>=8)for(const t of ue.keys())if(t!==e){await be(t);break}const r=async function(e,t){const n=oe();if(!n||"function"!=typeof n.getDirectory)return null;const a=await n.getDirectory(),r=await a.getDirectoryHandle(A,{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));ye.set(e,r);try{const t=await r;return t&&ue.set(e,t),t}finally{ye.delete(e)}}function me(e,t,n){const a=new Uint8Array(n);let r=0;for(;r<a.length;){const n=e.write(a.subarray(r),{at:t+r});if(n<=0)throw new Error("OPFS short write");r+=n}}async function pe(e){const{schemaVersion:t,roomId:n,fromPeerId:a,channelLabel:r,timestamp:o,merkleRoot:i,hash:s,filename:c,messageType:l,chunkIndex:d,mimeType:u,leafHash:y,realLen:w,totalSize:h,data:f,storage:g}=e;if(1!==t||!Number.isSafeInteger(l)||l<1||l>64||!Number.isSafeInteger(d)||d<0||!Number.isSafeInteger(w)||w<=0||w>x||!Number.isSafeInteger(h)||h<=0||h>10737418240||w>h||d>=h||f.byteLength!==w||!Number.isSafeInteger(o))throw new Error("invalid receive chunk bounds");const m=e=>{if(e&&(e.roomId!==n||e.fromPeerId!==a||e.hash!==s||e.totalSize!==h||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 n=0;for(let e=0;e<t.length;e++){const a=t[e];if(!Number.isSafeInteger(a.chunkIndex)||a.chunkIndex<0||!Number.isSafeInteger(a.realLen)||a.realLen<=0||a.realLen>x||a.realLen>h||a.chunkIndex>=h||e>0&&t[e-1].chunkIndex===a.chunkIndex)throw new Error("invalid receive chunk layout");if(n+=a.realLen,!Number.isSafeInteger(n)||n>h)throw new Error("receive chunks exceed declared total")}const a=t.find(e=>0===e.chunkIndex);let r;if(a)r=a.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(h/r),a=e-1,o=h-r*a;for(const n of t){if(n.chunkIndex>=e)throw new Error("receive chunk index exceeds canonical manifest");const t=n.chunkIndex===a?o:r;if(n.realLen!==t)throw new Error("receive chunk length conflicts with manifest")}const i=n===h&&t.length===e&&t.every((e,t)=>e.chunkIndex===t);if(n===h&&!i)throw new Error("receive completion has a chunk-index gap");return{savedSize:n,complete:i}}if(n===h)throw new Error("receive completion is missing chunk zero");return{savedSize:n,complete:!1}},b=await C();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 C();try{const t=e.transaction(["chunks","messageData"],"readonly"),n=t.objectStore("chunks").index("merkleRoot"),a=[];let r=await n.openCursor(i);for(;r;)a.push(r.value),r=await r.continue();m(await t.objectStore("messageData").index("merkleRoot").get(i));const o=p(a);return await t.done,{stored:!1,...o}}finally{e.close()}}const S=await C();try{const e=S.transaction(["chunks","messageData"],"readonly"),t=[];let n=await e.objectStore("chunks").index("merkleRoot").openCursor(i);for(;n;)t.push(n.value),n=await n.continue();m(await e.objectStore("messageData").index("merkleRoot").get(i)),p([...t,{chunkIndex:d,realLen:w}]),await e.done}finally{S.close()}let I=!1;if("opfs"===g)try{I=await async function(e,t,n,a,r){const o=await ge(e,a);if(!o)return!1;if(o.maxRealLen=Math.max(o.maxRealLen,n),o.seenCount+=1,o.uniformKnown||(0===t?(n<a&&(o.uniformSize=n),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,w,h,f)}catch(e){console.error(e),I=!1}const v="opfs"===g&&I?{merkleRoot:i,hash:s,chunkIndex:d,mimeType:u,realLen:w,leafHash:y}:{merkleRoot:i,hash:s,chunkIndex:d,mimeType:u,realLen:w,leafHash:y,data:f},K=await C();try{const e=K.transaction(["chunks","messageData","uniqueRoom"],"readwrite"),t=e.objectStore("chunks"),u=await t.getKey([i,d]);let y=!1;const f=[];let g=await t.index("merkleRoot").openCursor(i);for(;g;)f.push(g.value),g=await g.continue();void 0===u&&(p([...f,{chunkIndex:d,realLen:w}]),await t.add(v),f.push(v),y=!0);const b=p(f);if(y){const t=e.objectStore("messageData"),d=await t.index("merkleRoot").get(i);m(d),await t.put({roomId:n,timestamp:d?.timestamp??o,merkleRoot:i,hash:s,fromPeerId:a,filename:c,messageType:l,savedSize:b.savedSize,totalSize:h,channelLabel:r});const u=e.objectStore("uniqueRoom"),y=await u.index("roomId").get(n);y&&y.lastMessageMerkleRoot!==i&&await u.put({...y,lastMessageMerkleRoot:i,messageCount:y.messageCount+1,updatedAt:o})}return await e.done,{stored:y,...b}}finally{K.close()}}async function be(e){const t=ye.get(e);if(t)try{await t}catch{}const n=ue.get(e);if(n){ue.delete(e);try{n.access.flush(),n.access.close()}catch{}}}async function ke(e,t,n,a){if(e.length!==2*v)return null;await be(e);const r=we.get(e);if(r)return r;const o=async function(e,t,n,a){try{const r=oe();if(!r||"function"!=typeof r.getDirectory)return null;const o=await r.getDirectory(),i=await o.getDirectoryHandle(A,{create:!0}),s=await i.getFileHandle(e,{create:!0}),c=await C(),l=[];let d=0;try{const t=c.transaction("chunks","readonly"),n=t.objectStore("chunks").index("merkleRoot");let a=await n.openCursor(e);for(;a;){const e=a.value;e.realLen&&e.realLen>d&&(d=e.realLen),e.data&&e.data.byteLength>0&&l.push(e),a=await a.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,n,e,a);if(l.length>0&&(0===d||l.some(e=>null==e.realLen)))return c.close(),null;const y=se(s);if("function"!=typeof y)return c.close(),null;const w=await y.call(s);try{t>0&&w.getSize()!==t&&w.truncate(t);for(let e=0;e<l.length;e++){const t=l[e];me(w,0===t.chunkIndex?0:t.chunkIndex*d,t.data)}w.flush()}finally{w.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 n=l[e];await t.put({merkleRoot:n.merkleRoot,hash:n.hash,chunkIndex:n.chunkIndex,mimeType:n.mimeType,realLen:n.realLen,leafHash:n.leafHash})}await e.done}catch(e){console.error(e)}c.close();const h=await s.getFile();return t>0&&h.size!==t?null:ce(h,n,e,a)}catch(e){return console.error(e),null}}(e,t,n,a);we.set(e,o);try{return await o}finally{we.delete(e)}}const Se=new class{#e=new Map;#t(e,t){const n=(e=>`${String(e.roomId.length)}:${e.roomId}${String(e.peerPublicKey.length)}:${e.peerPublicKey}`)(e),a=this.#e.get(n);if(a&&e.updatedAt<a.updatedAt)throw t.fill(0),new Error("Ratchet persistence rollback detected");if(e.updatedAt===a?.updatedAt&&!te(t,a.fingerprint))throw t.fill(0),new Error("Ratchet persistence equivocation detected");!a||e.updatedAt>a.updatedAt?(a?.fingerprint.fill(0),this.#e.set(n,{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 n=`${String(e.length)}:${e}${String(t.length)}:${t}`;this.#e.get(n)?.fingerprint.fill(0),this.#e.delete(n)}clear(){for(const e of this.#e.values())e.fingerprint.fill(0);this.#e.clear()}},Ie=new Map,ve=new Map,xe=(e,t)=>`${String(e.length)}:${e}${String(t.length)}:${t}`,Ke=async(e,t,n)=>{const a=xe(e,t),r=ve.get(a)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=r.catch(()=>{}).then(()=>i);ve.set(a,s),await r.catch(()=>{});try{return await n()}finally{o(),ve.get(a)===s&&ve.delete(a)}};async function Ae(e,t){return Ke(e,t,async()=>{try{const n=await C();let a;try{a=await n.get("ratchetSessions",[e,t])}finally{n.close()}if(!a)return;const r=await ne(),o=await async function(e,t,n){const a=X(e);W(a);const r=[];try{const e=Y(a.rootKey),o=await Z(t,a.rootKey,_(a,N.RootKey,e),e);r.push(o);const i=a.sendingChainKey?await Z(t,a.sendingChainKey,_(a,N.SendingChainKey,e),e):null;i&&r.push(i);const s=a.receivingChainKey?await Z(t,a.receivingChainKey,_(a,N.ReceivingChainKey,e),e):null;s&&r.push(s);const c=await Z(t,a.dhSelfSec,_(a,N.DhSelfSecret,e),e);r.push(c);const l=[];for(let n=0;n<a.skippedMessageKeys.length;n++){const o=a.skippedMessageKeys[n],i=await Z(t,o.messageKey,_(a,N.SkippedMessageKey,e,n),e);r.push(i),l.push({dhPub:o.dhPub,n:o.n,messageKey:i})}const d=a.edgeCryptoState?await Z(t,a.edgeCryptoState,_(a,N.EdgeCryptoState,e),e,null):null;return d&&r.push(d),n&&await n.acceptAuthenticated(a),{...a,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(a)}}(a,r,Se),i=xe(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 Ke(e.roomId,e.peerPublicKey,async()=>{const t=xe(e.roomId,e.peerPublicKey),n=Ie.get(t)??0,a=Math.max(Date.now(),e.updatedAt),r=a>n?a:n+1;if(!Number.isSafeInteger(r))throw new Error("Ratchet persistence timestamp exhausted");const o={...e,updatedAt:r};try{const e=await ne(),n=await async function(e,t){const n=X(e);if(W(n),$(n.rootKey,"ratchet rootKey",32),n.sendingChainKey&&$(n.sendingChainKey,"ratchet sendingChainKey",32),n.receivingChainKey&&$(n.receivingChainKey,"ratchet receivingChainKey",32),$(n.dhSelfSec,"ratchet dhSelfSec",32),n.skippedMessageKeys.forEach((e,t)=>$(e.messageKey,`ratchet skipped[${String(t)}].messageKey`,32)),n.edgeCryptoState&&($(n.edgeCryptoState,"ratchet edge crypto state"),n.edgeCryptoState.byteLength<1||n.edgeCryptoState.byteLength>M))throw new Error("ratchet edge crypto state length is invalid");try{const e=crypto.getRandomValues(new Uint8Array(L)),a=await J(t,n.rootKey,_(n,N.RootKey,e),e),r=n.sendingChainKey?await J(t,n.sendingChainKey,_(n,N.SendingChainKey,e),e):null,o=n.receivingChainKey?await J(t,n.receivingChainKey,_(n,N.ReceivingChainKey,e),e):null,i=await J(t,n.dhSelfSec,_(n,N.DhSelfSecret,e),e),s=[];for(let a=0;a<n.skippedMessageKeys.length;a++){const r=n.skippedMessageKeys[a];s.push({dhPub:r.dhPub,n:r.n,messageKey:await J(t,r.messageKey,_(n,N.SkippedMessageKey,e,a),e)})}const c=n.edgeCryptoState?await J(t,n.edgeCryptoState,_(n,N.EdgeCryptoState,e),e,null):null;return{...n,rootKey:a,sendingChainKey:r,receivingChainKey:o,dhSelfSec:i,skippedMessageKeys:s,edgeCryptoState:c}}finally{G(n)}}(o,e),a=await C();try{await a.put("ratchetSessions",n)}finally{a.close()}await Se.rememberTrustedWrite(n),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 Ce=/^[0-9a-f]{64}$/,Pe=(e,t)=>{if("string"!=typeof e||0===e.length)throw new Error("PIN attempt room ID must not be empty");if(void 0!==t&&!Ce.test(t))throw new Error("PIN attempt peer identity must be 32-byte lowercase hexadecimal")},De=e=>`pinAttempts:v2:${e.length}:${e}:`,Ee=(e,t)=>`${De(e)}${t}`;const Le="identityX25519";const Be="identityEd25519",je="identityEd25519Revision",Me=0xffffffffffffffffn,Ue=e=>e.slice(0),Ne=(e,t)=>{if(e.byteLength!==t.byteLength)return!1;const n=new Uint8Array(e),a=new Uint8Array(t);let r=0;for(let e=0;e<n.byteLength;e++)r|=n[e]^a[e];return 0===r},qe=(e,t)=>{if(32!==e.byteLength||64!==t.byteLength)return!1;const n=new Uint8Array(e),a=new Uint8Array(t);let r=0;for(let e=0;e<n.byteLength;e++)r|=n[e]^a[32+e];return 0===r},$e=(e,t,n)=>{if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`${n} is malformed`);const a=Reflect.ownKeys(e);if(a.length!==t.length||a.some(e=>"string"!=typeof e||!t.includes(e)))throw new Error(`${n} is malformed`);for(const a of t){const t=Object.getOwnPropertyDescriptor(e,a);if(!t||!("value"in t))throw new Error(`${n} is malformed`)}return e},Te=(e,t,n)=>{if("bigint"!=typeof e||e<0n||e>Me||!n&&0n===e)throw new Error(`${t} must be a ${n?"":"non-zero "}uint64`);return e},ze=e=>{const t=e.pub,n=e.wrappedSecret;if(!(t instanceof ArrayBuffer)||32!==t.byteLength)throw new Error("Stored Ed25519 public key has an invalid length");if(!(n instanceof ArrayBuffer)||92!==n.byteLength)throw new Error("Stored Ed25519 wrapped secret is malformed");return{pub:t,wrappedSecret:n}},Fe=e=>{if(void 0===e)return;if("object"==typeof e&&null!==e&&Object.prototype.hasOwnProperty.call(e,"version")){const t=$e(e,["version","pub","wrappedSecret","recordRevision"],"Stored Ed25519 identity");if(1!==t.version)throw new Error("Stored Ed25519 identity version is unsupported");return{kind:"current",...ze(t),recordRevision:Te(t.recordRevision,"Stored Ed25519 identity revision",!1)}}const t=$e(e,["pub","wrappedSecret"],"Legacy stored Ed25519 identity");return{kind:"legacy",...ze(t)}},Oe=e=>{if(void 0===e)return;const t=$e(e,["version","lastRevision"],"Ed25519 identity revision record");if(1!==t.version)throw new Error("Ed25519 identity revision version is unsupported");return{version:1,lastRevision:Te(t.lastRevision,"Ed25519 identity high-water revision",!0)}},He=(e,t)=>{if("legacy"===e?.kind&&void 0!==t)throw new Error("Stored Ed25519 identity revision state is inconsistent");if("current"===e?.kind&&(void 0===t||e.recordRevision!==t.lastRevision))throw new Error("Stored Ed25519 identity revision state is inconsistent")},Qe=(e,t)=>"legacy"===e?.kind?1n:t?.lastRevision??0n,Ve=e=>{if(e>=Me)throw new Error("Ed25519 identity revision overflow");return e+1n},We=async e=>{const t=e.transaction("meta","readonly"),n=t.objectStore("meta"),[a,r]=await Promise.all([n.get(Be),n.get(je)]);await t.done;const o=Fe(a),i=Oe(r);return He(o,i),{identity:o,revision:i}},Xe=async(e,t)=>{if("legacy"!==t.identity?.kind||void 0!==t.revision)throw new Error("Legacy Ed25519 migration state is inconsistent");const n=e.transaction("meta","readwrite"),a=n.objectStore("meta"),[r,o]=await Promise.all([a.get(Be),a.get(je)]),i={identity:Fe(r),revision:Oe(o)};return He(i.identity,i.revision),"legacy"===i.identity?.kind&&void 0===i.revision&&Ne(t.identity.pub,i.identity.pub)&&Ne(t.identity.wrappedSecret,i.identity.wrappedSecret)?(await Promise.all([a.put({version:1,pub:Ue(t.identity.pub),wrappedSecret:Ue(t.identity.wrappedSecret),recordRevision:1n},Be),a.put({version:1,lastRevision:1n},je)]),await n.done,!0):(await n.done,!1)};const Ge="identityDerivation",_e=e=>"random"===e||"mnemonic"===e,Ye=e=>{try{return Fe(e)?.pub}catch{return}};async function Je(){const e=await C();let t,n;try{const a=e.transaction("meta","readonly"),r=a.objectStore("meta");[t,n]=await Promise.all([r.get(Ge),r.get(Be)]),await a.done}finally{e.close()}const a=(e=>{if("object"!=typeof e||null===e||Array.isArray(e))return;const t=e;if(1!==t.version)return;if(!_e(t.derivation))return;const n=t.boundPub;return!(null===n||n instanceof ArrayBuffer)||n instanceof ArrayBuffer&&32!==n.byteLength?void 0:{version:1,derivation:t.derivation,boundPub:n}})(t);if(void 0===a)return null;if(null===a.boundPub)return a.derivation;const r=Ye(n);return void 0===r?null:Ne(a.boundPub,r)?a.derivation:null}async function Ze(){try{await async function(){const e=[...ye.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(A,{recursive:!0}).catch(()=>{})}}catch{}await function(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",e=>t(e.oldVersion,e)),d(n).then(()=>{})}(R,{blocked(){console.error("DB deletion BLOCKED")}}),Se.clear(),Ie.clear()}onmessage=async e=>{const t=e.data,{id:n,method:a}=t;try{let e;switch(a){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 n=await C();try{const a=n.transaction("addressBook","readonly"),r=e?a.objectStore("addressBook").index("peerId"):a.objectStore("addressBook").index("peerPublicKey"),o=e?await r.get(e):await r.get(t??"");return await a.done,n.close(),o?{username:o.username,peerId:o.peerId,peerPublicKey:o.peerPublicKey}:void 0}catch{return void n.close()}}(...t.args);break;case"getAllDBAddressBookEntries":e=await async function(){try{const e=await C(),t=await e.getAll("addressBook");return e.close(),t}catch{return[]}}(...t.args);break;case"setDBAddressBookEntry":await async function(e,t,n){try{const a=await C(),r=a.transaction(["addressBook"],"readwrite"),o=r.objectStore("addressBook"),i=o.index("peerId"),s=o.index("peerPublicKey"),c=await i.get(t),l=await s.get(n);(!c&&!l||c&&!l||!c&&l)&&await o.put({username:e,peerId:t,peerPublicKey:n,dateAdded:Date.now()}),await r.done,a.close()}catch(e){console.error(e)}}(...t.args),e=void 0;break;case"deleteDBAddressBookEntry":e=await async function(e,t,n){const a=!e||0===e.length,r=!t||t.length<10,o=64!==n?.length;if(a&&r&&o)throw new Error("Cannot delete address book with no data");let i=t??"";try{const a=await C(),s=a.transaction("addressBook","readwrite"),c=s.objectStore("addressBook");if(r)if(o){const t=c.index("username"),n=await t.getKey(e??"");if(n){const a=await t.get(e??"");i=a?.peerId??"",await c.delete(n)}}else{const e=c.index("peerPublicKey"),t=await e.getKey(n);if(t){const a=await e.get(n);i=a?.peerId??"",await c.delete(t)}}else{const e=c.index("peerId"),n=await e.getKey(t);n&&await c.delete(n)}await s.done,a.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 n=await C();try{const a=n.transaction("blacklist","readonly"),r=e?a.objectStore("blacklist").index("peerId"):a.objectStore("blacklist").index("peerPublicKey"),o=e?await r.get(e):await r.get(t??"");return await a.done,!!o}finally{n.close()}}(...t.args);break;case"getAllDBBlacklisted":e=await async function(){const e=await C();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 n=await C(),a=n.transaction(["blacklist"],"readwrite"),r=a.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 a.done,n.close()}catch(e){throw console.error(e),e}}(...t.args),e=void 0;break;case"deleteDBPeerFromBlacklist":await async function(e,t){const n=!e||e.length<10;if(n&&64!==t?.length)throw new Error("Cannot delete blacklisted with no data");try{const a=await C(),r=a.transaction("blacklist","readwrite"),o=r.objectStore("blacklist");if(n){const e=o.index("peerPublicKey"),n=await e.getKey(t??"");n&&await o.delete(n)}else{const t=o.index("peerId"),n=await t.getKey(e);n&&await o.delete(n)}await r.done,a.close()}catch(e){console.error(e)}}(...t.args),e=void 0;break;case"getAllDBUniqueRooms":e=await async function(){const e=await C();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,n){if(32!==n.byteLength)throw new Error("Room policy must be the canonical 32-byte descriptor");const a=await C();try{const r=a.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:n,updatedAt:Date.now()});else{const a=Date.now();await o.put({roomId:t,roomUrl:e,roomPolicy:n,messageCount:0,lastMessageMerkleRoot:"",createdAt:a,updatedAt:a})}await r.done}finally{a.close()}}(...t.args),e=void 0;break;case"getDBMessageData":e=await async function(e,t){try{const n=await C(),a=n.transaction(["messageData"],"readonly"),r=a.objectStore("messageData"),o=r.index("merkleRoot"),i=r.index("hash");if(e?.length===2*v){const r=await o.get(e);if(r)return await a.done,n.close(),r;if(t?.length===2*v){const e=await i.get(t);return await a.done,n.close(),e}return await a.done,void n.close()}if(t?.length===2*v){const e=await i.get(t);return await a.done,n.close(),e}return await a.done,void n.close()}catch(e){return void console.error(e)}}(...t.args);break;case"getDBRoomMessageData":e=await async function(e){const t=await C(),n=await t.getAllFromIndex("messageData","roomId",e);t.close();const a=n.length,r=[];for(let t=0;t<a;t++)r.push({transferId:n[t].transferId,roomId:e,merkleRoot:n[t].merkleRoot,hash:n[t].hash,fromPeerId:n[t].fromPeerId,filename:n[t].filename,messageType:n[t].messageType,savedSize:n[t].savedSize,totalSize:n[t].totalSize,channelLabel:n[t].channelLabel,timestamp:n[t].timestamp});return r}(...t.args);break;case"getDBRoomStats":e=await async function(e){const t=await C(),n=await t.getAllFromIndex("messageData","roomId",e);t.close();const a=new Set;let r=0,o=0,i=0,s=0;for(const e of n){const t=void 0!==e.transferId,n=t?e.totalSize:e.savedSize;t?(r+=n,i+=1):(o+=n,s+=1,e.fromPeerId.length>0&&a.add(e.fromPeerId))}return{messageCount:n.length,messagesSent:i,messagesReceived:s,bytesSent:r,bytesReceived:o,bytesTotal:r+o,peerIds:[...a]}}(...t.args);break;case"setDBRoomMessageData":await async function(e,t,n,a,r,o,i,s,c,l,d){try{const u=await C(),y=u.transaction(["messageData","uniqueRoom"],"readwrite"),w=y.objectStore("messageData"),h=await w.index("merkleRoot").get(t),f=h?.savedSize??0;try{await w.put({transferId:d,roomId:e,timestamp:l,merkleRoot:t,hash:n,fromPeerId:a,filename:s,messageType:i,savedSize:f+r<=o?f+r:o,totalSize:o,channelLabel:c})}catch(e){throw await y.done,u.close(),e}const g=y.objectStore("uniqueRoom"),m=await g.index("roomId").get(e);if(m&&m.lastMessageMerkleRoot!==t)try{await g.put({...m,lastMessageMerkleRoot:t,messageCount:m.messageCount+1,updatedAt:l})}catch(e){throw await y.done,u.close(),e}await y.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 n=await C(),a=await n.get("chunks",[e,t]);return n.close(),a?.data}(...t.args);break;case"existsDBChunk":e=await async function(e,t){const n=await C(),a=await n.count("chunks",[e,t]);return n.close(),a>0}(...t.args);break;case"getDBNewChunk":e=await async function(e,t){const n=await C();try{return await n.get("newChunks",[e,t])}finally{n.close()}}(...t.args);break;case"getDBNewChunkByReceipt":e=await async function(e,t){if(e.length!==2*v||t.length!==2*v)return;const n=await C();try{return await n.getFromIndex("newChunks","receiptScope",[e,t])}finally{n.close()}}(...t.args);break;case"existsDBNewChunk":e=await async function(e,t){const n=await C(),a=await n.count("newChunks",[e,t]);return n.close(),a>0}(...t.args);break;case"getDBSendQueue":e=await async function(e,t,n){const a=await C();if(n){const r=await a.get("sendQueue",[n,e,t]);return a.close(),r?[r]:[]}const r=a.transaction("sendQueue","readonly").objectStore("sendQueue").index("labelPeer"),o=IDBKeyRange.only([e,t]),i=await r.getAll(o);return a.close(),i}(...t.args);break;case"getDBAllChunks":e=await async function(e,t){try{const n=await C(),a=n.transaction("chunks","readonly"),r=a.objectStore("chunks"),o=r.index("hash"),i=r.index("merkleRoot");if(e?.length===2*v){const t=await i.getAll(e);return 0===t.length?(await a.done,n.close(),[]):(await a.done,n.close(),t)}if(t?.length===2*v){const e=await o.getAll(t);return await a.done,n.close(),e.length>0?e.filter(t=>t.merkleRoot===e[0].merkleRoot):e}return await a.done,n.close(),[]}catch(e){return console.error(e),[]}}(...t.args);break;case"getDBAllChunkLeafHashes":e=await async function(e){if(e.length!==2*v)return[];try{const t=await C(),n=t.transaction("chunks","readonly"),a=n.objectStore("chunks").index("merkleRoot"),r=[];let o=await a.openCursor(e);for(;o;)r.push({chunkIndex:o.value.chunkIndex,leafHash:o.value.leafHash}),o=await o.continue();return await n.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 n=await C(),a=n.transaction(["chunks"],"readonly"),r=a.objectStore("chunks"),o=r.index("hash"),i=r.index("merkleRoot");if(t?.length===2*v){const r=await o.count(t);if(0===r){if(e?.length===2*v){const t=await i.count(e);return await a.done,n.close(),t}return await a.done,n.close(),0}return await a.done,n.close(),r}if(e?.length===2*v){const t=await i.count(e);return await a.done,n.close(),t}return await a.done,n.close(),0}catch{return 0}}(...t.args);break;case"setDBChunk":await async function(e){const t=await C();try{await t.add("chunks",e)}finally{t.close()}}(...t.args),e=void 0;break;case"storeReceiveChunk":{const n=t.args[0];e=await fe(n.merkleRoot,()=>async function(e){return pe(e)}(n));break}case"getReceiveFile":{const n=t.args;e=await fe(n[0],()=>ke(...n));break}case"closeReceiveFile":await fe(t.args[0],()=>be(...t.args)),e=void 0;break;case"deleteReceiveTransfer":await fe(t.args[0],()=>async function(e){if(e.length!==2*v||!/^[0-9a-f]+$/.test(e))throw new Error("invalid receive transfer Merkle root");await be(e);const t=await C();try{const n=t.transaction(["chunks","messageData","uniqueRoom"],"readwrite"),a=n.objectStore("chunks"),r=n.objectStore("messageData"),o=n.objectStore("uniqueRoom"),i=await a.index("merkleRoot").getAllKeys(e);for(const e of i)await a.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"),n=await t.count(c),a=await t.openCursor(IDBKeyRange.only(c),"prev");await o.put({...e,messageCount:n,updatedAt:a?.value.timestamp??Date.now(),lastMessageMerkleRoot:a?.value.merkleRoot??""})}}await n.done}finally{t.close()}await de(e)}(...t.args)),e=void 0;break;case"getDBAllNewChunks":e=await async function(e){const{transferId:t,merkleRootHex:n,hashHex:a}=e,r=t?"transferId":n?"merkleRoot":a?"hash":void 0,o=t??n??a;if(!r||!o)return[];const i=await C();try{return await i.getAllFromIndex("newChunks",r,o)}finally{i.close()}}(...t.args);break;case"getDBAllNewChunksCount":e=await async function(e){const t=await C();try{return await t.countFromIndex("newChunks","transferId",e)}finally{t.close()}}(...t.args);break;case"setDBNewChunk":await async function(e){const t=await C();try{await t.put("newChunks",e)}finally{t.close()}}(...t.args),e=void 0;break;case"setDBSendQueue":await async function(e){const t=await C();await t.put("sendQueue",e),t.close()}(...t.args),e=void 0;break;case"countDBSendQueue":e=await async function(e,t){const n=await C(),a=n.transaction("sendQueue","readonly").objectStore("sendQueue").index("labelPeer"),r=IDBKeyRange.only([e,t]),o=await a.count(r);return n.close(),o}(...t.args);break;case"deleteDBChunk":await async function(e,t){try{const n=await C(),a=n.transaction("chunks","readwrite"),r=a.objectStore("chunks");if(void 0!==t){const n=IDBKeyRange.only([e,t]);await r.delete(n)}else{const t=r.index("hash"),n=await t.getAllKeys(e),a=n.length;if(0===a){const t=r.index("merkleRoot"),n=await t.getAllKeys(e),a=n.length;for(let e=0;e<a;e++)await r.delete(n[e])}else for(let e=0;e<a;e++)await r.delete(n[e])}await a.done,n.close()}catch{}}(...t.args),e=void 0;break;case"deleteDBNewChunk":await async function(e){const{transferId:t,merkleRootHex:n,hashHex:a,chunkIndex:r}=e,o=await C();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(n){const e=await i.index("merkleRoot").getAllKeys(n);for(const t of e)await i.delete(t)}else if(a){const e=await i.index("hash").getAllKeys(a);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 C(),n=t.transaction(["messageData","uniqueRoom"],"readwrite"),a=n.objectStore("messageData"),r=n.objectStore("uniqueRoom"),o=a.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 a.get(i[e]);c=t?.roomId??""}await a.delete(i[e])}if(c.length>0){const e=r.index("roomId"),t=await e.get(c);if(t){const e=a.index("roomId"),n=await e.getAllKeys(c),o=n.length,i=o>0?await a.get(n[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 n.done,t.close(),await fe(e,async()=>{await be(e),await de(e)})}catch{}}(...t.args),e=void 0;break;case"deleteDBUniqueRoom":await async function(e){const t=await C();try{const n=t.transaction(["uniqueRoom","ratchetSessions"],"readwrite"),a=n.objectStore("uniqueRoom"),r=a.index("roomId"),o=await r.getKey(e);void 0!==o&&await a.delete(o);const i=n.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(xe(e,t[1])));await n.done}finally{t.close()}}(...t.args),e=void 0;break;case"deleteDBSendQueue":await async function(e,t,n){try{const a=await C();if(void 0!==n)await a.delete("sendQueue",[n,e,t]);else{const n=IDBKeyRange.only([e,t]);await a.delete("sendQueue",n)}a.close()}catch{}}(...t.args),e=void 0;break;case"getRatchetSession":e=await Ae(...t.args);break;case"setRatchetSession":await Re(...t.args),e=void 0;break;case"deleteRatchetSession":await async function(e,t){await Ke(e,t,async()=>{try{const n=await C();await n.delete("ratchetSessions",[e,t]),n.close(),Se.forget(e,t),Ie.delete(xe(e,t))}catch(e){console.error(e)}})}(...t.args),e=void 0;break;case"getPinAttemptState":e=await async function(e,t){Pe(e,t);const n=await C();try{return await n.get("meta",Ee(e,t))}finally{n.close()}}(...t.args);break;case"incrementPinAttemptState":e=await async function(e,t,n,a,r,o){if(Pe(e,t),!Number.isSafeInteger(n)||!Number.isSafeInteger(a)||!Number.isSafeInteger(r)||!Number.isSafeInteger(o)||n<0||a<1||r<1||o<r)throw new Error("Invalid PIN backoff parameters");const i=await C();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,y={failures:u,retryAfter:n+(u<a?0:Math.min(r*2**(u-a),o))};return await c.put(y,l),await s.done,y}finally{i.close()}}(...t.args);break;case"deletePinAttemptState":await async function(e,t){Pe(e,t);const n=await C();try{if(void 0!==t)return void await n.delete("meta",Ee(e,t));const a=n.transaction("meta","readwrite"),r=a.objectStore("meta"),o=De(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 a.done}finally{n.close()}}(...t.args),e=void 0;break;case"getIdentityX25519":e=await async function(){const e=await C();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 n=await ne(),a=await re(n,t.wrappedSecret);if(32!==a.byteLength)throw new Error("Stored X25519 identity has an invalid secret length");return{pub:t.pub,secret:a,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 ne(),n=await ae(t,e.secret),a={pub:e.pub,wrappedSecret:n,crossSig:e.crossSig},r=await C();try{await r.put("meta",a,Le)}finally{r.close()}}(...t.args),e=void 0;break;case"deleteIdentityX25519":await async function(){const e=await C();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 C();let t;try{for(;;){const n=await We(e);if(!n.identity)return;t??=await ne();const a=await re(t,n.identity.wrappedSecret);if(64!==a.byteLength||!qe(n.identity.pub,a))throw new Uint8Array(a).fill(0),new Error("Stored Ed25519 public and secret keys are inconsistent");try{if("legacy"===n.identity.kind&&!await Xe(e,n)){new Uint8Array(a).fill(0);continue}return{pub:Ue(n.identity.pub),secret:a,recordRevision:"legacy"===n.identity.kind?1n:n.identity.recordRevision}}catch(e){throw new Uint8Array(a).fill(0),e}}}finally{e.close()}}();break;case"setIdentityEd25519":e=await async function(e){const t="object"==typeof e&&null!==e&&e.secret instanceof ArrayBuffer?new Uint8Array(e.secret):void 0;try{if(!(e.pub instanceof ArrayBuffer&&e.secret instanceof ArrayBuffer&&32===e.pub.byteLength&&64===e.secret.byteLength))throw new Error("Ed25519 identity has invalid key lengths");if(!qe(e.pub,e.secret))throw new Error("Ed25519 public key does not match the secret key");const t=Ue(e.pub),n=Ue(e.secret);let a;try{const e=await ne();a=await ae(e,n)}finally{new Uint8Array(n).fill(0)}const r=await C();try{const e=r.transaction("meta","readwrite"),n=e.objectStore("meta"),[o,i]=await Promise.all([n.get(Be),n.get(je)]),s=Fe(o),c=Oe(i);He(s,c);const l=Qe(s,c),d=Ve(l),u={version:1,pub:t,wrappedSecret:a,recordRevision:d},y={version:1,lastRevision:d};return await Promise.all([n.put(u,Be),n.put(y,je)]),await e.done,d}finally{r.close()}}finally{t?.fill(0)}}(...t.args);break;case"deleteIdentityEd25519":await async function(){const e=await C();try{const t=e.transaction(["meta","ratchetSessions"],"readwrite"),n=t.objectStore("meta"),[a,r]=await Promise.all([n.get(Be),n.get(je)]),o=Fe(a),i=Oe(r);if(He(o,i),void 0!==o){const e=Qe(o,i),t=Ve(e);await n.put({version:1,lastRevision:t},je),await n.delete(Be)}await t.objectStore("ratchetSessions").clear(),await t.done}finally{e.close()}Se.clear(),Ie.clear()}(),e=void 0;break;case"getIdentityDerivation":e=await Je();break;case"setIdentityDerivation":await async function(e){if(!_e(e))throw new Error("Identity derivation value is unsupported");const t=await C();try{const n=t.transaction("meta","readwrite"),a=n.objectStore("meta"),r=Ye(await a.get(Be));await a.put({version:1,derivation:e,boundPub:void 0===r?null:Ue(r)},Ge),await n.done}finally{t.close()}}(...t.args),e=void 0;break;case"deleteIdentityDerivation":await async function(){const e=await C();try{await e.delete("meta",Ge)}finally{e.close()}}(),e=void 0;break;case"deleteDB":await Ze(),e=void 0;break;default:return void postMessage({id:n,error:"Method not found"})}if("getIdentityEd25519"===t.method&&void 0!==e){const t=e.secret;try{globalThis.postMessage({id:n,result:e},[t])}catch(e){throw new Uint8Array(t).fill(0),e}}else postMessage({id:n,result:e})}catch(e){postMessage({id:n,error:String(e)})}};\n',Ta=new Blob([Da],{type:"application/javascript"}),La=new Worker(URL.createObjectURL(Ta),{type:"module"});let qa=0;const Oa=new Map;La.onmessage=e=>{const{id:t,result:n,error:r}=e.data,o=Oa.get(t);o?(Oa.delete(t),r?o.reject(r):o.resolve(n)):_a(n)};const Na=e=>{const t=[...Oa.values()];Oa.clear();for(const n of t)n.reject(e)};La.onerror=e=>{Na(new Error(`p2party: the database worker failed: ${e.message||"unknown error"}`))},La.onmessageerror=()=>{Na(new Error("p2party: a database worker message could not be deserialized"))};const Ba=(e,t,n=[])=>new Promise((r,o)=>{const a=++qa;Oa.set(a,{resolve:r,reject:o});try{La.postMessage({id:a,method:e,args:t},n)}catch(e){Oa.delete(a),o(e)}});function Fa(e,...t){return Ba(e,t)}const ja=(e,t)=>Fa("getDBAddressBookEntry",e,t),za=async(e,t)=>{try{return await Fa("getDBPeerIsBlacklisted",e,t)}catch(e){return console.error("p2party: blacklist lookup failed; treating this peer as blocked",e),!0}},$a=()=>Fa("getAllDBUniqueRooms"),Ha=(e,t,n)=>Fa("setDBUniqueRoom",e,t,n),Va=(e,t)=>Fa("getDBMessageData",e,t),Wa=e=>Fa("getDBRoomMessageData",e),Qa=(e,t)=>Fa("getDBNewChunk",e,t),Ga=e=>Fa("setDBChunk",e),Xa=e=>Fa("storeReceiveChunk",e),Ja=e=>Fa("deleteReceiveTransfer",e),Ya=e=>Fa("setDBNewChunk",e),Za=e=>Fa("deleteDBNewChunk",e),ei=(e,t,n)=>Fa("deleteDBSendQueue",e,t,n),ti=(e,t)=>Fa("deleteRatchetSession",e,t),ni=(e,t)=>Fa("getPinAttemptState",e,t),ri=()=>Fa("getIdentityX25519"),oi=()=>Fa("deleteIdentityX25519"),ai=()=>(async e=>{const t=await e();if(void 0!==t)try{const e=Ma(t),n=Ka(e.recordRevision),{input:r,material:o}=await Ua(t);return xa(o),{...r,recordRevision:n}}catch(e){throw _a(t),e}})(()=>Fa("getIdentityEd25519")),ii=async e=>(async(e,t)=>{const{material:n}=await Ua(e);let r;try{const e=Uint8Array.from(n.publicKey).buffer;r=Uint8Array.from(n.secretKey).buffer;const o=await t({pub:e,secret:r},[e,r]);return Ka(o)}finally{xa(n),void 0!==r&&0!==r.byteLength&&new Uint8Array(r).fill(0)}})(e,(e,t)=>Ba("setIdentityEd25519",[e],t)),si=e=>Fa("setIdentityDerivation",e),ci=(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!==y)throw new Error("Merkle root should be 64 bytes");let o="";const a=new Uint8Array(32);a.set(r.subarray(0,Math.min(32,r.length))),o+=so(a),o+="~",o+="string"==typeof t?t:so(t),n(o)}catch(e){r(e)}}),li=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 o=co(n[0]);if(32!==o.length)throw new Error("Channel label is not 32 bytes long.");const a=(new TextDecoder).decode(o).replace(/\0+$/,""),i=co(n[1]);if(i.length!==y)throw new Error("Merkle root has invalid length");t({channelLabel:a,merkleRoot:i,merkleRootHex:n[1]})}catch(e){n(e)}}),di=new Map,ui=(e,t,n)=>`${e}\0${t}\0${n}`,hi=(e,t,n)=>{const r=ui(e,t,n);let o=di.get(r);return o||(o={acked:new Set,complete:!1},di.set(r,o)),o},fi=(e,t,n)=>new Set(hi(e,t,n).acked),mi=(e,t,n)=>hi(e,t,n).acked.size,pi=(e,t,n)=>{const r=hi(e,t,n);return!r.complete&&(r.complete=!0,!0)},yi=(e,t,n)=>di.get(ui(e,t,n))?.complete??!1,gi=(e,t,n)=>{di.delete(ui(e,t,n))},wi=async(e,t,n,r,o)=>{const a=Date.now()+r;for(;Date.now()<a&&!yi(e,t,n)&&!o?.aborted;)await new Promise(e=>setTimeout(e,200));return!o?.aborted&&yi(e,t,n)},bi=async(e,t,n,r,o)=>{try{const a=so(e),{merkleRootHex:i}=await li(t),{rooms:s}=o.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(a===d){return pi(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)=>Fa("getDBNewChunkByReceipt",e,t))(i,a),t=e?.chunkIndex??-1;if(e&&e.transferId===u&&t>-1){const e=((e,t,n,r)=>{const o=hi(e,t,n).acked,a=o.size;return o.add(r),o.size!==a})(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}},vi=e=>{const t=new Uint8Array(T);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+=y;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),o=new Uint8Array(256);o.set(r.subarray(0,Math.min(256,r.length))),t.set(o,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},ki=e=>{if(e.length!==T)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 o=e[t];t+=1;const a=e.slice(t,t+y);t+=y;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),m=Number(f.getBigUint64(0,!1));t+=8;const p=new DataView(e.buffer,e.byteOffset+t,8),g=Number(p.getBigUint64(0,!1));t+=8;const w=new DataView(e.buffer,e.byteOffset+t,8);return{schemaVersion:r,messageType:o,hash:a,totalSize:s,date:d,name:h,chunkStartIndex:m,chunkEndIndex:g,chunkIndex:Number(w.getBigUint64(0,!1))}},Ii={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},Si={Text:"Text",Image:"Image",Document:"Document",Audio:"Audio",Video:"Video",Compressed:"Compressed",Code:"Code",Ebook:"Ebook",Font:"Font",Executable:"Executable",Unknown:"Unknown"},Ci=e=>{switch(e){case Ii.Text:return"text/plain";case Ii.ImagePNG:return"image/png";case Ii.ImageJPEG:case Ii.ImageJPG:return"image/jpeg";case Ii.ImageGIF:return"image/gif";case Ii.ImageBMP:return"image/bmp";case Ii.ImageTIFF:return"image/tiff";case Ii.ImageSVG:return"image/svg+xml";case Ii.ImageWEBP:return"image/webp";case Ii.ImageHEIC:return"image/heic";case Ii.ImageICO:return"image/vnd.microsoft.icon";case Ii.DocumentPDF:return"application/pdf";case Ii.DocumentDOC:return"application/msword";case Ii.DocumentDOCX:return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case Ii.DocumentXLS:return"application/vnd.ms-excel";case Ii.DocumentXLSX:return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case Ii.DocumentPPT:return"application/vnd.ms-powerpoint";case Ii.DocumentPPTX:return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case Ii.DocumentTXT:return"text/plain";case Ii.DocumentRTF:return"application/rtf";case Ii.DocumentODT:return"application/vnd.oasis.opendocument.text";case Ii.AudioMP3:return"audio/mpeg";case Ii.AudioWAV:return"audio/wav";case Ii.AudioAAC:return"audio/aac";case Ii.AudioFLAC:return"audio/flac";case Ii.AudioOGG:return"audio/ogg";case Ii.AudioM4A:return"audio/mp4";case Ii.VideoMP4:return"video/mp4";case Ii.VideoAVI:return"video/x-msvideo";case Ii.VideoMKV:return"video/x-matroska";case Ii.VideoMOV:return"video/quicktime";case Ii.VideoWMV:return"video/x-ms-wmv";case Ii.VideoFLV:return"video/x-flv";case Ii.VideoWEBM:return"video/webm";case Ii.CompressedZIP:return"application/zip";case Ii.CompressedRAR:return"application/vnd.rar";case Ii.Compressed7Z:return"application/x-7z-compressed";case Ii.CompressedTAR:return"application/x-tar";case Ii.CompressedGZ:return"application/gzip";case Ii.CodeHTML:return"text/html";case Ii.CodeCSS:return"text/css";case Ii.CodeJS:case Ii.CodeJSX:return"application/javascript";case Ii.CodeTS:case Ii.CodeTSX:return"application/typescript";case Ii.CodeJSON:return"application/json";case Ii.CodeXML:return"application/xml";case Ii.CodePY:return"text/x-python";case Ii.CodeJAVA:return"text/x-java-source";case Ii.CodeC:return"text/x-c";case Ii.CodeCPP:return"text/x-c++";case Ii.CodeCS:return"text/plain";case Ii.CodeRB:return"text/x-ruby";case Ii.CodePHP:return"application/x-httpd-php";case Ii.CodeSQL:return"application/sql";case Ii.EbookEPUB:return"application/epub+zip";case Ii.EbookMOBI:return"application/x-mobipocket-ebook";case Ii.EbookAZW:return"application/vnd.amazon.ebook";case Ii.FontTTF:return"font/ttf";case Ii.FontOTF:return"font/otf";case Ii.ExecutableEXE:return"application/vnd.microsoft.portable-executable";case Ii.ExecutableDMG:return"application/x-apple-diskimage";case Ii.ExecutableAPK:return"application/vnd.android.package-archive";default:return"application/octet-stream"}},Ai=(new TextEncoder).encode("p2party/protocol-v3/chunk-receipt/v1\0"),Ei=async(e,t,n)=>{if(e.length!==y)throw new Error("Chunk receipt Merkle root must be 64 bytes");if(n.length!==y)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(Ai.length+e.length+8+n.length);let o=0;return r.set(Ai,o),o+=Ai.length,r.set(e,o),o+=e.length,new DataView(r.buffer).setBigUint64(o,BigInt(t),!1),o+=8,r.set(n,o),new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",r))};class Pi extends Error{name="X25519RejectedPublicPointError";constructor(){super("x25519_dh failed (identity point)")}}const xi=(()=>{const e=new Uint8Array(R);return e[0]=9,e})(),Ri=(e,t,n)=>{const r=e._malloc(t);if(0===r)throw new Error(`${n} failed (allocation)`);return r},Mi=(e,t,n)=>new Uint8Array(e.wasmMemory.buffer,t,n),Ki=e=>{let t,n;try{if(t=Ri(e,R,"x25519_keypair"),n=Ri(e,M,"x25519_keypair"),0!==e._x25519_keypair(t,n))throw new Error("x25519_keypair failed");return{publicKey:Uint8Array.from(Mi(e,t,R)),secretKey:Uint8Array.from(Mi(e,n,M))}}finally{try{void 0!==n&&Do(e,Mi(e,n,M))}finally{void 0!==t&&e._free(t)}}},Ui=async e=>{const t=e?.wasmMemory??ho(),n=e??await _o(t);return Ki(n)},_i=(e,t,n)=>{const r=Pa(e,"secretKey",{exactLength:M});let o,a,i;try{const e=Pa(t,"publicKey",{exactLength:R});if(o=Ri(n,R,"x25519_dh"),a=Ri(n,r.length,"x25519_dh"),i=Ri(n,e.length,"x25519_dh"),Mi(n,a,r.length).set(r),Mi(n,i,e.length).set(e),0!==n._x25519_dh(o,a,i))throw new Pi;return Uint8Array.from(Mi(n,o,R))}finally{try{try{void 0!==o&&Do(n,Mi(n,o,R))}finally{try{void 0!==a&&Do(n,Mi(n,a,r.length))}finally{void 0!==i&&n._free(i)}}}finally{r.fill(0)}}},Di=(e,t,n)=>{const r=Math.max(e.length,1),o=Math.max(t.length,1),a=n._malloc(p),i=n._malloc(r),s=n._malloc(o);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(a,i,e.length,s,t.length))throw new Error("hkdf_sha512_extract failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,a,p))}finally{Do(n,new Uint8Array(n.wasmMemory.buffer,a,p)),Do(n,new Uint8Array(n.wasmMemory.buffer,i,r)),Do(n,new Uint8Array(n.wasmMemory.buffer,s,o))}},Ti=(e,t,n,r)=>{const o=r._malloc(n),a=r._malloc(p),i=r._malloc(Math.max(t.length,1));try{new Uint8Array(r.wasmMemory.buffer,a,p).set(e),new Uint8Array(r.wasmMemory.buffer,i,t.length).set(t);if(0!==r._hkdf_sha512_expand(o,n,a,i,t.length))throw new Error("hkdf_sha512_expand failed");return Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,o,n))}finally{Do(r,new Uint8Array(r.wasmMemory.buffer,o,n)),Do(r,new Uint8Array(r.wasmMemory.buffer,a,p)),r._free(i)}},Li=(new TextEncoder).encode("p2party-rk-v1"),qi=(new TextEncoder).encode("p2party-ck-v1"),Oi=(new TextEncoder).encode("p2party-mk-v1"),Ni=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Bi=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},Fi=(e,t,n)=>{const r=Di(e,t,n),o=Ti(r,Li,64,n);r.fill(0);const a=o.slice(0,32),i=o.slice(32,64);return o.fill(0),{rootKey:a,chainKey:i}},ji=(e,t)=>{const n=Di(e,Oi,t),r=Di(e,qi,t),o=n.slice(0,32),a=r.slice(0,32);return n.fill(0),r.fill(0),{chainKey:a,messageKey:o}},zi=(e,t,n,r,o=J)=>{const a=Ki(r),i={rootSuite:o,rootKey:Uint8Array.from(e),sendingChainKey:null,receivingChainKey:null,dhSelfPub:a.publicKey,dhSelfSec:a.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=_i(i.dhSelfSec,i.dhRemotePub,r),t=Fi(i.rootKey,e,r);e.fill(0),i.rootKey.fill(0),i.rootKey=t.rootKey,i.sendingChainKey=t.chainKey}return i},$i=(e,t)=>{if(!e.sendingChainKey)throw new Error("ratchet: no sending chain");const{chainKey:n,messageKey:r}=ji(e.sendingChainKey,t),o={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:o}},Hi=(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}=ji(e.receivingChainKey,n);e.receivingChainKey.fill(0),e.receivingChainKey=t,e.skipped.set(`${Ni(e.dhRemotePub)}:${e.Nr}`,r),e.Nr+=1}if(e.skipped.size>Y)for(const t of e.skipped.keys()){if(e.skipped.size<=Y)break;e.skipped.get(t)?.fill(0),e.skipped.delete(t)}}},Vi=(e,t,n)=>{e.PN=e.Ns,e.Ns=0,e.Nr=0,e.dhRemotePub=Uint8Array.from(t.dhPub);let r=_i(e.dhSelfSec,e.dhRemotePub,n),o=Fi(e.rootKey,r,n);r.fill(0),e.rootKey.fill(0),e.rootKey=o.rootKey,e.receivingChainKey?.fill(0),e.receivingChainKey=o.chainKey;const a=e.dhSelfSec,i=Ki(n);e.dhSelfPub=i.publicKey,e.dhSelfSec=i.secretKey,a.fill(0),r=_i(e.dhSelfSec,e.dhRemotePub,n),o=Fi(e.rootKey,r,n),r.fill(0),e.rootKey.fill(0),e.rootKey=o.rootKey,e.sendingChainKey?.fill(0),e.sendingChainKey=o.chainKey},Wi=(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=`${Ni(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))&&(Hi(e,t.PN,n),Vi(e,t,n)),t.N<e.Nr)throw new Error("ratchet: message key already consumed");Hi(e,t.N,n);const{chainKey:o,messageKey:a}=ji(e.receivingChainKey,n);return e.receivingChainKey.fill(0),e.receivingChainKey=o,e.Nr+=1,a},Qi=e=>e.slice().buffer,Gi=e=>e?e.slice().buffer:null,Xi=e=>({rootSuite:e.rootSuite,rootKey:Qi(e.rootKey),sendingChainKey:Gi(e.sendingChainKey),receivingChainKey:Gi(e.receivingChainKey),dhSelfPub:Qi(e.dhSelfPub),dhSelfSec:Qi(e.dhSelfSec),dhRemotePub:Gi(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:Bi(e.slice(0,n)).slice().buffer,n:Number(e.slice(n+1)),messageKey:t.slice().buffer}})}),Ji=e=>{const t=new Map;for(const n of e.skippedMessageKeys){const e=new Uint8Array(n.dhPub);t.set(`${Ni(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}},Yi=e=>Ji(Xi(e)),Zi=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)},es=(e,t)=>{if(e.rootSuite!==t.rootSuite)throw new Error("ratchet: cannot adopt a different root suite");Zi(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},ts=(1n<<64n)-1n,ns=(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)},rs=(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)},os=(e,t,n=0n)=>{if(e.dhPub.length!==z)throw new Error("chunkFrame: dhPub must be 32 bytes");if(t.length!==$)throw new Error("chunkFrame: nonce must be 12 bytes");const r=new Uint8Array(69);return r[0]=2,r.set(e.dhPub,1),ns(r,33,e.N),ns(r,41,e.PN),((e,t,n)=>{if("bigint"!=typeof n||n<0n||n>ts)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},as=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:rs(e,33),PN:rs(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},is=I,ss=(1n<<64n)-1n,cs=(new TextEncoder).encode("p2party/pq-message-key/v1\0"),ls=(e,t,n)=>{if(!(e instanceof Uint8Array)||e.length!==n)throw new Error(`pqMessageKey: ${t} must be ${String(n)} bytes`)},ds=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new Error(`pqMessageKey: ${t} is outside the safe u64 range`)},us=(e,t)=>{if("string"!=typeof(n=e.rootSuite)||!X.includes(n))throw new Error("pqMessageKey: unsupported root suite");var n;ls(e.rootKey,"rootKey",32),ls(e.binding,"binding",32),(e=>{if("bigint"!=typeof e||e<0n||e>ss)throw new Error("pqMessageKey: epoch is outside the u64 range")})(e.epoch),ls(t.dhPub,"header.dhPub",z),ds(t.N,"header.N"),ds(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 o=cs.length+2+r.length+32+8+1+z+8+8,a=new Uint8Array(o);let i=0;a.set(cs,i),i+=cs.length;const s=new DataView(a.buffer);return s.setUint16(i,r.length,!1),i+=2,a.set(r,i),i+=r.length,a.set(e.binding,i),i+=32,s.setBigUint64(i,e.epoch,!1),i+=8,a[i++]=2,a.set(t.dhPub,i),i+=z,s.setBigUint64(i,BigInt(t.N),!1),i+=8,s.setBigUint64(i,BigInt(t.PN),!1),a},hs=(e,t,n,r)=>{if(!(e instanceof Uint8Array))throw new Error("pqMessageKey: classicalMessageKey must be a Uint8Array");if(t?.rootKey instanceof Uint8Array&&(o=e,a=t.rootKey,o.buffer===a.buffer&&o.byteOffset<a.byteOffset+a.byteLength&&a.byteOffset<o.byteOffset+o.byteLength))throw new Error("pqMessageKey: classicalMessageKey must not alias context.rootKey");var o,a;let i=null,s=null;try{ls(e,"classicalMessageKey",is);const o=us(t,n);return i=Uint8Array.from(t.rootKey),s=Di(i,e,r),Ti(s,o,is,r)}finally{e.fill(0),i?.fill(0),s?.fill(0)}},fs=I,ms=S,ps=C,ys=y+57,gs=(1n<<64n)-1n,ws=(e,t,n)=>{const r=`${o=e,Array.from(o,e=>e.toString(16).padStart(2,"0")).join("")}:${t}`;var o;if(void 0===n)return r;if("bigint"!=typeof n||n<0n||n>gs)throw new Error("messageChunkCrypto: PQ epoch out of u64 range");return`${r}:${n.toString(10)}`},bs=(e,t,n,r)=>{const o=e._malloc(U),a=e._malloc(N),i=e._malloc(y),s=e._malloc(fs),c=new Uint8Array(e.wasmMemory.buffer,o,U),l=new Uint8Array(e.wasmMemory.buffer,a,N);c.fill(0),l.fill(0),c.set(t.subarray(0,U),0),new Uint8Array(e.wasmMemory.buffer,i,y).set(n),new Uint8Array(e.wasmMemory.buffer,s,fs).set(r);const d=e._receive_message_with_key(a,o,i,s),u=0===d?Uint8Array.from(l):null;return e._free(o),e._free(i),Do(e,new Uint8Array(e.wasmMemory.buffer,s,fs)),Do(e,l),{code:d,decrypted:u}},vs=(e,t,n,r,o,a)=>{if(r.length!==y)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const i=(()=>{const e=new Uint8Array(ms);return crypto.getRandomValues(e),e})(),s=os(t,i,a?.epoch??0n),c=((e,t)=>{if(t.length<57)throw new Error("messageChunkCrypto: incomplete chunk frame header");const n=new Uint8Array(ys);return n.set(e,0),n.set(t.subarray(0,57),y),n})(r,s);let l=null;try{const r=((e,t,n,r,o)=>{const a=Math.max(r.length,1),i=Math.max(o.length,1),s=r.length+ps,c=e._malloc(fs),l=e._malloc(ms),d=e._malloc(a),u=e._malloc(i),h=e._malloc(s);new Uint8Array(e.wasmMemory.buffer,c,fs).set(t),new Uint8Array(e.wasmMemory.buffer,l,ms).set(n),r.length&&new Uint8Array(e.wasmMemory.buffer,d,r.length).set(r),o.length&&new Uint8Array(e.wasmMemory.buffer,u,o.length).set(o);const f=0===e._encrypt_chachapoly_symmetric(h,d,r.length,c,l,u,o.length)?Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,h,s)):null;if(Do(e,new Uint8Array(e.wasmMemory.buffer,c,fs)),e._free(l),Do(e,new Uint8Array(e.wasmMemory.buffer,d,a)),e._free(u),Do(e,new Uint8Array(e.wasmMemory.buffer,h,s)),!f)throw new Error("messageChunkCrypto: AEAD encrypt failed");return f})(o,a?l=hs(Uint8Array.from(e),a,t,o):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)}},ks=(e,t,n,r,o,a)=>{if(r.length!==y)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const{header:i,pqEpoch:s}=as(t);let c=null;if(a){try{c=a(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=ws(i.dhPub,i.N,a?s:void 0),f=n.get(h);if(f){const{code:e,decrypted:n}=bs(o,t,r,f);return{decrypted:0===e?n:null,ok:0===e,stateAdvanced:!1}}const m=Yi(e);let p;try{p=Is(m,i,o),c&&(p=hs(p,c,i,o))}catch{return Zi(m),{decrypted:null,ok:!1,stateAdvanced:!1}}const{code:g,decrypted:w}=bs(o,t,r,p);return-2===g?(p.fill(0),Zi(m),{decrypted:null,ok:!1,stateAdvanced:!1}):(es(e,m),n.set(h,p),{decrypted:0===g?w:null,ok:0===g,stateAdvanced:!0})},Is=(e,t,n)=>{try{return Wi(e,t,n)}catch(t){throw Zi(e),t}},Ss=(e,t)=>`${e.length}:${e}${t.length}:${t}`,Cs=new Map,As=new Map,Es=new WeakMap,Ps=async(e,t,n)=>{const r=Ss(e,t),o=Cs.get(r)??Promise.resolve();let a;const i=new Promise(e=>{a=e}),s=o.catch(()=>{}).then(()=>i);Cs.set(r,s),await o.catch(()=>{});try{return await n()}finally{a(),Cs.get(r)===s&&Cs.delete(r)}},xs=(e,t)=>{const n=Ss(t,e.withPeerPublicKey),r=Es.get(e);if(r){if(As.get(n)!==r)throw new Error("ratchet persistence: stale connection cannot reclaim edge");return}const o=Symbol(n);Es.set(e,o),As.set(n,o)},Rs=(e,t)=>{const n=Ss(t,e.withPeerPublicKey),r=Es.get(e);if(!r||As.get(n)!==r)throw new Error("ratchet persistence: stale connection owner")},Ms=async(e,t,n,r,o=null)=>{const a=Xi(e),i={rootSuite:a.rootSuite,roomId:t,peerPublicKey:n,peerId:r,rootKey:a.rootKey,sendingChainKey:a.sendingChainKey,receivingChainKey:a.receivingChainKey,dhSelfPub:a.dhSelfPub,dhSelfSec:a.dhSelfSec,dhRemotePub:a.dhRemotePub,Ns:a.Ns,Nr:a.Nr,PN:a.PN,skippedMessageKeys:a.skippedMessageKeys,edgeCryptoState:null===o?null:o.slice().buffer,updatedAt:Date.now()};try{await(e=>Fa("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)}},Ks=async(e,t,n,r,o=null)=>Ps(t,n,()=>Ms(e,t,n,r,o)),Us=async(e,t,n,r,o=Ms,a=ti)=>Ps(n,e.withPeerPublicKey,async()=>{Rs(e,n);let i=!1;const s=e.serializeEdgeCryptoState?.()??null;try{i=!0,await o(t,n,e.withPeerPublicKey,e.withPeerId,s),Rs(e,n),r()}catch(t){if(i)try{await a(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)}}),_s=new WeakMap,Ds=async(e,t)=>{const n=_s.get(e)??Promise.resolve();let r;const o=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>o);_s.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),_s.get(e)===a&&_s.delete(e)}},Ts=async(e,t,n,r)=>Ds(e,async()=>{const o=e.ratchetState;if(!o)throw new Error("ratchet persistence: no live ratchet state");const a=Yi(o);let i,s=!1;try{if(i=n(a),i.advanced){const n=i.stageEdgeCryptoState;if(r===Ks)await Ps(t,e.withPeerPublicKey,async()=>{if(Rs(e,t),e.ratchetState!==o)throw new Error("ratchet persistence: live state changed");const r=n?.()??e.serializeEdgeCryptoState?.()??null;try{await Ms(a,t,e.withPeerPublicKey,e.withPeerId,r)}finally{r?.fill(0)}Rs(e,t)});else{const o=n?.()??e.serializeEdgeCryptoState?.()??null;try{await r(a,t,e.withPeerPublicKey,e.withPeerId,o)}finally{o?.fill(0)}}if(e.ratchetState!==o)throw new Error("ratchet persistence: live state changed");es(o,a),s=!0}else Zi(a);return i.commit?.(),i.value}catch(e){throw s||Zi(a),i?.rollback?.(),e}}),Ls=async(e,t,n,r=Ks)=>Ts(e,t,t=>{const r=$i(t,n),o=e.pqHealingState;let a=null;if(o){const e=o.currentMessageContext();a={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:a},advanced:!0,commit:()=>e.pqHealingState?.noteApplicationMessage(),rollback:()=>{r.messageKey.fill(0),a?.rootKey.fill(0)}}},r),qs=async(e,t,n,r,o=Ks)=>Ts(e,t,t=>{const o=e.pqHealingState;if(o){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:()=>o.serialize(e),commit:()=>{n.get(r)?.fill(0),n.delete(r)}}}const a=t.skipped.get(r);return a&&(t.skipped.delete(r),a.fill(0)),{value:void 0,advanced:void 0!==a,commit:()=>{n.get(r)?.fill(0),n.delete(r)}}},o),Os=new WeakMap,Ns=async(e,t,n,r=qs)=>{let o=Os.get(e);const a=o?.get(n);if(a)return a;const i=(async()=>{const o=e.messageKeyByMerkleRoot?.get(n),a=e.messageKeyCache;return!(!o||!a)&&(await r(e,t,a,o),e.messageKeyByMerkleRoot?.get(n)===o&&e.messageKeyByMerkleRoot.delete(n),!0)})();o??=new Map,o.set(n,i),Os.set(e,o);try{return await i}finally{o.get(n)===i&&o.delete(n),0===o.size&&Os.delete(e)}},Bs=async(e,t,n,r,o=qs)=>!!(e=>void 0!==e&&Number.isSafeInteger(e.savedSize)&&Number.isSafeInteger(e.totalSize)&&e.savedSize>=0&&e.totalSize>0&&e.savedSize===e.totalSize)(r)&&Ns(e,t,n,o),Fs=()=>({date:new Date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!1,totalSize:0,messageType:Ii.Text,filename:"",chunkHash:new Uint8Array,messageHash:new Uint8Array}),js=async(e,t,n=Xa)=>{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)}},zs=async(e,t,n,r,o,a,i,s={})=>{if(i?.aborted)return Fs();if(!r.ratchetState)return console.error("v3 receive: no ratchet state for peer"),Fs();r.messageKeyCache||(r.messageKeyCache=r.pqHealingState?.activeReceiveKeys??new Map);const c=r.messageKeyCache;let l;try{const{header:t,pqEpoch:n}=as(e);l=ws(t.dhPub,t.N,r.pqHealingState?n:void 0)}catch{return Fs()}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,o,a,i=Ks)=>Ts(e,t,t=>{const i=e.pqHealingState,{header:s,pqEpoch:c}=as(n),l=ws(s.dhPub,s.N,i?c:void 0),d=new Map(r),u=ks(t,n,d,o,a,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>Y;){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,o,a,s.persistRatchetState);d=n.decrypted,u=n.ok}catch(e){return console.error("Could not durably decrypt message",e),Fs()}if(!u||!d)return console.error("Could not decrypt or verify message"),Fs();const h=so(o);((e,t,n)=>{e.messageKeyByMerkleRoot??=new Map,e.messageKeyByMerkleRoot.set(t,n)})(r,h,l);try{if(i?.aborted)return Fs();const e=d.subarray(0,T),a=d.slice(T,T+y),c=d.subarray(T+L),l=ki(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!==y)throw new Error("Invalid metadata hash");if(!Number.isSafeInteger(e.totalSize)||e.totalSize<1||e.totalSize>_)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>U?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:a,messageHash:l.hash});if(0===u)return g();if(f=l.chunkStartIndex,m=l.chunkEndIndex,p=c.length,!(Number.isSafeInteger(f)&&Number.isSafeInteger(m)&&f>=0&&m>=f&&m<=p))return g();const w=await Ei(o,l.chunkIndex,a);if(i?.aborted)return w.fill(0),Fs();const b=Ci(l.messageType),v=c.slice(l.chunkStartIndex,l.chunkEndIndex),k=await js({schemaVersion:l.schemaVersion,roomId:t,fromPeerId:r.withPeerId,channelLabel:n,timestamp:l.date.getTime(),merkleRoot:h,hash:so(l.hash),filename:l.name,messageType:l.messageType,chunkIndex:l.chunkIndex,mimeType:b,leafHash:so(a),realLen:u,totalSize:l.totalSize,storage:l.messageType===Ii.Text?"indexeddb":"opfs"},v,s.storeReceiveChunk);if(!k)return w.fill(0),Fs();if(i?.aborted)return w.fill(0),Fs();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),Fs()}finally{d.fill(0)}var f,m,p},$s=new Map,Hs=(e,t)=>`${e}\0${t}`,Vs=(e,t)=>{const n=Hs(e,t);let r=$s.get(n);if(!r){let e,t;const o=new Promise((n,r)=>{e=n,t=r});o.catch(()=>{}),r={promise:o,resolve:e,reject:t,settled:!1,outcome:"pending",lease:{token:Symbol("ratchet-gate")}},$s.set(n,r)}return r},Ws=(e,t)=>Vs(e,t).promise,Qs=(e,t,n)=>$s.get(Hs(e,t))?.lease===n,Gs=(e,t,n)=>{const r=$s.get(Hs(e,t));return"open"===r?.outcome&&(void 0===n||r.lease===n)},Xs=(e,t,n,r)=>{const o=Vs(e,t);return(!r||o.lease===r)&&(o.settled||(o.settled=!0,o.outcome="rejected",o.reject(n)),!0)},Js=(e,t,n=new Error("Ratchet gate reset"))=>{const r=Hs(e,t),o=$s.get(r);return o&&!o.settled&&(o.settled=!0,o.outcome="rejected",o.reject(n)),$s.delete(r),Vs(e,t).lease},Ys=e=>{if(e.length!==B)throw new Error("Receipt token must be exactly 64 bytes");const t=new Uint8Array(F);return t[0]=3,t.set(e,1),t},Zs=(e,t)=>"open"===e.readyState&&(e.send(Ys(t).buffer),!0),ec=async(e,t)=>{let n=0;for(const r of t){for(;"open"===e.readyState&&e.bufferedAmount>=D;)await new Promise(e=>setTimeout(e,25));if("open"!==e.readyState)return!1;e.send(Ys(r).buffer),n++,32===n&&(n=0,await new Promise(e=>setTimeout(e,10)))}return"open"===e.readyState},tc=new WeakMap,nc=(e,t,n)=>{const r=e.coverRuntime;if(!r)return!1;if(64!==t.length||64!==n.length)return!1;const o=(e=>{let t=tc.get(e);return t||(t={pending:[],drainJobActive:!1,jobSequence:0},tc.set(e,t)),t})(e);for(o.pending.push({merkleRoot:Uint8Array.from(t),token:Uint8Array.from(n)});o.pending.length>4096;)o.pending.shift();return rc(e,r,o),!0},rc=(e,t,n)=>{if(n.drainJobActive||0===n.pending.length)return;const r=t.cellsPerLanePerCycle(),o=Math.min(n.pending.length,r);if(o<=0)return;n.drainJobActive=!0,n.jobSequence+=1;const a={id:t.randomLaneLabel(),kind:"control",declaredCellCount:o,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(a)}catch(e){return n.drainJobActive=!1,void console.error("coverTransfer: could not enqueue receipt drain job",e)}t.onJobSettled(a.id,()=>{n.drainJobActive=!1,rc(e,t,n)})},oc=e=>{const t=tc.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,tc.delete(e)}},ac=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 o=(()=>{const t=e.getAckedChunks?.()??ic;for(;r<n.length;){const e=n[r];if(r+=1,!t.has(e))return e}return null})();if(null===o)return null;const a=await e.sealSlotCell(o);if(null===a)return null;if(a.length!==H)throw new Error("coverTransfer: sealed transfer cell is not the uniform length");return a}}},ic=new Set,sc=e=>{if(e.byteLength<32)return`${String(e.byteLength)}:${so(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")},cc=new Map,lc=new Map,dc=new WeakMap,uc=new Map,hc=(e,t)=>`${String(e.length)}:${e}${t}`,fc=(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()},mc=(e,t)=>t.value||0!==e.length?new Promise(e=>{t.idleWaiters??=new Set,t.idleWaiters.add(e)}):Promise.resolve(),pc=(e,t,n,r)=>{const o=Math.max(0,(dc.get(e)??0)+r);0===o?dc.delete(e):dc.set(e,o);const a=hc(t,n),i=Math.max(0,(lc.get(a)??0)+r);0===i?lc.delete(a):lc.set(a,i)},yc=async(e,t)=>{const n=cc.get(e)??Promise.resolve();let r;const o=new Promise(e=>{r=e}),a=n.then(()=>o);cc.set(e,a),await n;try{return await t()}finally{r(),cc.get(e)===a&&cc.delete(e)}},gc=(e,t)=>{const n=hc(e.roomId,e.peerId),r=Math.max(0,(uc.get(n)??0)+t);0===r?uc.delete(n):uc.set(n,r)},wc=e=>{if(e.released)return;e.released=!0;const t=e.pending.length;e.pending.length=0,e.seen.clear(),t>0&&gc(e,-t)},bc=async(e,t)=>{if(e.draining||e.released)return;e.draining=!0;const n=hc(e.roomId,e.peerId);try{for(;!e.released;){const r=e.pending.shift();if(!r)break;gc(e,-1);try{await yc(n,()=>t(r))}finally{e.seen.delete(sc(r))}}}catch(e){console.error(e)}finally{e.draining=!1,!e.released&&e.pending.length>0&&bc(e,t)}},vc=async(e,t,n,r,o,a,i,s,c,l,d)=>{if(d?.aborted)return{receivedFullSize:!1};if(c)try{const u=c.ratchetGateLease;if(!Qs(n,r,u))return{receivedFullSize:!1};if(await Ws(n,r),d?.aborted)return{receivedFullSize:!1};if(!Qs(n,r,u))return{receivedFullSize:!1};const h=await zs(e,n,o,c,i,l,d),{date:f,chunkSize:m,chunkIndex:p,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===y&&e.chunkIndex>-1&&e.chunkSize>0)return!!t&&Zs(t,e.chunkHash);if("open"!==t?.readyState)return!1;const n=new Uint8Array(y);crypto.getRandomValues(n),Zs(t,n)})(h,s);const S=so(I);return g&&c?.coverRuntime&&nc(c,i,i),g?(await(e=>Fa("closeReceiveFile",e))(a),t.dispatch(at({roomId:n,merkleRootHex:a,sha512Hex:S,fromPeerId:r,totalSize:b,messageType:v,filename:k,channelLabel:o,timestamp:f.getTime(),alsoSendFinishedMessage:!0})),(e=>void 0===e?.coverRuntime)(c)&&s&&Zs(s,I)):m>0&&p>-1&&!w&&t.dispatch(ot({roomId:n,merkleRootHex:a,sha512Hex:S,fromPeerId:r,chunkSize:m,totalSize:b,messageType:v,filename:k,channelLabel:o,timestamp:f.getTime()})),t.dispatch(it({roomId:n,merkleRootHex:a,real:m>0&&p>-1&&!w})),{receivedFullSize:g}}catch(e){return console.error(e),{receivedFullSize:!1}}return{receivedFullSize:!1}},kc=async(e,t,n,r,o,a,i,s,c,l,d,u,h)=>{if(n.value||n.released||h?.aborted)return;n.value=!0;const f=hc(o,a);try{for(;!n.released&&!h?.aborted;){const t=e.pop();if(!t)break;pc(e,o,a,-t.byteLength),await yc(f,async()=>vc(t,r,o,a,i,s,c,l,d,u,h))}}finally{n.value=!1,e.length>0&&!n.released&&!h?.aborted?kc(e,t,n,r,o,a,i,s,c,l,d,u,h):fc(e,n)}},Ic=e=>Object.freeze({...e,wasmExports:Object.freeze({...e.wasmExports})}),Sc=Ic({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"}}),Cc=Ic({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"}}),Ac=Ic({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"}}),Ec=Object.freeze({512:Sc,768:Cc,1024:Ac}),Pc=e=>{const t=Ec[e];if(void 0===t)throw new RangeError(`unsupported ML-KEM parameter set: ${String(e)}`);return t},xc=(e,t,n,r)=>{const o=e._malloc(n);if(0===o)throw new Error(`${t.standardName}: failed to allocate ${r}`);return o},Rc=(e,t,n)=>new Uint8Array(e.wasmMemory.buffer,t,n),Mc=(e,t)=>{void 0!==t&&e._free(t)},Kc=(e,t,n)=>{void 0!==t&&Do(e,Rc(e,t,n))};class Uc{#e;#t;suite;constructor(e,t){this.#e=e,this.suite=t,this.#t=((e,t)=>{const n=e,r=t.wasmExports,o=[r.keypair,r.encaps,r.decaps].filter(e=>"function"!=typeof n[e]);if(0!==o.length)throw new Error(`${t.standardName} WASM exports are unavailable; rebuild libcrypto.wasm (missing ${o.join(", ")})`);return{keypair:n[r.keypair].bind(e),encaps:n[r.encaps].bind(e),decaps:n[r.decaps].bind(e)}})(e,t)}async generateKeyPair(){const e=this.suite,t=new Uint8Array(e.keyPairRandomBytes);try{return Po(t),this.#n(t)}finally{t.fill(0)}}async deriveKeyPair(e){const t=this.suite,n=Pa(e,`${t.standardName} key-generation seed`,{exactLength:t.keyPairRandomBytes});try{return this.#n(n)}finally{n.fill(0)}}#n(e){const t=this.#e,n=this.suite;let r,o,a;try{r=xc(t,n,n.publicKeyBytes,"public key"),o=xc(t,n,n.secretKeyBytes,"secret key"),a=xc(t,n,e.length,"key-generation seed"),Rc(t,a,e.length).set(e);const i=this.#t.keypair(r,o,a);if(0!==i)throw new Error(`${n.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(Rc(t,r,n.publicKeyBytes)),Uint8Array.from(Rc(t,o,n.secretKeyBytes)))}finally{try{Mc(t,r)}finally{try{Kc(t,o,n.secretKeyBytes)}finally{Kc(t,a,e.length)}}}}async encapsulate(e){const t=this.suite,n=Pa(e,`${t.standardName} public key`,{exactLength:t.publicKeyBytes}),r=new Uint8Array(t.encapsRandomBytes);try{return Po(r),this.#r(n,r)}finally{r.fill(0)}}async encapsulateDeterministically(e,t){const n=this.suite,r=Pa(e,`${n.standardName} public key`,{exactLength:n.publicKeyBytes}),o=Pa(t,`${n.standardName} encapsulation randomness`,{exactLength:n.encapsRandomBytes});try{return this.#r(r,o)}finally{o.fill(0)}}#r(e,t){const n=this.#e,r=this.suite;let o,a,i,s;try{o=xc(n,r,r.ciphertextBytes,"ciphertext"),a=xc(n,r,r.sharedSecretBytes,"shared secret"),i=xc(n,r,e.length,"public key"),s=xc(n,r,t.length,"encapsulation randomness"),Rc(n,i,e.length).set(e),Rc(n,s,t.length).set(t);const c=this.#t.encaps(o,a,i,s);if(0!==c)throw new Error(`${r.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(Rc(n,o,r.ciphertextBytes)),Uint8Array.from(Rc(n,a,r.sharedSecretBytes)))}finally{try{Mc(n,o)}finally{try{Kc(n,a,r.sharedSecretBytes)}finally{try{Mc(n,i)}finally{Kc(n,s,t.length)}}}}}async decapsulate(e,t){const n=this.suite,r=Pa(e,`${n.standardName} ciphertext`,{exactLength:n.ciphertextBytes}),o=Pa(t,`${n.standardName} secret key`,{exactLength:n.secretKeyBytes});try{return this.#o(r,o)}finally{o.fill(0)}}#o(e,t){const n=this.#e,r=this.suite;let o,a,i;try{o=xc(n,r,r.sharedSecretBytes,"shared secret"),a=xc(n,r,e.length,"ciphertext"),i=xc(n,r,t.length,"secret key"),Rc(n,a,e.length).set(e),Rc(n,i,t.length).set(t);const s=this.#t.decaps(o,a,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(Rc(n,o,r.sharedSecretBytes)))}finally{try{Kc(n,o,r.sharedSecretBytes)}finally{try{Mc(n,a)}finally{Kc(n,i,t.length)}}}}}const _c=(e,t)=>{const n=Pc(t.parameterSet);if(t!==n)throw new TypeError("ML-KEM suite descriptor must be one of the exported canonical suites");return new Uc(e,n)},Dc=32,Tc=32,Lc=64,qc=new Uint8Array([80,50,81,72]),Oc=(new TextEncoder).encode("p2party/pq-healing/root/v1\0"),Nc=(1n<<64n)-1n;class Bc extends Error{code;constructor(e,t){super(`pqHealing: ${t}`),this.name="PqHealingError",this.code=e}}const Fc=(e,t)=>{throw new Bc(e,t)},jc=(e,t,n)=>e instanceof Uint8Array?e.length!==n?Fc("invalid-record",`${t} must be exactly ${String(n)} bytes`):e:Fc("invalid-record",`${t} must be a Uint8Array`),zc=(e,t)=>{("bigint"!=typeof e||e<0n||e>Nc)&&Fc("overflow",`${t} is outside the unsigned 64-bit range`)},$c=(e,t)=>{zc(e,t),e===Nc&&Fc("overflow",`${t} cannot advance beyond uint64`)},Hc=e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return Fc("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")||Fc("invalid-record","advance acknowledgement must contain only epoch and advanceCounter");const r=Object.getOwnPropertyDescriptor(t,"epoch"),o=Object.getOwnPropertyDescriptor(t,"advanceCounter");if(!(void 0!==r&&void 0!==o&&"value"in r&&"value"in o&&r.enumerable&&o.enumerable))return Fc("invalid-record","advance acknowledgement fields must be enumerable data properties");const a=r.value,i=o.value;return"bigint"!=typeof a||"bigint"!=typeof i?Fc("invalid-record","advance acknowledgement fields must be bigint values"):(zc(a,"advance acknowledgement epoch"),zc(i,"advance acknowledgement counter"),{epoch:a,advanceCounter:i})},Vc=(e,t,n)=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return Fc("invalid-record",`${t} must be a plain record`);const r=e,o=Reflect.ownKeys(r);if(o.length!==n.length||n.some(e=>!o.includes(e)))return Fc("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||Fc("invalid-record",`${t}.${e} must be an enumerable data property`)}return r},Wc=(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},Qc=e=>768===e?1:512===e?2:1024===e?3:Fc("suite-mismatch","unsupported ML-KEM parameter set"),Gc=e=>1===e?768:2===e?512:3===e?1024:Fc("invalid-record","record has an unknown ML-KEM suite tag"),Xc=(e,t)=>Reflect.get(e,t),Jc=e=>{const t=Pc(e.parameterSet);e.standardName===t.standardName&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes&&Xc(e,"sharedSecretBytes")===t.sharedSecretBytes&&Xc(e,"keyPairRandomBytes")===t.keyPairRandomBytes&&Xc(e,"encapsRandomBytes")===t.encapsRandomBytes||Fc("suite-mismatch","selected suite does not match its canonical FIPS 203 descriptor")},Yc=(e,t)=>{Jc(e),Jc(t),e.parameterSet===t.parameterSet&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes||Fc("suite-mismatch","room-selected suite does not exactly match the ML-KEM backend")},Zc=e=>Lc+e.publicKeyBytes,el=e=>Lc+Zc(e)+e.ciphertextBytes,tl=(e,t,n)=>{Jc(t),jc(n,"binding",Dc),jc(e,"ACK",64),Wc(e.subarray(0,4),qc)||Fc("invalid-record","ACK magic is invalid"),1!==e[4]&&Fc("invalid-record","ACK version is unsupported"),3!==e[5]&&Fc("invalid-record","ACK type is unexpected"),0!==e[7]&&Fc("invalid-record","ACK reserved flags must be zero");Gc(e[6])!==t.parameterSet&&Fc("suite-mismatch","ACK suite differs from the authenticated room suite"),Wc(e.subarray(8,40),n)||Fc("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)&&Fc("invalid-record","ACK reserved bytes must be zero"),{advanceCounter:r.getBigUint64(40,!1),epoch:r.getBigUint64(48,!1)}},nl=(e,t,n,r,o,a,i)=>{jc(n,"binding",Dc),zc(r,"sender counter"),zc(o,"from epoch"),zc(a,"to epoch"),o!==Nc&&a===o+1n||Fc("invalid-record","record must advance exactly one PQ epoch");const s=new Uint8Array(i);s.set(qc,0),s[4]=1,s[5]=e,s[6]=Qc(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,o,!1),c.setBigUint64(56,a,!1),s},rl=(e,t,n,r)=>{e instanceof Uint8Array||Fc("invalid-record","record must be a Uint8Array"),e.length<Lc&&Fc("invalid-record","record is shorter than its canonical header"),Wc(e.subarray(0,4),qc)||Fc("invalid-record","record magic is invalid"),1!==e[4]&&Fc("invalid-record","record version is unsupported"),e[5]!==t&&Fc("invalid-record","record type is unexpected"),0!==e[7]&&Fc("invalid-record","record reserved flags must be zero");Gc(e[6])!==n.parameterSet&&Fc("suite-mismatch","record suite differs from the authenticated room suite");const o=e.subarray(8,40);void 0===r||Wc(o,r)||Fc("binding-mismatch","record belongs to a different authenticated edge");const a=new DataView(e.buffer,e.byteOffset,e.byteLength),i=a.getBigUint64(40,!1),s=a.getBigUint64(48,!1),c=a.getBigUint64(56,!1);return s!==Nc&&c===s+1n||Fc("invalid-record","record must advance exactly one PQ epoch"),{senderCounter:i,fromEpoch:s,toEpoch:c}},ol=(e,t,n)=>{const r=rl(e,1,t,n);return e.length!==Zc(t)&&Fc("invalid-record","OFFER length is not canonical for its suite"),{...r,bytes:Uint8Array.from(e),publicKey:e.slice(Lc)}},al=(e,t,n)=>{const r=rl(e,2,t,n);e.length!==el(t)&&Fc("invalid-record","ADVANCE length is not canonical for its suite");const o=Zc(t),a=e.slice(Lc,Lc+o),i=ol(a,t,n);return i.fromEpoch===r.fromEpoch&&i.toEpoch===r.toEpoch||Fc("fork","ADVANCE epoch does not exactly match its embedded OFFER"),{...r,bytes:Uint8Array.from(e),offer:i,ciphertext:e.slice(Lc+o)}},il=(e,t)=>{if(Jc(t),!(e instanceof Uint8Array))return Fc("invalid-record","record must be a Uint8Array");if(e.length<Lc)return Fc("invalid-record","record is shorter than its canonical header");if(1===e[5]){const n=ol(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=al(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 Fc("invalid-record","record type is unknown")},sl=(e,t,n,r)=>{jc(e,"PQ root",Tc);const o=Di(e,t,r),a=((...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})(Oc,n);try{return Ti(o,a,Tc,r)}finally{o.fill(0)}},cl=(e,t)=>{const n=Uint8Array.from(e),r=Uint8Array.from(t);let o=!1;return{publicKey:n,secretKey:r,get destroyed(){return o},destroy(){o||(r.fill(0),o=!0)}}},ll=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)}}},dl=(e,t)=>"bigint"!=typeof e?Fc("invalid-record",`${t} must be a bigint`):(zc(e,t),e),ul=(e,t,n)=>{const r=(e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return Fc("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:Fc("invalid-record","snapshot.phase.kind must be an enumerable string data property")})(e);switch(r){case"idle":return Vc(e,"snapshot.phase",["kind"]),{kind:"idle"};case"outbound-offer-prepared":case"outbound-offer-dispatched":{const o=Vc(e,"snapshot.phase",["kind","offer","secretKey"]),a=ol(jc(o.offer,"snapshot.phase.offer",Zc(t)),t,n),i=jc(o.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes);return{kind:"outbound-offer",dispatched:"outbound-offer-dispatched"===r,offer:a,keyPair:cl(a.publicKey,i)}}case"inbound-offer":{const r=Vc(e,"snapshot.phase",["kind","offer"]);return{kind:"inbound-offer",offer:ol(jc(r.offer,"snapshot.phase.offer",Zc(t)),t,n)}}case"outbound-advance-prepared":{const r=Vc(e,"snapshot.phase",["kind","advance","nextRoot"]),o=al(jc(r.advance,"snapshot.phase.advance",el(t)),t,n);return{kind:"outbound-advance-prepared",offer:o.offer,advance:o,nextRoot:Uint8Array.from(jc(r.nextRoot,"snapshot.phase.nextRoot",Tc))}}case"outbound-advance-awaiting-ack":{const r=Vc(e,"snapshot.phase",["kind","advance"]),o=al(jc(r.advance,"snapshot.phase.advance",el(t)),t,n);return{kind:"outbound-advance-awaiting-ack",offer:o.offer,advance:o}}case"inbound-advance-prepared":{const r=Vc(e,"snapshot.phase",["kind","advance","secretKey","nextRoot"]),o=al(jc(r.advance,"snapshot.phase.advance",el(t)),t,n),a=jc(r.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes),i=Uint8Array.from(jc(r.nextRoot,"snapshot.phase.nextRoot",Tc));return{kind:"inbound-advance-prepared",offer:o.offer,advance:o,keyPair:cl(o.offer.publicKey,a),nextRoot:i}}case"inbound-advance-awaiting-ack-dispatch":{const r=Vc(e,"snapshot.phase",["kind","advance"]);return{kind:"inbound-advance-awaiting-ack-dispatch",advance:al(jc(r.advance,"snapshot.phase.advance",el(t)),t,n)}}default:return Fc("invalid-record","snapshot phase is unknown")}},hl=(e,t)=>{e||Fc("invalid-record",`snapshot ${t}`)},fl=(e,t)=>{Yc(t.suite,t.backend.suite),jc(t.binding,"binding",Dc);const n=Vc(e,"snapshot",["formatVersion","parameterSet","binding","rootKey","epoch","localCounter","remoteCounter","nextOfferer","phase","lastInboundOffer","lastInboundAdvance"]);1!==n.formatVersion&&Fc("invalid-record","snapshot format version is unsupported"),n.parameterSet!==t.suite.parameterSet&&Fc("suite-mismatch","snapshot suite differs from the authenticated room suite");const r=jc(n.binding,"snapshot.binding",Dc);Wc(r,t.binding)||Fc("binding-mismatch","snapshot belongs to a different authenticated edge");const o=jc(n.rootKey,"snapshot.rootKey",Tc),a=dl(n.epoch,"snapshot.epoch"),i=dl(n.localCounter,"snapshot.localCounter"),s=dl(n.remoteCounter,"snapshot.remoteCounter");if("local"!==n.nextOfferer&&"remote"!==n.nextOfferer)return Fc("invalid-record","snapshot.nextOfferer must be local or remote");const c=Uint8Array.from(o);let l;try{l=ul(n.phase,t.suite,t.binding);const e=null===n.lastInboundOffer?null:ol(jc(n.lastInboundOffer,"snapshot.lastInboundOffer",Zc(t.suite)),t.suite,t.binding),r=null===n.lastInboundAdvance?null:al(jc(n.lastInboundAdvance,"snapshot.lastInboundAdvance",el(t.suite)),t.suite,t.binding),o={rootKey:c,epoch:a,localCounter:i,remoteCounter:s,nextOfferer:n.nextOfferer,phase:l,lastInboundOffer:e,lastInboundAdvance:r};return(e=>{const{epoch:t,localCounter:n,remoteCounter:r,nextOfferer:o,phase:a,lastInboundOffer:i,lastInboundAdvance:s}=e;switch(null!==i&&(hl(i.toEpoch<=t,"last inbound OFFER is from a future epoch"),hl(i.senderCounter<r,"last inbound OFFER counter was not consumed")),null!==s&&(hl(s.toEpoch<=t,"last inbound ADVANCE is from a future epoch"),hl(s.senderCounter<r,"last inbound ADVANCE counter was not consumed")),a.kind){case"idle":return;case"outbound-offer":return void hl("local"===o&&a.offer.senderCounter===n&&a.offer.fromEpoch===t,"outbound OFFER does not match the current turn/counter/epoch");case"inbound-offer":return void hl("remote"===o&&a.offer.senderCounter===r&&a.offer.fromEpoch===t,"inbound OFFER does not match the current turn/counter/epoch");case"outbound-advance-prepared":return void hl("remote"===o&&a.advance.senderCounter===n&&a.offer.senderCounter===r&&a.advance.fromEpoch===t,"prepared outbound ADVANCE does not match current state");case"outbound-advance-awaiting-ack":return hl("local"===o&&a.advance.senderCounter+1n===n&&a.offer.senderCounter+1n===r&&a.advance.toEpoch===t,"outbound ADVANCE awaiting ACK does not match committed state"),void hl(null!==i&&Wc(i.bytes,a.offer.bytes),"outbound ADVANCE is missing its exact inbound OFFER replay record");case"inbound-advance-prepared":return void hl("local"===o&&a.advance.senderCounter===r&&a.offer.senderCounter===n&&a.advance.fromEpoch===t,"prepared inbound ADVANCE does not match current state");case"inbound-advance-awaiting-ack-dispatch":hl("remote"===o&&a.advance.senderCounter+1n===r&&a.advance.offer.senderCounter+1n===n&&a.advance.toEpoch===t,"inbound ADVANCE awaiting ACK dispatch does not match committed state"),hl(null!==s&&Wc(s.bytes,a.advance.bytes),"pending ACK is missing its exact inbound ADVANCE replay record")}})(o),o}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 ml{#e;#a;#i;#s;#c;#l;#d;#u;#h;#f={kind:"idle"};#m=null;#p=null;#y=!1;#g=!1;constructor(e){Yc(e.suite,e.backend.suite),jc(e.binding,"binding",Dc),jc(e.rootKey,"PQ root",Tc);const t=e.nextOfferer;"local"!==t&&"remote"!==t&&Fc("invalid-state","nextOfferer must be local or remote");const n=e.epoch??0n,r=e.localCounter??0n,o=e.remoteCounter??0n;zc(n,"epoch"),zc(r,"local counter"),zc(o,"remote counter"),this.#e=e.module,this.#a=e.backend,this.#i=e.suite,this.#s=Uint8Array.from(e.binding),this.#c=Uint8Array.from(e.rootKey),this.#l=n,this.#d=r,this.#u=o,this.#h=e.nextOfferer}static restore(e,t){const n=fl(e,t);try{const e=new ml({...t,rootKey:n.rootKey,epoch:n.epoch,localCounter:n.localCounter,remoteCounter:n.remoteCounter,nextOfferer:n.nextOfferer});return e.#f=n.phase,e.#m=n.lastInboundOffer,e.#p=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.#i}get phase(){return this.#g?"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.#f)}get epoch(){return this.#w(),this.#l}get localCounter(){return this.#w(),this.#d}get remoteCounter(){return this.#w(),this.#u}get nextOfferer(){return this.#w(),this.#h}get trafficBlocked(){return this.#g||"idle"!==this.#f.kind}copyRootKey(){return this.#w(),Uint8Array.from(this.#c)}snapshot(){return this.#b(),{formatVersion:1,parameterSet:this.#i.parameterSet,binding:Uint8Array.from(this.#s),rootKey:Uint8Array.from(this.#c),epoch:this.#l,localCounter:this.#d,remoteCounter:this.#u,nextOfferer:this.#h,phase:ll(this.#f),lastInboundOffer:null===this.#m?null:Uint8Array.from(this.#m.bytes),lastInboundAdvance:null===this.#p?null:Uint8Array.from(this.#p.bytes)}}clone(){const e=this.snapshot();try{return ml.restore(e,{module:this.#e,backend:this.#a,suite:this.#i,binding:this.#s})}finally{pl(e)}}adopt(e){this.#b(),e.#b(),e===this&&Fc("invalid-state","cannot adopt a machine into itself"),this.#i.parameterSet===e.#i.parameterSet&&Wc(this.#s,e.#s)||Fc("invalid-state","cannot adopt a machine from another suite or authenticated edge"),this.#v(this.#f),this.#c.fill(0),this.#c=e.#c,this.#l=e.#l,this.#d=e.#d,this.#u=e.#u,this.#h=e.#h,this.#f=e.#f,this.#m=e.#m,this.#p=e.#p,e.#c=new Uint8Array(Tc),e.#s.fill(0),e.#f={kind:"idle"},e.#m=null,e.#p=null,e.#g=!0}copyPendingOutboundRecord(){this.#b();const e=this.#f;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):Fc("invalid-state","there is no pending outbound record")}async prepareOffer(){let e;this.#k();try{"idle"!==this.#f.kind&&Fc("invalid-state","cannot prepare an OFFER while another transition is pending"),"local"!==this.#h&&Fc("wrong-turn","the remote peer owns the next OFFER turn"),this.#I(),e=await this.#a.generateKeyPair(),this.#w(),jc(e.publicKey,"ML-KEM public key",this.#i.publicKeyBytes),jc(e.secretKey,"ML-KEM secret key",this.#i.secretKeyBytes);const t=((e,t,n,r,o)=>{jc(o,"ML-KEM public key",e.publicKeyBytes);const a=nl(1,e,t,n,r,r+1n,Zc(e));return a.set(o,Lc),a})(this.#i,this.#s,this.#d,this.#l,e.publicKey),n=ol(t,this.#i,this.#s);return this.#f={kind:"outbound-offer",dispatched:!1,offer:n,keyPair:e},e=void 0,Uint8Array.from(t)}finally{e?.destroy(),this.#S()}}markOfferDispatched(){this.#b();const e=this.#f;if("outbound-offer"!==e.kind)return Fc("invalid-state","there is no outbound OFFER to dispatch");e.dispatched&&Fc("invalid-state","outbound OFFER was already marked dispatched"),this.#f={...e,dispatched:!0}}abortUnsentOffer(){this.#b();const e=this.#f;if("outbound-offer"!==e.kind||e.dispatched)return Fc("invalid-state","only an undispatched OFFER can be aborted");e.keyPair.destroy(),this.#f={kind:"idle"}}acceptAuthenticatedOffer(e){this.#b();const t=ol(e,this.#i,this.#s);this.#C(t),"idle"!==this.#f.kind&&Fc("invalid-state","another PQ healing transition is pending"),"remote"!==this.#h&&Fc("wrong-turn","the local peer owns the next OFFER turn"),this.#A(t.senderCounter),this.#E(t.fromEpoch),this.#I(),this.#f={kind:"inbound-offer",offer:t}}async prepareAdvance(){let e;this.#k();try{const t=this.#f;if("inbound-offer"!==t.kind)return Fc("invalid-state","an authenticated inbound OFFER is required");$c(this.#d,"local counter"),e=await this.#a.encapsulate(t.offer.publicKey),this.#w(),jc(e.ciphertext,"ML-KEM ciphertext",this.#i.ciphertextBytes),jc(e.sharedSecret,"ML-KEM shared secret",this.#i.sharedSecretBytes);const n=((e,t,n,r,o)=>{jc(o,"ML-KEM ciphertext",e.ciphertextBytes);const a=nl(2,e,t,n,r.fromEpoch,r.toEpoch,el(e));return a.set(r.bytes,Lc),a.set(o,Lc+r.bytes.length),a})(this.#i,this.#s,this.#d,t.offer,e.ciphertext),r=al(n,this.#i,this.#s),o=sl(this.#c,e.sharedSecret,n,this.#e);return this.#f={kind:"outbound-advance-prepared",offer:t.offer,advance:r,nextRoot:o},Uint8Array.from(n)}finally{e?.destroy(),this.#S()}}commitPreparedAdvance(){this.#b();const e=this.#f;return"outbound-advance-prepared"!==e.kind?Fc("invalid-state","there is no prepared outbound ADVANCE"):(this.#P(e.nextRoot),this.#l=e.advance.toEpoch,this.#d+=1n,this.#u+=1n,this.#h="local",this.#m=e.offer,this.#f={kind:"outbound-advance-awaiting-ack",offer:e.offer,advance:e.advance},Uint8Array.from(e.advance.bytes))}acceptAuthenticatedAdvanceAcknowledgement(e){this.#b();const t=Hc(e),n=this.#f;if("outbound-advance-awaiting-ack"!==n.kind)return Fc("invalid-state","no outbound ADVANCE is awaiting acknowledgement");t.epoch===this.#l&&t.advanceCounter===n.advance.senderCounter||Fc("invalid-record","advance acknowledgement does not bind the pending transition"),this.#f={kind:"idle"}}async acceptAuthenticatedAdvance(e){let t;this.#k();try{const n=al(e,this.#i,this.#s);this.#x(n);const r=this.#f;if("outbound-offer"!==r.kind||!r.dispatched)return Fc("invalid-state","a dispatched outbound OFFER is required before ADVANCE");this.#A(n.senderCounter),this.#E(n.fromEpoch),Wc(n.offer.bytes,r.offer.bytes)||Fc("fork","ADVANCE answers a different OFFER"),t=await this.#a.decapsulate(n.ciphertext,r.keyPair.secretKey),this.#w(),jc(t.sharedSecret,"ML-KEM shared secret",this.#i.sharedSecretBytes);const o=sl(this.#c,t.sharedSecret,n.bytes,this.#e);this.#f={kind:"inbound-advance-prepared",offer:r.offer,advance:n,keyPair:r.keyPair,nextRoot:o}}finally{t?.destroy(),this.#S()}}commitAcceptedAdvance(){this.#b();const e=this.#f;return"inbound-advance-prepared"!==e.kind?Fc("invalid-state","there is no accepted ADVANCE to commit"):(e.keyPair.destroy(),this.#P(e.nextRoot),this.#l=e.advance.toEpoch,this.#d+=1n,this.#u+=1n,this.#h="remote",this.#p=e.advance,this.#f={kind:"inbound-advance-awaiting-ack-dispatch",advance:e.advance},{epoch:this.#l,advanceCounter:e.advance.senderCounter})}markAdvanceAcknowledgementDispatched(e){this.#b();const t=Hc(e),n=this.#f;if("inbound-advance-awaiting-ack-dispatch"!==n.kind)return Fc("invalid-state","no advance acknowledgement is pending dispatch");t.epoch===this.#l&&t.advanceCounter===n.advance.senderCounter||Fc("invalid-record","advance acknowledgement does not bind the committed transition"),this.#f={kind:"idle"}}destroy(){this.#g||(this.#v(this.#f),this.#c.fill(0),this.#s.fill(0),this.#m=null,this.#p=null,this.#f={kind:"idle"},this.#g=!0)}#w(){this.#g&&Fc("destroyed","state machine is destroyed")}#b(){this.#w(),this.#y&&Fc("invalid-state","another asynchronous transition is in flight")}#k(){this.#b(),this.#y=!0}#S(){this.#y=!1}#I(){$c(this.#l,"epoch"),$c(this.#d,"local counter"),$c(this.#u,"remote counter")}#A(e){e<this.#u&&Fc("replay","record sender counter was already consumed"),e>this.#u&&Fc("counter-gap","record sender counter skips an expected transition")}#E(e){e<this.#l&&Fc("replay","record PQ epoch was already consumed"),e>this.#l&&Fc("epoch-gap","record skips the current PQ epoch")}#C(e){let t=this.#m;const n=this.#f;var r,o;("inbound-offer"!==n.kind&&"outbound-advance-prepared"!==n.kind&&"outbound-advance-awaiting-ack"!==n.kind||(t=n.offer),null!==t&&(o=t,(r=e).senderCounter===o.senderCounter&&r.fromEpoch===o.fromEpoch&&r.toEpoch===o.toEpoch))&&(Wc(e.bytes,t.bytes)&&Fc("replay","OFFER is an exact replay"),Fc("fork","different OFFER bytes reuse an authenticated slot"))}#x(e){let t=this.#p;const n=this.#f;var r,o;("inbound-advance-prepared"!==n.kind&&"inbound-advance-awaiting-ack-dispatch"!==n.kind||(t=n.advance),null!==t&&(o=t,(r=e).senderCounter===o.senderCounter&&r.fromEpoch===o.fromEpoch&&r.toEpoch===o.toEpoch))&&(Wc(e.bytes,t.bytes)&&Fc("replay","ADVANCE is an exact replay"),Fc("fork","different ADVANCE bytes reuse an authenticated slot"))}#P(e){jc(e,"candidate PQ root",Tc),this.#c.fill(0),this.#c=e}#v(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 pl=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)}},yl=H-69-C,gl=(1n<<64n)-1n,wl=(new TextEncoder).encode("p2party/pq-control-frame/key/v1\0");class bl extends Error{code;constructor(e,t){super(`pqHealingFrame: ${t}`),this.name="PqControlFrameError",this.code=e}}const vl=(e,t)=>{throw new bl(e,t)},kl=(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},Il=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&vl("invalid-frame",`${t} must be exactly ${String(n)} bytes`),e):vl("invalid-frame",`${t} must be a Uint8Array`),Sl=(e,t)=>"bigint"!=typeof e||e<0n||e>gl?vl("invalid-frame",`${t} must be an unsigned 64-bit bigint`):e,Cl=(e,t,n,r,o,a)=>{Il(n,"PQ root",Tc),Il(r,"binding",Dc);const i=(e=>{const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t})(Sl(a,"keyEpoch")),s=new Uint8Array(wl.length+1+1+r.length+i.length);s.set(wl,0),s[wl.length]=(e=>{const t=Pc(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?vl("invalid-frame","ML-KEM suite descriptor is not canonical"):768===e.parameterSet?1:512===e.parameterSet?2:1024===e.parameterSet?3:vl("invalid-frame","ML-KEM suite is unsupported")})(t),s[wl.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:vl("invalid-direction","control direction is unknown"))(o),s.set(r,wl.length+2),s.set(i,wl.length+2+r.length);const c=Di(n,r,e);try{return Ti(c,s,I,e)}finally{c.fill(0),i.fill(0)}},Al=(e,t,n)=>{if(Il(e,"control record"),64===e.length){const r=tl(e,t,n);return{counter:r.advanceCounter,keyEpoch:r.epoch}}const r=il(e,t);return kl(r.binding,n)?{counter:r.senderCounter,keyEpoch:r.fromEpoch}:vl("binding-mismatch","control record belongs to another authenticated edge")},El=e=>{const t=Il(e.binding,"binding",Dc),n=Sl(e.keyEpoch,"keyEpoch"),r=Al(e.record,e.suite,t);r.keyEpoch!==n&&vl("epoch-mismatch","control record is not authenticated under its required epoch"),e.record.length>yl-4&&vl("invalid-frame","control record does not fit the uniform cell");const o=(()=>{const e=new Uint8Array(S);return crypto.getRandomValues(e),e})(),a=new Uint8Array(69);a[0]=5,a.set(t,1);const i=new DataView(a.buffer,a.byteOffset,a.byteLength);i.setBigUint64(33,r.counter,!1),i.setBigUint64(49,n,!1),a.set(o,57);const s=new Uint8Array(yl);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e.record.length,!1),s.set(e.record,4);const c=Cl(e.module,e.suite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,o)=>{const a=r.length+C,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(o.length),d=e._malloc(a);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,o.length).set(o),0!==e._encrypt_chachapoly_symmetric(d,c,r.length,i,s,l,o.length)?vl("invalid-frame","control-frame AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,a))}finally{Do(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),Do(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),Do(e,new Uint8Array(e.wasmMemory.buffer,d,a))}})(e.module,c,o,s,a),n=new Uint8Array(H);return n.set(a,0),n.set(t,69),n}finally{c.fill(0),s.fill(0)}},Pl=e=>{const t=Il(e.frame,"control frame",H),n=Il(e.binding,"binding",Dc),r=Sl(e.keyEpoch,"keyEpoch");5!==t[0]&&vl("invalid-frame","frame type is not PQ control"),kl(t.subarray(1,33),n)||vl("binding-mismatch","control frame belongs to another edge");const o=t.subarray(0,69),a=new DataView(t.buffer,t.byteOffset,t.byteLength),i=a.getBigUint64(33,!1);0n!==a.getBigUint64(41,!1)&&vl("invalid-frame","control-frame reserved header must be zero"),a.getBigUint64(49,!1)!==r&&vl("epoch-mismatch","control-frame epoch is not the expected epoch");const s=t.subarray(57,69),c=t.subarray(69),l=Cl(e.module,e.suite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,o)=>{const a=r.length-C,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(o.length),d=e._malloc(a);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,o.length).set(o);const u=new Uint8Array(e.wasmMemory.buffer,d,a);return u.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,r.length,i,s,l,o.length)?vl("authentication-failed","control-frame authentication failed"):Uint8Array.from(u)}finally{Do(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),Do(e,new Uint8Array(e.wasmMemory.buffer,d,a))}})(e.module,l,s,c,o);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,!1);(0===t||t>yl-4)&&vl("invalid-padding","encrypted control-record length is invalid");const a=4+t;let u=0;for(let e=a;e<d.length;e+=1)u|=d[e];0!==u&&vl("invalid-padding","encrypted control padding must be all zero");const h=d.slice(4,a),f=Al(h,e.suite,n);return f.keyEpoch!==r&&vl("epoch-mismatch","decrypted control record does not match its frame epoch"),f.counter!==i&&vl("record-mismatch","decrypted control counter does not match its public header"),h}finally{l.fill(0),d?.fill(0)}},xl=new Uint8Array([80,50,69,68,71,69,52,0]),Rl=(1n<<64n)-1n,Ml=262144,Kl=Math.min(Y,256),Ul=/^[0-9a-f]{64}:[0-9]+:[0-9]+$/,_l=new TextEncoder,Dl=new TextDecoder("utf-8",{fatal:!0}),Tl=e=>{throw new Error(`pqHealingRuntime: ${e}`)},Ll=(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},ql=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&Tl(`${t} must be exactly ${String(n)} bytes`),e):Tl(`${t} must be a Uint8Array`),Ol=(e,t)=>"number"!=typeof e||!Number.isSafeInteger(e)||e<0?Tl(`${t} must be a non-negative safe integer`):e,Nl=e=>1===e?"local":2===e?"remote":Tl("checkpoint has an invalid next-offerer turn");class Bl{#R=[];#M=0;bytes(e){const t=Uint8Array.from(e);this.#R.push(t),this.#M+=t.length,this.#M>Ml&&Tl("checkpoint exceeds the encrypted edge-state budget")}u8(e){(!Number.isInteger(e)||e<0||e>255)&&Tl("u8 value is out of range"),this.bytes(Uint8Array.of(e))}u16(e){(!Number.isInteger(e)||e<0||e>65535)&&Tl("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)&&Tl("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>Rl)&&Tl(`${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&&Tl("present checkpoint byte strings must not be empty"),this.u32(e.length),this.bytes(e)):this.u32(0)}finish(){const e=new Uint8Array(this.#M);let t=0;try{for(const n of this.#R)e.set(n,t),t+=n.length;return e}finally{for(const e of this.#R)e.fill(0);this.#R.length=0,this.#M=0}}}class Fl{#K;#U=0;constructor(e){(0===e.length||e.length>Ml)&&Tl("checkpoint length is invalid"),this.#K=Uint8Array.from(e)}take(e){if(!Number.isSafeInteger(e)||e<0||this.#U+e>this.#K.length)return Tl("checkpoint is truncated");const t=this.#K.slice(this.#U,this.#U+e);return this.#U+=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?Tl("checkpoint field exceeds its budget"):this.take(t)}finish(){this.#U!==this.#K.length&&Tl("checkpoint contains trailing bytes")}destroy(){this.#K.fill(0),this.#U=this.#K.length}}const jl=(e,t,n)=>e.sized(t)??Tl(`${n} is missing`),zl=(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:jl(e,n,"prepared OFFER"),secretKey:jl(e,t.secretKeyBytes,"prepared OFFER secret key")};case 2:return{kind:"outbound-offer-dispatched",offer:jl(e,n,"dispatched OFFER"),secretKey:jl(e,t.secretKeyBytes,"dispatched OFFER secret key")};case 3:return{kind:"inbound-offer",offer:jl(e,n,"inbound OFFER")};case 4:return{kind:"outbound-advance-prepared",advance:jl(e,r,"prepared ADVANCE"),nextRoot:jl(e,32,"candidate PQ root")};case 5:return{kind:"outbound-advance-awaiting-ack",advance:jl(e,r,"outbound ADVANCE")};case 6:return{kind:"inbound-advance-prepared",advance:jl(e,r,"inbound ADVANCE"),secretKey:jl(e,t.secretKeyBytes,"inbound ADVANCE secret key"),nextRoot:jl(e,32,"candidate PQ root")};case 7:return{kind:"inbound-advance-awaiting-ack-dispatch",advance:jl(e,r,"acknowledged ADVANCE")};default:return Tl("checkpoint has an unknown PQ phase")}},$l=e=>{for(const t of e.values())t.fill(0);e.clear()};class Hl{#e;#_;#D;#i;#a;#s;#T;#L;#q;#O;#N=null;#B=null;#F=null;#j=null;#z=new Map;#$=0;#H;#g=!1;constructor(e){const t=ne(e.pqMode);re(e.pqMode)!==e.rootSuite&&Tl("authenticated root suite and room PQ mode disagree"),ql(e.binding,"edge binding",32),ql(e.rootKey,"PQ root",32),this.#e=e.module,this.#_=e.pqMode,this.#D=e.rootSuite,this.#i=Pc(t),this.#a=_c(e.module,this.#i),this.#s=Uint8Array.from(e.binding),this.#q=new ml({module:e.module,backend:this.#a,suite:this.#i,binding:this.#s,rootKey:e.rootKey,nextOfferer:e.nextOfferer}),this.#O=this.#q.copyRootKey(),this.#H=Ol(e.now??Date.now(),"initial healing time"),this.#T=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#L=e.amInitiator?"responder-to-initiator":"initiator-to-responder"}get pqMode(){return this.#_}get rootSuite(){return this.#D}get epoch(){return this.#V(),this.#q.epoch}get phase(){return this.#q.phase}get trafficBlocked(){return this.#g||this.#q.trafficBlocked}get nextOfferer(){return this.#q.nextOfferer}get activeReceiveKeys(){return this.#V(),this.#z}get messagesSinceHealing(){return this.#V(),this.#$}get lastHealedAt(){return this.#V(),this.#H}currentMessageContext(){return this.#V(),{rootKey:this.#O,binding:this.#s,rootSuite:this.#D,epoch:this.#q.epoch}}resolveMessageContext(e){return this.#V(),e===this.#q.epoch?this.currentMessageContext():null}noteApplicationMessage(){this.#V(),this.#$>=Number.MAX_SAFE_INTEGER&&Tl("application-message counter overflow"),this.#$+=1}healingDue(e=Date.now()){return this.#V(),Ol(e,"healing clock"),!this.#q.trafficBlocked&&"local"===this.#q.nextOfferer&&(this.#$>=64||e-this.#H>=864e5)}copyPendingFrame(){return this.#V(),this.#N?Uint8Array.from(this.#N.frame):null}get pendingRetryAt(){return this.#V(),this.#N?.nextRetryAt??null}get pendingAttempts(){return this.#V(),this.#N?.attempts??0}markPendingDispatched(e=Date.now()){this.#V();const t=this.#N;if(!t)return Tl("there is no PQ control outbox");Ol(e,"dispatch clock"),t.attempts>=8&&Tl("PQ control retry budget is exhausted"),this.#N={kind:t.kind,frame:t.frame,attempts:t.attempts+1,nextRetryAt:e+5e3}}async prepareHealingOffer(e=Date.now()){this.#V(),this.healingDue(e)||Tl("a local sparse-PQ healing exchange is not due");const t=await this.#q.prepareOffer(),n=this.#q.copyRootKey();try{const r=El({module:this.#e,suite:this.#i,rootKey:n,binding:this.#s,direction:this.#T,keyEpoch:this.#q.epoch,record:t});return this.#q.markOfferDispatched(),this.#N?.frame.fill(0),this.#N={kind:"offer",frame:Uint8Array.from(r),attempts:0,nextRetryAt:e},this.#W(),r}finally{n.fill(0),t.fill(0)}}async acceptControlFrame(e,t=Date.now()){if(this.#V(),ql(e,"PQ control frame",H),Ol(t,"control clock"),this.#B&&"advance"===this.#N?.kind&&Ll(e,this.#B))return{dispatch:Uint8Array.from(this.#N.frame),changed:!1};if(this.#F&&this.#j&&Ll(e,this.#F))return{dispatch:Uint8Array.from(this.#j),changed:!1};const n=this.#q.copyRootKey();let r=null;try{if(r=Pl({module:this.#e,suite:this.#i,rootKey:n,binding:this.#s,direction:this.#L,keyEpoch:this.#q.epoch,frame:e}),64===r.length){const e=this.#N;if("advance"!==e?.kind)return Tl("unexpected PQ ADVANCE acknowledgement");const n=tl(r,this.#i,this.#s);return this.#q.acceptAuthenticatedAdvanceAcknowledgement(n),e.frame.fill(0),this.#N=null,this.#W(),this.#$=0,this.#H=t,this.#Q(),{dispatch:null,changed:!0}}if("offer"===il(r,this.#i).type){this.#q.acceptAuthenticatedOffer(r);const o=await this.#q.prepareAdvance();let a;try{a=El({module:this.#e,suite:this.#i,rootKey:n,binding:this.#s,direction:this.#T,keyEpoch:this.#q.epoch,record:o}),this.#q.commitPreparedAdvance()}finally{o.fill(0)}return this.#N?.frame.fill(0),this.#N={kind:"advance",frame:Uint8Array.from(a),attempts:0,nextRetryAt:t},this.#B?.fill(0),this.#B=Uint8Array.from(e),this.#F?.fill(0),this.#F=null,this.#j?.fill(0),this.#j=null,this.#Q(),{dispatch:a,changed:!0}}const o=this.#N;if("offer"!==o?.kind)return Tl("unexpected PQ ADVANCE without a persisted OFFER");await this.#q.acceptAuthenticatedAdvance(r);const a=this.#q.commitAcceptedAdvance(),i=((e,t,n)=>{Jc(t),jc(n,"binding",Dc);const r=Hc(e),o=new Uint8Array(64);o.set(qc,0),o[4]=1,o[5]=3,o[6]=Qc(t.parameterSet),o[7]=0,o.set(n,8);const a=new DataView(o.buffer,o.byteOffset,o.byteLength);return a.setBigUint64(40,r.advanceCounter,!1),a.setBigUint64(48,r.epoch,!1),o})(a,this.#i,this.#s),s=this.#q.copyRootKey();try{const n=El({module:this.#e,suite:this.#i,rootKey:s,binding:this.#s,direction:this.#T,keyEpoch:a.epoch,record:i});return this.#q.markAdvanceAcknowledgementDispatched(a),o.frame.fill(0),this.#N=null,this.#F?.fill(0),this.#F=Uint8Array.from(e),this.#j?.fill(0),this.#j=Uint8Array.from(n),this.#B?.fill(0),this.#B=null,this.#$=0,this.#H=t,this.#Q(),{dispatch:n,changed:!0}}finally{s.fill(0),i.fill(0)}}finally{n.fill(0),r?.fill(0)}}clone(){this.#V();const e=this.#q.copyRootKey();let t=null;try{return t=new Hl({module:this.#e,pqMode:this.#_,rootSuite:this.#D,binding:this.#s,rootKey:e,nextOfferer:this.#q.nextOfferer,amInitiator:"initiator-to-responder"===this.#T,now:this.#H}),t.#q.destroy(),t.#q=this.#q.clone(),t.#O.fill(0),t.#O=Uint8Array.from(this.#O),t.#N=null===(n=this.#N)?null:{kind:n.kind,frame:Uint8Array.from(n.frame),attempts:n.attempts,nextRetryAt:n.nextRetryAt},t.#B=null===this.#B?null:Uint8Array.from(this.#B),t.#F=null===this.#F?null:Uint8Array.from(this.#F),t.#j=null===this.#j?null:Uint8Array.from(this.#j),t.#z=(e=>{const t=new Map;for(const[n,r]of e)t.set(n,Uint8Array.from(r));return t})(this.#z),t.#$=this.#$,t.#H=this.#H,t}catch(e){throw t?.destroy(),e}finally{e.fill(0)}var n}adopt(e){this.#V(),e.#V(),e===this&&Tl("cannot adopt a PQ runtime into itself"),e.#e===this.#e&&e.#_===this.#_&&e.#D===this.#D&&e.#T===this.#T&&Ll(e.#s,this.#s)||Tl("cannot adopt a PQ runtime from another authenticated edge"),this.#q.destroy(),this.#O.fill(0),this.#N?.frame.fill(0),this.#B?.fill(0),this.#F?.fill(0),this.#j?.fill(0),$l(this.#z),this.#q=e.#q,this.#O=e.#O,this.#N=e.#N,this.#B=e.#B,this.#F=e.#F,this.#j=e.#j,this.#z=e.#z,this.#$=e.#$,this.#H=e.#H,e.#O=new Uint8Array(32),e.#N=null,e.#B=null,e.#F=null,e.#j=null,e.#z=new Map,e.#s.fill(0),e.#g=!0}serialize(e=this.#z){this.#V();const t=this.#q.snapshot(),n=new Bl;try{return n.bytes(xl),n.u8(1),n.u8(512===(o=this.#i.parameterSet)?1:768===o?2:1024===o?3:Tl("unsupported ML-KEM suite")),n.u8("initiator-to-responder"===this.#T?1:2),n.u8(0),n.u64(BigInt(this.#H)),n.u64(BigInt(this.#$)),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:Tl("invalid next-offerer turn")),((e,t)=>{switch(e.u8((e=>{switch(e.kind){case"idle":return 0;case"outbound-offer-prepared":return 1;case"outbound-offer-dispatched":return 2;case"inbound-offer":return 3;case"outbound-advance-prepared":return 4;case"outbound-advance-awaiting-ack":return 5;case"inbound-advance-prepared":return 6;case"inbound-advance-awaiting-ack-dispatch":return 7}})(t)),t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return e.sized(t.offer),void e.sized(t.secretKey);case"inbound-offer":return void e.sized(t.offer);case"outbound-advance-prepared":return e.sized(t.advance),void e.sized(t.nextRoot);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void e.sized(t.advance);case"inbound-advance-prepared":e.sized(t.advance),e.sized(t.secretKey),e.sized(t.nextRoot)}})(n,t.phase),n.sized(t.lastInboundOffer),n.sized(t.lastInboundAdvance),((e,t)=>{null!==t?(e.u8("offer"===t.kind?1:2),e.u8(t.attempts),e.u64(BigInt(t.nextRetryAt)),e.sized(t.frame)):e.u8(0)})(n,this.#N),n.sized(this.#B),n.sized(this.#F),n.sized(this.#j),((e,t)=>{t.size>Kl&&Tl("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){Ul.test(t)||Tl("active receive cache key is non-canonical");const n=_l.encode(t);(0===n.length||n.length>160)&&Tl("active receive cache key length is invalid"),ql(r,"active receive message key",32),e.u16(n.length),e.bytes(n),e.bytes(r)}})(n,e),n.finish()}finally{pl(t)}var r,o}static readCheckpointBinding(e){ql(e,"checkpoint");const t=xl.length+1+1+1+1+8+8;return e.length<t+32?Tl("checkpoint is too short to contain a binding"):e.slice(t,t+32)}static restore(e,t){ql(e,"encrypted edge checkpoint plaintext"),ql(t.binding,"expected edge binding",32);const n=new Fl(e);let r=null,o=null,a=null,i=null,s=null,c=null,l=null,d=null;try{const e=n.take(xl.length),h=Ll(e,xl);e.fill(0),h||Tl("checkpoint magic is invalid"),1!==n.u8()&&Tl("checkpoint version is unsupported");const f=1===(u=n.u8())?512:2===u?768:3===u?1024:Tl("checkpoint has an unknown ML-KEM suite");f!==ne(t.pqMode)&&Tl("checkpoint suite disagrees with the authenticated room policy"),re(t.pqMode)!==t.rootSuite&&Tl("authenticated root suite and room PQ mode disagree");const m=n.u8();m!==(t.amInitiator?1:2)&&Tl("checkpoint belongs to the opposite edge direction"),0!==n.u8()&&Tl("checkpoint reserved byte is non-zero");const p=n.u64(),y=n.u64();(p>BigInt(Number.MAX_SAFE_INTEGER)||y>BigInt(Number.MAX_SAFE_INTEGER))&&Tl("checkpoint counters exceed the safe-integer range");const g=n.take(32);Ll(g,t.binding)||Tl("checkpoint belongs to another authenticated edge");const w=n.take(32),b=Pc(f);r={formatVersion:1,parameterSet:f,binding:g,rootKey:w,epoch:n.u64(),localCounter:n.u64(),remoteCounter:n.u64(),nextOfferer:Nl(n.u8()),phase:zl(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 Tl("checkpoint outbox kind is invalid");const n=e.u8();n>8&&Tl("checkpoint outbox attempts exceed the retry budget");const r=e.u64();r>BigInt(Number.MAX_SAFE_INTEGER)&&Tl("checkpoint retry deadline exceeds the safe-integer range");const o=jl(e,H,"outbox frame");return ql(o,"outbox frame",H),{kind:1===t?"offer":"advance",attempts:n,nextRetryAt:Number(r),frame:o}})(n),c=n.sized(H),l=n.sized(H),d=n.sized(H);for(const e of[c,l,d])e&&ql(e,"cached control frame",H);i=(e=>{const t=e.u16();t>Kl&&Tl("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)&&Tl("checkpoint active receive cache key length is invalid");const r=e.take(t);let o;try{o=Dl.decode(r)}finally{r.fill(0)}0!==o.length&&Ul.test(o)&&!n.has(o)||Tl("checkpoint active receive cache key is non-canonical"),n.set(o,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=_c(t.module,b);o=ml.restore(r,{module:t.module,backend:v,suite:b,binding:t.binding});const k=o.copyRootKey();try{a=new Hl({module:t.module,pqMode:t.pqMode,rootSuite:t.rootSuite,binding:t.binding,rootKey:k,nextOfferer:o.nextOfferer,amInitiator:t.amInitiator,now:Number(p)})}finally{k.fill(0)}return a.#q.destroy(),a.#q=o,o=null,a.#O.fill(0),a.#O=a.#q.copyRootKey(),a.#N=s,s=null,a.#B=c,c=null,a.#F=l,l=null,a.#j=d,d=null,a.#z=i,i=null,a.#$=Number(y),a.#G(),a}catch(e){throw a?.destroy(),e}finally{n.destroy(),r&&pl(r),o?.destroy(),s?.frame.fill(0),c?.fill(0),l?.fill(0),d?.fill(0),i&&$l(i)}var u}destroy(){this.#g||(this.#q.destroy(),this.#s.fill(0),this.#O.fill(0),this.#N?.frame.fill(0),this.#B?.fill(0),this.#F?.fill(0),this.#j?.fill(0),$l(this.#z),this.#N=null,this.#B=null,this.#F=null,this.#j=null,this.#g=!0)}#Q(){const e=this.#q.copyRootKey();this.#O.fill(0),this.#O=e}#W(){this.#B?.fill(0),this.#F?.fill(0),this.#j?.fill(0),this.#B=null,this.#F=null,this.#j=null}#G(){const e=this.#q.phase;("outbound-offer-dispatched"===e&&"offer"!==this.#N?.kind||"outbound-advance-awaiting-ack"===e&&"advance"!==this.#N?.kind||"offer"===this.#N?.kind&&"outbound-offer-dispatched"!==e||"advance"===this.#N?.kind&&"outbound-advance-awaiting-ack"!==e)&&Tl("checkpoint PQ phase and sealed outbox disagree"),null!==this.#B&&"advance"!==this.#N?.kind&&Tl("checkpoint cached OFFER has no matching ADVANCE outbox"),null===this.#F!=(null===this.#j)&&Tl("checkpoint ADVANCE replay and ACK cache must be paired"),null!==this.#B&&null!==this.#F&&Tl("checkpoint contains mutually exclusive replay caches")}#V(){this.#g&&Tl("state is destroyed")}}const Vl=/a=fingerprint:sha-256\s+([0-9A-Fa-f:]+)/,Wl=e=>{const t=Vl.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)},Ql=new TextEncoder,Gl=Ql.encode("CPaceRistretto255"),Xl=Ql.encode("CPaceRistretto255_ISK"),Jl=new Uint8Array(0),Yl=(e,t,n)=>{if(t.length!==n)throw new Error(`cpace: ${e} must be ${n} bytes`)},Zl=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)},ed=(e,t,n,r=!1)=>{if(0===n.length)return;const o=e._malloc(n.length),a=new Uint8Array(e.wasmMemory.buffer,o,n.length);try{if(a.set(n),0!==e._sha512_update(t,o,n.length))throw new Error("sha512_update failed")}finally{r?Do(e,a):e._free(o)}},td=(e,t,n)=>{ed(e,t,Zl(n.data.length)),ed(e,t,n.data,n.secret)},nd=(e,t,n,r)=>{const o=Math.max(0,127-(Zl(Gl.length).length+Gl.length)-(Zl(e.length).length+e.length)),a=((e,t)=>{const n=e._malloc(g),r=e._malloc(y),o=new Uint8Array(e.wasmMemory.buffer,n,g),a=new Uint8Array(e.wasmMemory.buffer,r,y);try{if(o.fill(0),a.fill(0),0!==e._sha512_init(n))throw new Error("sha512_init failed");for(const r of t)td(e,n,r);if(0!==e._sha512_final(n,r))throw new Error("sha512_final failed");return Uint8Array.from(a)}finally{Do(e,o),Do(e,a)}})(r,[{data:Gl},{data:e,secret:!0},{data:new Uint8Array(o)},{data:n},{data:t}]),i=r._malloc(P),s=r._malloc(E),c=new Uint8Array(r.wasmMemory.buffer,i,P),l=new Uint8Array(r.wasmMemory.buffer,s,E);try{return c.set(a),l.fill(0),r._cpace_ristretto255_from_hash(s,i),Uint8Array.from(l)}finally{a.fill(0),Do(r,c),r._free(s)}},rd=(new TextEncoder).encode("p2party-interactive-3dh-v2"),od=new Uint8Array(64),ad=e=>{const t=new Uint8Array(V.length+e.length);return t.set(V,0),t.set(e,V.length),t},id=async(e,t,n)=>qo(ad(e),t,n),sd=async(e,t,n,r)=>Oo(ad(e),t,n,r),cd=Object.freeze({HELLO:1,CONFIRM:2,FINISH:3}),ld=e=>{const t=Pc(ne(e));return Object.freeze({[cd.HELLO]:193+t.publicKeyBytes+t.ciphertextBytes,[cd.CONFIRM]:97,[cd.FINISH]:65})},dd=Object.freeze({"hybrid-mlkem512":ld("hybrid-mlkem512"),"hybrid-mlkem768":ld("hybrid-mlkem768"),"hybrid-mlkem1024":ld("hybrid-mlkem1024")}),ud=(e,t="hybrid-mlkem768")=>dd[t][e];Math.max(...Object.values(dd).flatMap(e=>Object.values(e)));const hd=(e,t,n="hybrid-mlkem768")=>e.length===ud(t,n)&&e[0]===t,fd=e=>{const t=(e=>{if("hybrid-mlkem768"===e)return j;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 o=new Uint8Array(r);let a=0;for(const e of n)o.set(e,a),a+=e.length;return o},md=(new TextEncoder).encode("p2party-v4-hs-kc-transcript-v4"),pd=(new TextEncoder).encode("p2party-v4-hs-kc-responder-v4"),yd=(new TextEncoder).encode("p2party-v4-hs-kc-initiator-ratchet-dh-v4"),gd=(new TextEncoder).encode("p2party-v4-hs-kc-responder-finish-v4"),wd=new Uint8Array(64),bd=(new TextEncoder).encode("p2party-v4-pq-healing-extract-v1"),vd=(new TextEncoder).encode("p2party-v4-pq-healing-root-v1"),kd=(new TextEncoder).encode("p2party-v4-pq-healing-binding-v1\0"),Id=129,Sd=ud(cd.CONFIRM),Cd=ud(cd.FINISH),Ad=(e,t,n)=>{const r=n._malloc(e.length),o=n._malloc(t.length),a=n._malloc(64);try{new Uint8Array(n.wasmMemory.buffer,r,e.length).set(e),new Uint8Array(n.wasmMemory.buffer,o,t.length).set(t);if(0!==n._hkdf_sha512_extract(a,r,e.length,o,t.length))throw new Error("handshake hmac_sha512 failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,a,64))}finally{Do(n,new Uint8Array(n.wasmMemory.buffer,r,e.length)),n._free(o),n._free(a)}},Ed=e=>{let t=0;for(const n of e)t|=n;return 0===t},Pd=(e,t)=>{const n=new Uint8Array(Sd);return n[0]=cd.CONFIRM,n.set(e,1),n.set(t,33),n},xd=async(e,t,n)=>{const{mode:r,pqMode:o="hybrid-mlkem768",pin:a,channelInput:i,amInitiator:s,idSelfSec:c,selfIdentityX25519Pub:l,selfIdentityCrossSignature:d,peerIdentityEd25519Pub:u}=t,h=(e=>{const t=Pc(ne(e));return{suite:t,publicKeyOffset:193,ciphertextOffset:193+t.publicKeyBytes,length:ud(cd.HELLO,e)}})(o),f=_c(n,h.suite),m=re(o),p=crypto.getRandomValues(new Uint8Array(32)),w=Ki(n);let b=new Uint8Array(32),v=null;const k=new Uint8Array(h.suite.publicKeyBytes),I=new Uint8Array(h.suite.ciphertextBytes);let S,C,A,P,R,M,K,U,_=null,D=null,T=null;const L=e=>{if("pin"!==r)return null;if(!a)throw new Error("PIN mode requires a PIN");const t=nd(a,e,i,n),o=((e,t)=>{Yl("generator",e,E);const n=t._malloc(x),r=t._malloc(E),o=t._malloc(E),a=new Uint8Array(t.wasmMemory.buffer,n,x),i=new Uint8Array(t.wasmMemory.buffer,r,E),s=new Uint8Array(t.wasmMemory.buffer,o,E);try{if(a.fill(0),s.fill(0),i.set(e),t._cpace_ristretto255_scalar_random(n),0!==t._cpace_ristretto255_scalarmult(o,n,r))throw new Error("cpace: public share is the identity");return{y:Uint8Array.from(a),Y:Uint8Array.from(s)}}finally{Do(t,a),t._free(r),t._free(o)}})(t,n);return t.fill(0),o},q=()=>((e,t,n,r,o,a,i,s)=>{const c=new Uint8Array(e.length);return c[0]=cd.HELLO,c.set(t,1),c.set(n,33),c.set(r,65),c.set(o,97),c.set(a,Id),c.set(i,e.publicKeyOffset),c.set(s,e.ciphertextOffset),c})(h,p,w.publicKey,b,l,d,k,I);try{let t;if(s){_=await f.generateKeyPair(),k.set(_.publicKey);const n=L(p);n&&(v=n.y,b=n.Y),await e.send(q()),t=await e.recv()}else t=await e.recv();if(!hd(t,cd.HELLO,o))throw new Error("Malformed handshake HELLO");const a=t.subarray(1,33),O=t.subarray(33,65),N=t.subarray(65,97),B=t.subarray(97,129),F=t.subarray(Id,193),j=t.subarray(h.publicKeyOffset,h.publicKeyOffset+h.suite.publicKeyBytes),$=t.subarray(h.ciphertextOffset,h.ciphertextOffset+h.suite.ciphertextBytes);if(s){if(!Ed(j))throw new Error("Malformed handshake HELLO: responder ML-KEM public-key field must be zero");if(Ed($))throw new Error("Malformed handshake HELLO: responder ML-KEM ciphertext is required")}else{if(Ed(j))throw new Error("Malformed handshake HELLO: initiator ML-KEM public key is required");if(!Ed($))throw new Error("Malformed handshake HELLO: initiator ML-KEM ciphertext field must be zero")}if(!await sd(B,F,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($,_.secretKey),_.destroy()}else{const t=await f.encapsulate(j);D=t,I.set(t.ciphertext);const n=L(a);n&&(v=n.y,b=n.Y),await e.send(q())}S=((e,t,n,r,o,a)=>{let i,s;const c=_i(n,r,a);o?(i=_i(e,r,a),s=_i(n,t,a)):(i=_i(n,t,a),s=_i(e,r,a));const l=new Uint8Array(96);l.set(i,0),l.set(s,32),l.set(c,64);const d=Di(od,l,a),u=Ti(d,rd,32,a);return l.fill(0),i.fill(0),s.fill(0),c.fill(0),d.fill(0),u})(c,B,w.secretKey,O,s,n);const H=s?p:a,V=s?a:p,W=s?w.publicKey:O,Q=s?O:w.publicKey,G=s?b:N,X=s?N:b,J=s?l:B,Y=s?d:F,Z=s?B:l,ee=s?F:d,te=s?k:j,ne=s?I:$,re=s?j:k,oe=s?$:I;if("pin"===r){if(!v)throw new Error("Handshake CPace scalar is unavailable");C=((e,t)=>{const{y:n,peerShare:r,sid:o,initiatorShare:a,responderShare:i,initiatorAssociatedData:s=Jl,responderAssociatedData:c=Jl}=e;Yl("private scalar",n,x),Yl("peer share",r,E),Yl("initiator share",a,E),Yl("responder share",i,E);const l=t._malloc(x),d=t._malloc(E),u=t._malloc(E),h=t._malloc(g),f=t._malloc(y),m=new Uint8Array(t.wasmMemory.buffer,l,x),p=new Uint8Array(t.wasmMemory.buffer,d,E),w=new Uint8Array(t.wasmMemory.buffer,u,E),b=new Uint8Array(t.wasmMemory.buffer,h,g),v=new Uint8Array(t.wasmMemory.buffer,f,y);try{if(m.set(n),p.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(td(t,h,{data:Xl}),td(t,h,{data:o}),ed(t,h,Zl(E)),0!==t._sha512_update(h,u,E))throw new Error("sha512_update failed");if(td(t,h,{data:a}),td(t,h,{data:s}),td(t,h,{data:i}),td(t,h,{data:c}),0!==t._sha512_final(h,f))throw new Error("sha512_final failed");return Uint8Array.from(v)}finally{Do(t,m),t._free(d),Do(t,w),Do(t,b),Do(t,v)}})({y:v,peerShare:N,sid:H,initiatorShare:G,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);A=await ao("pin"===r?[C,S,D.sharedSecret]:[S,D.sharedSecret]),P=Di(wd,A,n);const ie=await ao([ae,i,J,Y,Z,ee,te,oe]);R=Ti(P,ie,32,n);const se=await ao([kd,i,H,V,W,Q,J,Y,Z,ee,te,oe]);try{U=new Uint8Array(await crypto.subtle.digest("SHA-256",se.slice().buffer))}finally{se.fill(0)}M=Di(bd,R,n);const ce=await ao([vd,U]);try{K=Ti(M,ce,32,n)}finally{ce.fill(0),M.fill(0),M=void 0}S.fill(0),C?.fill(0),A.fill(0),P.fill(0),D.destroy();const le=(e,t,n,r=[])=>ao([md,e,H,V,W,Q,G,X,J,Y,Z,ee,te,ne,re,oe,t,...n?[n]:[],...r,i]);if(s){const t=await e.recv();if(!hd(t,cd.CONFIRM,o))throw new Error("Malformed handshake CONFIRM");const r=Uint8Array.from(t.subarray(1,33)),a=t.subarray(33,97);T=zi(R,!0,r,n,m);const i=T.dhSelfPub,s=await le(yd,r,i,[a]),c=Ad(R,s,n);try{await e.send(Pd(i,c));const t=await le(pd,r),s=Ad(R,t,n),l=await io(a,s);if(s.fill(0),!l)throw new Error("Handshake key-confirmation failed");const d=await e.recv();if(!hd(d,cd.FINISH,o))throw new Error("Malformed handshake FINISH");const u=d.subarray(1,65),h=await le(gd,r,i,[a,c]),f=Ad(R,h,n),m=await io(u,f);if(f.fill(0),!m)throw new Error("Handshake final confirmation failed")}finally{c.fill(0)}}else{T=zi(R,!1,null,n,m);const t=T.dhSelfPub,r=await le(pd,t),a=Ad(R,r,n);try{await e.send(Pd(t,a));const r=await e.recv();if(!hd(r,cd.CONFIRM,o))throw new Error("Malformed handshake CONFIRM");const i=Uint8Array.from(r.subarray(1,33)),s=r.subarray(33,97),c=await le(yd,t,i,[a]),l=Ad(R,c,n),d=await io(s,l);if(l.fill(0),!d)throw new Error("Handshake key-confirmation failed");((e,t,n)=>{if(t.length!==z)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");Vi(e,{dhPub:t},n)})(T,i,n);const u=await le(gd,t,i,[a,s]),h=Ad(R,u,n);try{await e.send((e=>{const t=new Uint8Array(Cd);return t[0]=cd.FINISH,t.set(e,1),t})(h))}finally{h.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 de=T;T=null;const ue={rootKey:K,binding:U,nextOfferer:s?"local":"remote"};return K=void 0,U=void 0,{state:de,secret:R,pqHealing:ue}}catch(e){throw R?.fill(0),K?.fill(0),U?.fill(0),e}finally{w.secretKey.fill(0),v?.fill(0),S?.fill(0),C?.fill(0),A?.fill(0),P?.fill(0),M?.fill(0),K?.fill(0),U?.fill(0),D?.destroy(),_?.destroy(),T&&Zi(T)}},Rd=e=>e.replace(/:/g,"").toLowerCase();let Md=!1;const Kd=new Map,Ud=(e,t)=>`${e}\0${t}`,_d=(e,t,n=new Error("Handshake channel closed"),r)=>{const o=Ud(e,t),a=Kd.get(o);if(!a||r&&a.lease!==r)return!1;Kd.delete(o);for(const e of a.waiters)e.reject(n);return!0},Dd=async(e,t,n,r,o,a,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=Rd(so(Wl(t))),o=Rd(so(Wl(n))),a=await e.getStats();let i,s,c=!1;if(a.forEach(e=>{"transport"===e.type&&(i=e.localCertificateId??i,s=e.remoteCertificateId??s),"certificate"===e.type&&(c=!0)}),!c&&void 0===i)return void(Md||(Md=!0,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 a.forEach((n,r)=>{"certificate"!==n.type||r!==e&&n.id!==e||!n.fingerprint||(t=Rd(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!==o)throw new Error("DTLS fingerprint mismatch: remote certificate not found or does not match remote SDP fingerprint (possible MITM)")})(e);const{publicKey:f}=nm.getState().keyPair,m=jo(f,e.withPeerPublicKey),p=await ri();if(!p)throw new Error("X25519 identity not provisioned");l=new Uint8Array(p.secret);const y=new Uint8Array(p.pub),g=new Uint8Array(p.crossSig),w=co(e.withPeerPublicKey),b=((e,t,n)=>{const r=Ud(e,t),o=Kd.get(r);if(!o||o.lease!==n)throw new Error(`No owned handshake channel registered for ${t}`);const a=()=>{if(Kd.get(r)!==o||o.lease!==n)throw new Error("Handshake channel lease is stale")};return{send:e=>{a();const t=new Uint8Array(1+e.length);t[0]=1,t.set(e,1),o.channel.send(t.buffer)},recv:()=>{try{a()}catch(e){return Promise.reject(e)}return o.queue.length>0?Promise.resolve(o.queue.shift()):new Promise((e,t)=>{const n={resolve:t=>{clearTimeout(r),e(t)},reject:e=>{clearTimeout(r),t(e)}},r=setTimeout(()=>{const e=o.waiters.indexOf(n);e>-1&&o.waiters.splice(e,1),t(new Error("Handshake step timed out"))},3e4);o.waiters.push(n)})}}})(t,e.withPeerId,s),v=await xd(b,{mode:n,pqMode:r,pin:o,channelInput:a,amInitiator:m,idSelfSec:l,selfIdentityX25519Pub:y,selfIdentityCrossSignature:g,peerIdentityEd25519Pub:w},i);if(u=v.state,d=v.secret,h=((e,t,n,r,o)=>{try{return new Hl({module:e,pqMode:t,rootSuite:n,binding:o.binding,rootKey:o.rootKey,nextOfferer:o.nextOfferer,amInitiator:r})}finally{o.rootKey.fill(0),o.binding.fill(0)}})(i,r,u.rootSuite,m,v.pqHealing),!Qs(t,e.withPeerId,c))throw new Error("Handshake transport lease is stale");xs(e,t),await(async(e,t,n,r,o,a)=>{const i=()=>n.pqRuntime.serialize();e.serializeEdgeCryptoState=i;try{await Us(e,n.state,t,()=>{r(),e.ratchetState&&Zi(e.ratchetState),e.ratchetState=n.state,e.pqHealingState?.destroy(),e.pqHealingState=n.pqRuntime,e.messageKeyCache=n.pqRuntime.activeReceiveKeys},o,a)}catch(t){throw e.serializeEdgeCryptoState===i&&(e.serializeEdgeCryptoState=void 0),t}})(e,t,{state:u,pqRuntime:h},()=>{if(!Qs(t,e.withPeerId,c))throw new Error("Handshake transport lease was replaced during persistence");if(!((e,t,n)=>{const r=Vs(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 Xs(t,e.withPeerId,n,c),n}finally{d?.fill(0),l?.fill(0),u&&Zi(u),h?.destroy(),_d(t,e.withPeerId,new Error("Handshake attempt finished"),s)}},Td=new WeakMap,Ld=(e,t,n,r)=>(async(e,t,n,r)=>Ps(n,e.withPeerPublicKey,async()=>{Rs(e,n);const o=r?.()??e.serializeEdgeCryptoState?.()??null;try{await Ms(t,n,e.withPeerPublicKey,e.withPeerId,o)}finally{o?.fill(0)}Rs(e,n)}))(e,t,n,r),qd=e=>{throw new Error(`pqHealingOrchestrator: ${e}`)};class Od extends Error{constructor(e){super("pqHealingOrchestrator: edge checkpoint persistence failed",{cause:e}),this.name="PqPersistenceError"}}const Nd=e=>{const t=Td.get(e);return!(!t||!t.inboundBlocked&&!t.failed)||(e.pqHealingState?.trafficBlocked??!1)},Bd=(e,t)=>0===(e.messageChannels?.size??0)&&!((e,t)=>{const n=hc(e,t);return(lc.get(n)??0)>0||cc.has(n)})(t,e.withPeerId),Fd=async(e,t,n)=>Ds(e,async()=>{const r=e.pqHealingState,o=e.ratchetState;if(!r||!o)return qd("edge has no live PQ runtime or ratchet");const a=r.clone();let i;try{if(i=await n(a),i.persist){try{await t.persistEdge(e,o,t.roomId,()=>a.serialize())}catch(e){throw new Od(e)}if(e.pqHealingState!==r)throw new Od(new Error("live PQ runtime changed during persistence"));r.adopt(a),e.messageKeyCache=r.activeReceiveKeys}else a.destroy()}catch(e){throw a.destroy(),e}i.dispatch&&(i.dispatch=Uint8Array.from(i.dispatch),t.hooks.sendControlFrame(i.dispatch)||i.dispatch.fill(0))}),jd=e=>{const t=Td.get(e);t&&(t.destroyed=!0,null!==t.interval&&clearInterval(t.interval),t.interval=null,Td.delete(e))},zd=(e,t)=>{e.failed||(e.failed=!0,e.hooks.failEdge(t))},$d=async e=>{const t=Td.get(e),n=e.pqHealingState;if(t&&!t.destroyed&&!t.failed&&!t.busy&&n){t.busy=!0;try{const r=t.now(),o=n.pendingRetryAt;if(null!==o&&r>=o)return n.pendingAttempts>=8?void zd(t,new Error("pqHealingOrchestrator: control retry budget exhausted; failing the authenticated edge")):void await Fd(e,t,e=>{e.markPendingDispatched(r);const t=e.copyPendingFrame();return t?Promise.resolve({dispatch:t,persist:!0}):qd("retry tick found no persisted outbox")});n.healingDue(r)&&!n.trafficBlocked&&!t.inboundBlocked&&Bd(e,t.roomId)&&await Fd(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}}},Hd=async(e,t,n)=>{const r=Td.get(e),o=e.pqHealingState;if(r&&!r.destroyed&&!r.failed&&o)if(n.length===H){r.inboundBlocked=!0;try{await(async(e,t)=>{const n=hc(e,t);for(;;){const e=cc.get(n);if(!e&&0===(lc.get(n)??0))return;e?await e.catch(()=>{}):await new Promise(e=>setTimeout(e,10))}})(t,e.withPeerId);const o=r.now();await Fd(e,r,async e=>{const t=await e.acceptControlFrame(Uint8Array.from(n),o);return t.changed?(null!==t.dispatch&&null!==e.pendingRetryAt&&e.markPendingDispatched(o),{dispatch:t.dispatch,persist:!0}):{dispatch:t.dispatch,persist:!1}})}catch(e){if(e instanceof Od)return void console.error("pqHealingOrchestrator: inbound transition not durable",e);zd(r,new Error("pqHealingOrchestrator: unauthenticated or forked control cell; failing the authenticated edge",{cause:e}))}finally{r.inboundBlocked=!1}}else zd(r,new Error("pqHealingOrchestrator: malformed control cell length"))},Vd=(e,t)=>{if(!Number.isSafeInteger(t))throw new Error(`coverScheduler: ${e} must be a safe integer`)},Wd=(e,t)=>{if(!(t instanceof Uint8Array))throw new Error(`coverScheduler: ${e} must return a Uint8Array`);return t},Qd=e=>e.cancelRequested?0:"control"===e.job.kind?1:2,Gd=(e,t)=>{const n=Qd(e)-Qd(t);if(0!==n)return n;return(t.job.priority??0)-(e.job.priority??0)||e.sequence-t.sequence},Xd=e=>({id:e.job.id,kind:e.job.kind,declaredCellCount:e.job.declaredCellCount});class Jd{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(Zd(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>=Yd(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(Gd).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(Vd("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&&Vd("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),o=this.schedule.phaseOffsetMs+r*this.cycleDurationMs;if(!t&&o<=e&&(r++,o=this.schedule.phaseOffsetMs+r*this.cycleDurationMs),!Number.isSafeInteger(o))throw new Error("coverScheduler: next cycle boundary is out of range");return o}cycleIndexAtBoundary(e){const t=Math.round((e-this.schedule.phaseOffsetMs)/this.cycleDurationMs);return Vd("cycle index",t),t}sortQueue(){this.queued.sort(Gd)}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,o=()=>{if(r!==this.generation)return;const a=this.assertClockNow(),i=e-a,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 a=this.assertClockNow();a<e?o():a>e+this.maxTimerDriftMs?this.handleLateTimer(t,e,a):Promise.resolve(n(r)).catch(()=>{"slot"===t?this.degrade("cell-production-failed"):this.suspend("boundary-handler-failed")})},s)};o()}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 o=[];for(let e=0;e<this.schedule.coverLanes;e++)o.push(this.dequeue());for(const e of o)e&&(e.state="admitted",e.everAdmitted=!0);const a=[];let i=!1;for(let t=0;t<this.schedule.coverLanes;t++){const s=o[t],c={cycleIndex:n,cycleStartMs:e,cycleEndMs:r,laneIndex:t,job:s?Xd(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");a.push({laneIndex:t,handle:e,openContext:c,job:s})}catch{i=!0}}if(this.cycle={index:n,startMs:e,endMs:r,lanes:a,nextSlotOrdinal:0},i){this.setStatus("degraded","lane-open-failed");for(const e of this.cycle.lanes)e.job=void 0;for(const e of o)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,o=Math.floor(r/this.schedule.coverLanes),a=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:a,frameIndex:o,laneSlotIndex:n*this.schedule.coverFramesPerCell+o}}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??Wd("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:Wd("nextCell",r),source:n.job.kind,slot:t,jobId:n.job.id,jobCellIndex:n.sentCells}}}}return{cell:Wd("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 o,a;try{o=await this.requestForSlot(r,e)}catch{return void this.degrade("cell-production-failed")}if(t!==this.generation)return void this.cacheUnsent(r,o);if(this.assertClockNow()>e.deadlineMs+this.maxTimerDriftMs)return this.cacheUnsent(r,o),void this.degrade("missed-deadline");try{a=await r.handle.send(o)}catch{return this.cacheUnsent(r,o),void this.degrade("send-failed")}if(!1===a)return this.cacheUnsent(r,o),void this.degrade("backpressure");if(this.acceptSent(r,o),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 Yd=e=>e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell),Zd=e=>{if(null===e||"object"!=typeof e)throw new Error("coverScheduler: schedule must be an object");if(Vd("phase offset",e.phaseOffsetMs),Vd("cover cadence",e.coverCadenceMs),Vd("cover lanes",e.coverLanes),Vd("cover frames per cell",e.coverFramesPerCell),Vd("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(Yd(e)<25)throw new Error("coverScheduler: schedule requires at least 25ms per staggered slot")},eu=H-69-C,tu=y,nu=eu-1-4,ru=(1n<<64n)-1n,ou=(new TextEncoder).encode("p2party/cover-cell/key/v1\0");class au extends Error{code;constructor(e,t){super(`coverCell: ${t}`),this.name="CoverCellError",this.code=e}}const iu=(e,t)=>{throw new au(e,t)},su=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&iu("invalid-cell",`${t} must be exactly ${String(n)} bytes`),e):iu("invalid-cell",`${t} must be a Uint8Array`),cu=(e,t)=>"bigint"!=typeof e||e<0n||e>ru?iu("invalid-cell",`${t} must be an unsigned 64-bit bigint`):e,lu=(e,t,n,r,o,a)=>{su(n,"PQ message root",32),su(r,"edge binding",32);const i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,cu(a,"keyEpoch"),!1);const s=new Uint8Array(ou.length+1+1+r.length+i.length);s.set(ou,0),s[ou.length]=(e=>e===Q?1:e===W?2:e===G?3:iu("invalid-cell","authenticated room suite is unsupported"))(t),s[ou.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:iu("invalid-direction","cover-cell direction is unknown"))(o),s.set(r,ou.length+2),s.set(i,ou.length+2+r.length);const c=Di(n,r,e);try{return Ti(c,s,I,e)}finally{c.fill(0),i.fill(0)}},du=e=>{const t=su(e.binding,"edge binding",32),n=cu(e.keyEpoch,"keyEpoch"),r=cu(e.counter,"counter"),o=(e=>{if("dummy"===e.subtype)return new Uint8Array(0);if("cancel"===e.subtype)return Uint8Array.from(su(e.merkleRoot,"cancel transfer root",tu));const t=su(e.merkleRoot,"receipt transfer root",tu),n=su(e.token,"receipt token",tu),r=new Uint8Array(t.length+n.length);return r.set(t,0),r.set(n,t.length),r})(e.content);o.length>nu&&iu("invalid-cell","cover payload does not fit the uniform cell");const a=(()=>{const e=new Uint8Array(S);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(a,57);const c=new Uint8Array(eu);var l;c[0]="dummy"===(l=e.content.subtype)?1:"cancel"===l?2:"receipt"===l?3:iu("invalid-cell","cover-cell subtype is unknown"),new DataView(c.buffer,c.byteOffset,c.byteLength).setUint32(1,o.length,!1),c.set(o,5);const d=lu(e.module,e.rootSuite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,o)=>{const a=r.length+C,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(o.length),d=e._malloc(a);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,o.length).set(o),0!==e._encrypt_chachapoly_symmetric(d,c,r.length,i,s,l,o.length)?iu("invalid-cell","cover-cell AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,a))}finally{Do(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),Do(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),Do(e,new Uint8Array(e.wasmMemory.buffer,d,a))}})(e.module,d,a,c,i),n=new Uint8Array(H);return n.set(i,0),n.set(t,69),n}finally{d.fill(0),c.fill(0),o.fill(0)}},uu=e=>{const t=su(e.frame,"cover cell",H),n=su(e.binding,"edge binding",32),r=cu(e.keyEpoch,"keyEpoch");4!==t[0]&&iu("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)||iu("binding-mismatch","cover cell belongs to another edge");const o=t.subarray(0,69),a=new DataView(t.buffer,t.byteOffset,t.byteLength),i=a.getBigUint64(33,!1);0n!==a.getBigUint64(41,!1)&&iu("invalid-cell","cover-cell reserved header must be zero"),a.getBigUint64(49,!1)!==r&&iu("epoch-mismatch","cover-cell epoch is not the expected epoch"),void 0!==e.counterAbove&&(cu(e.counterAbove,"counterAbove"),i<=e.counterAbove&&iu("replayed-counter","cover-cell counter is not strictly newer"));const s=t.subarray(57,69),c=t.subarray(69),l=lu(e.module,e.rootSuite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,o)=>{const a=r.length-C,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(o.length),d=e._malloc(a);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,o.length).set(o);const u=new Uint8Array(e.wasmMemory.buffer,d,a);return u.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,r.length,i,s,l,o.length)?iu("authentication-failed","cover-cell authentication failed"):Uint8Array.from(u)}finally{Do(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),Do(e,new Uint8Array(e.wasmMemory.buffer,d,a))}})(e.module,l,s,c,o);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(1,!1);t>nu&&iu("invalid-padding","encrypted cover payload length is invalid");const n=5,r=n+t;let a=0;for(let e=r;e<d.length;e+=1)a|=d[e];0!==a&&iu("invalid-padding","encrypted cover padding must be all zero");return{content:(u=d[0],h=d.subarray(n,r),1===u?(0!==h.length&&iu("invalid-cell","dummy cover cells carry no payload"),{subtype:"dummy"}):2===u?(h.length!==tu&&iu("invalid-cell","CANCEL payload must be one 64-byte transfer root"),{subtype:"cancel",merkleRoot:Uint8Array.from(h)}):3===u?(h.length!==2*tu&&iu("invalid-cell","receipt payload must be root ‖ token"),{subtype:"receipt",merkleRoot:h.slice(0,tu),token:h.slice(tu)}):iu("invalid-cell","cover-cell subtype is unknown")),counter:i}}finally{l.fill(0),d?.fill(0)}var u,h},hu={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},fu=(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 mu{#X;#e;#J;#T;#L;#Y;#Z=0n;#ee=null;#te=new Set;static#ne=1024n;#re=new Map;#oe=!1;#g=!1;#ae="stopped";constructor(e){this.#X=e.epc,this.#e=e.module,this.#J=e,this.#T=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#L=e.amInitiator?"responder-to-initiator":"initiator-to-responder";const t={...e.schedule,phaseOffsetMs:fu(e.policyHash,e.schedule.coverCadenceMs)},n=Yd(t),r=e.maxTimerDriftMs??Math.max(0,Math.min(Math.floor(n)-1,500));this.#Y=(e=>new Jd(e))({schedule:t,maxTimerDriftMs:r,clock:e.clock??hu,laneFactory:e=>this.#ie(e),makeDummy:e=>this.#se(e),onStatusChange:t=>{this.#ae=t.status,e.onStatusChange?.(t)},onJobResult:t=>{const n=this.#re.get(t.jobId);n&&(this.#re.delete(t.jobId),n()),e.onJobResult?.(t)},onJobInterrupted:e.onJobInterrupted})}cellsPerLanePerCycle(){return this.#J.schedule.coverFramesPerCell*this.#J.schedule.coverDurationEpochs}onJobSettled(e,t){this.#V(),this.#re.set(e,t)}randomLaneLabel(){return this.#ce()}get status(){return this.#ae}start(){this.#V(),this.#le(),this.#Y.start()}stop(){this.#de(),this.#Y.stop()}destroy(){this.#g||(this.stop(),this.#g=!0)}suspend(e){this.#V(),this.#Y.suspend(e)}resume(){this.#V(),this.#Y.resume()}enqueue(e){this.#V(),this.#Y.enqueue(e)}cancel(e){return this.#V(),this.#Y.cancel(e)}complete(e){this.#V(),this.#Y.complete(e)}getQueuedJobIds(){return this.#Y.getQueuedJobIds()}sealCoverContent(e){return this.#V(),this.#ue(e)}processInboundCoverCell(e){this.#V();const t=this.#X.pqHealingState;if(!t||e.length!==H)return!1;const n=t.currentMessageContext();try{const t=uu({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#L,keyEpoch:n.epoch,frame:e});return!!this.#he(t.counter)&&("cancel"===t.content.subtype?this.#J.onRemoteCancel?.(so(t.content.merkleRoot)):"receipt"===t.content.subtype&&this.#J.onScheduledReceipt?.(so(t.content.merkleRoot),t.content.token),!0)}catch{return!1}}async makeDummyLaneLabel(){const e=new Uint8Array(64);return crypto.getRandomValues(e),ci(this.#J.laneLabelName,e)}#he(e){const t=this.#ee;if(null!==t&&t>=mu.#ne&&e<=t-mu.#ne)return!1;if(this.#te.has(e))return!1;if(this.#te.add(e),(null===t||e>t)&&(this.#ee=e,e>=mu.#ne)){const t=e-mu.#ne;for(const e of this.#te)e<=t&&this.#te.delete(e)}return!0}#ue(e){const t=this.#X.pqHealingState;if(!t)throw new Error("coverRuntime: edge has no live PQ runtime");const n=t.currentMessageContext(),r=this.#Z;return this.#Z+=1n,du({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#T,keyEpoch:n.epoch,counter:r,content:e})}#se(e){return this.#ue({subtype:"dummy"})}#ie(e){const t=null!==e.job?e.job.id:this.#ce(),n=this.#J.openLaneChannel(t);return{send:e=>{if(e.cell.length!==H)throw new Error("coverRuntime: refusing a non-uniform cell at the lane boundary");if("open"!==n.readyState)return!1;if(n.bufferedAmount>=D)return!1;const t=Uint8Array.from(e.cell);return n.send(t.buffer),!0},close:e=>{"closed"!==n.readyState&&n.close()}}}#ce(){const e=(new TextEncoder).encode(this.#J.laneLabelName),t=new Uint8Array(32);t.set(e.subarray(0,Math.min(32,e.length)));const n=new Uint8Array(64);return crypto.getRandomValues(n),`${so(t)}~${so(n)}`}#fe=()=>{"undefined"!=typeof document&&("hidden"===document.visibilityState?this.#Y.suspend("page-hidden"):this.#Y.resume())};#me=()=>{this.#Y.suspend("pagehide")};#pe=()=>{this.#Y.suspend("freeze")};#ye=()=>{this.#Y.suspend("offline")};#ge=()=>{this.#Y.resume()};#le(){this.#oe||(this.#oe=!0,"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.#fe),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.#me),window.addEventListener("freeze",this.#pe),window.addEventListener("offline",this.#ye),window.addEventListener("online",this.#ge)))}#de(){this.#oe&&(this.#oe=!1,"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.#fe),"undefined"!=typeof window&&(window.removeEventListener("pagehide",this.#me),window.removeEventListener("freeze",this.#pe),window.removeEventListener("offline",this.#ye),window.removeEventListener("online",this.#ge)))}#V(){if(this.#g)throw new Error("coverRuntime: runtime is destroyed")}}const pu=(e,t,n)=>{e?.delete(n);for(let e=t.length-1;e>=0;e--)t[e]===n&&t.splice(e,1)},yu=(e,t,n=[])=>{((e,t)=>{if(!e.has(t)&&e.size>=64)throw new Error("Too many cover DataChannels on one peer edge");e.add(t)})(e,t);const r=()=>{pu(e,n,t)};if(t.addEventListener("close",r),"closed"===t.readyState)throw r(),new Error("Cover DataChannel closed during setup");return r},gu=new WeakMap,wu=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}},bu=(e,t,n,r,o)=>{let a=gu.get(e);a||(a=new Map,gu.set(e,a)),a.set(r,{transferId:o,peerId:n,roomId:t})},vu=e=>{const t=e.epc.coverRuntime;if(!t)return!1;const n=ac({runtime:t,channelMessageLabel:e.channelMessageLabel,totalChunks:e.totalChunks,sealSlotCell:e.sealSlotCell,getAckedChunks:e.getAckedChunks});return t.enqueue(n),!0},ku=new Map,Iu=(e,t)=>{const n=ku.get(e);n&&(n.delete(t),0===n.size&&ku.delete(e))},Su=(e,t)=>{e.controller.signal.aborted||e.controller.abort(t)},Cu=()=>{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},Au=e=>/^[0-9a-f]{64}$/.test(e),Eu=(e,t=Cu())=>{if(0===e.length)throw new Error("Transfer roomId must not be empty");if(!Au(t))throw new Error("Transfer ID must be 32-byte lowercase hex");if([...ku.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=ku.get(e);return r||(r=new Set,ku.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,Iu(e,n))}}},Pu=(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&&!Au(t.transferId))throw new Error("Transfer ID must be 32-byte lowercase hex");const n=ku.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 o=0;for(const e of r)Su(e,new Error("Message transfer cancelled")),o++;return o},xu=e=>{const t=ku.get(e);if(!t)return 0;let n=0;for(const e of t)Su(e,new Error("Room transfers cancelled")),n++;return n},Ru=()=>{let e=0;for(const t of[...ku.keys()])e+=xu(t);return e},Mu=e=>{if(e?.aborted){if(e.reason instanceof Error)throw e.reason;throw new Error("Message transfer cancelled")}},Ku=async(e,t)=>(Mu(t),t?new Promise((n,r)=>{const o=()=>{a(),r(t.reason instanceof Error?t.reason:new Error("Message transfer cancelled"))},a=()=>t.removeEventListener("abort",o);t.addEventListener("abort",o,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})}):e),Uu=(e,t)=>{const{signalingServer:n}=e.getState();return!(!n.isConnected||!n.isVerified)&&(e.dispatch(Ge({roomId:t,connectingToPeers:!0,reason:"redial"})),!0)},_u={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>{clearTimeout(e)}},Du=e=>{const t=e.rebindDeadline,n=e.rebindDeadlineClear;e.rebindDeadline=void 0,e.rebindDeadlineClear=void 0,void 0!==t&&(n??_u.clearTimeout)(t)},Tu=e=>{e.fill(0)},Lu=e=>{if("string"!=typeof e||0===e.length)throw new Error("roomPinVault: room context must be a non-empty string")};const qu=new class{#we=new Map;#be;constructor(e=Tu){this.#be=e}put(e,t){Lu(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.#we.get(e);r&&this.#be(r),this.#we.set(e,n)}get(e){Lu(e);const t=this.#we.get(e);return t?Uint8Array.from(t):void 0}has(e){return Lu(e),this.#we.has(e)}delete(e){Lu(e);const t=this.#we.get(e);return!!t&&(this.#be(t),this.#we.delete(e))}clear(){for(const e of this.#we.values())this.#be(e);this.#we.clear()}},Ou=(e,t)=>{qu.put(e,t)},Nu=e=>qu.get(e),Bu=e=>qu.delete(e),Fu=3e5,ju=new Map,zu=(e,t)=>{const n=t-Fu,r=(ju.get(e)??[]).filter(e=>e>n);return 0===r.length?ju.delete(e):ju.set(e,r),r},$u=async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=zu(e,t);if(!(n.length<30))throw new Error(`PIN retries for this room are temporarily throttled until ${new Date(n[0]+Fu).toISOString()}`)})(e,n);const r=await ni(e,t);if(r&&r.retryAfter>n)throw new Error(`PIN retry for this peer identity is throttled until ${new Date(r.retryAfter).toISOString()}`)},Hu=async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=zu(e,t);n.push(t),ju.set(e,n)})(e,n),await((e,t,n,r,o,a)=>Fa("incrementPinAttemptState",e,t,n,r,o,a))(e,t,n,3,500,3e5)},Vu=(e,t)=>(void 0===t&&(e=>{ju.delete(e)})(e),((e,t)=>Fa("deletePinAttemptState",e,t))(e,t)),Wu=(new TextEncoder).encode("p2party/room-channel/v1\0"),Qu=(e,t,n)=>{const r=co(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 o=(new TextEncoder).encode(t),a=new Uint8Array(Wu.length+r.length+n.length+o.length);let i=0;return a.set(Wu,i),i+=Wu.length,a.set(r,i),i+=r.length,a.set(n,i),i+=n.length,a.set(o,i),a},Gu=async({channel:e,epc:t,roomId:n,dataChannels:r,incoming:o=!1},a)=>{const{keyPair:i,rooms:s}=a.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 o=r.findIndex(r=>r.label===e&&r.withPeerId===t.withPeerId&&r.roomIds.includes(n));if(o>-1&&"open"===r[o].readyState)return r[o]}const m="string"==typeof e?e:e.label;if(0===m.length||m.length>193||!m.includes("~")&&(new TextEncoder).encode(m).length>32)throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected invalid or oversized DataChannel label");if(o&&"main"===m&&(p=i.publicKey,g=t.withPeerPublicKey,jo(p,g)))throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected incoming main DataChannel on the designated opener side");var p,g;if(!o&&"main"===m&&!jo(i.publicKey,t.withPeerPublicKey))throw new Error("Only the designated identity may create main DataChannel");if("main"===m&&t.mainChannel&&"closing"!==t.mainChannel.readyState&&"closed"!==t.mainChannel.readyState){if(!o)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;let k=()=>{pu(t.coverChannels,r,b)};if(v){t.coverChannels??=new Set;try{k=yu(t.coverChannels,b,r)}catch(e){throw"closed"!==b.readyState&&b.close(),e}}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 I=t.ratchetGateLease,S="main"===b.label?t.ratchetGateLease:void 0,C="main"===b.label?((e,t,n,r="hybrid-mlkem768",o=!1)=>{const a=Ud(e,t),i=Kd.get(a);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 Kd.set(a,{lease:s,pqMode:r,expectFinish:o,channel:n,queue:[],nextStep:1,waiters:[]}),s})(n,t.withPeerId,b,s[c]?.policy.pqMode??"hybrid-mlkem768",jo(i.publicKey,t.withPeerPublicKey)):void 0;let A;try{A=await li(m)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw t.messageChannels?.delete(b),k(),t.mainChannel===b&&(t.mainChannel=void 0),C&&_d(n,t.withPeerId,r,C),"closed"!==b.readyState&&b.close(),r}const{channelLabel:E,merkleRoot:P,merkleRootHex:x}=A;if(v&&"closed"===b.readyState)throw k(),wc(f),new Error("Cover DataChannel closed during label decoding");let R=!1,M=!1;const K=()=>{M||(M=!0,wc(f),t.messageChannels?.delete(b),v&&k())},U=()=>{R||(R=!0,h.signal.aborted||h.abort(new Error("Message channel processing stopped")),((e,t,n,r)=>{r&&(r.released=!0);const o=e.reduce((e,t)=>e+t.byteLength,0);e.length=0,o>0&&pc(e,t,n,-o),r&&fc(e,r)})(l,n,t.withPeerId,u),K())};b.releaseProtocolResources=U;let _,D=!1;const T=()=>_||(D=!0,U(),_=(async()=>{await mc(l,u),""!==x&&(await Ns(t,n,x),await Ja(x))})(),_);return"main"!==b.label&&(b.cancelReceiveTransfer=T),b.onclose=async()=>{if(It(`Channel with label ${b.label} has closed.`),v){if(K(),await mc(l,u),""!==x)try{const e=await Va(x);await Bs(t,n,x,e)}catch(e){console.error(e)}U()}else if("main"===b.label){if(U(),S&&!Qs(n,t.withPeerId,S))return;C&&_d(n,t.withPeerId,new Error("Main data channel closed"),C),await a.dispatch(kf.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId})),Uu(a,n)}else{if(!r.includes(b))return;K(),await mc(l,u);let e,o=!1;if(D)try{await _,o=!0}catch(e){console.error(e)}else if(""!==x)try{e=await Va(x);const r="connected"===t.connectionState&&Qs(n,t.withPeerId,I);o=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(x)&&(o=!0)}catch(e){console.error(e),o=!1}if(o)try{await T()}catch(e){console.error(e),o=!1}else{if(""!==x)try{await Bs(t,n,x,e)}catch(e){console.error(e)}U()}await a.dispatch(kf.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:b.label,channel:b,alsoDeleteData:o}))}},b.onerror=async e=>{if(console.error(e),"main"===b.label){if(S&&!Qs(n,t.withPeerId,S))return;await a.dispatch(kf.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}))}else{if(!r.includes(b))return U(),void("closed"!==b.readyState&&b.close());await a.dispatch(kf.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:b.label,channel:b}))}Uu(a,n)},b.onmessage=async e=>{const r=new Uint8Array(e.data);if("main"!==b.label&&!Gs(n,t.withPeerId,I))return console.error("Rejected application data before peer authentication"),U(),void("closed"!==b.readyState&&b.close());const o=(e=>{const t=e.length>=1?e[0]:-1,n=3===t&&e.length!==F?-1:t;return{type:n,payload:-1===n?e.subarray(e.length):e.subarray(1)}})(r);if("main"!==b.label&&3===o.type){return void(((e,t,n)=>{if(t.released)return!1;const r=sc(e);if(t.seen.has(r))return!0;const o=uc.get(hc(t.roomId,t.peerId))??0;return!(t.pending.length>=2048||o>=8192||(t.seen.add(r),t.seen.size>4096&&t.seen.clear(),t.pending.push(e),gc(t,1),t.draining||bc(t,n),0))})(o.payload,f,async e=>{Gs(n,t.withPeerId,I)&&await bi(e,b.label,b.withPeerId,n,a)})||(console.error("Closing message DataChannel: receipt queue budget exceeded"),U(),"closed"!==b.readyState&&b.close()))}if(2===o.type&&r.length===H){const e=((e,t,n,r,o,a,i,s,c,l,d,u,h,f)=>{if(r.released||f?.aborted)return!1;const m=sc(e);if(n.has(m))return!0;const p=lc.get(hc(a,i))??0;return!(t.length>=64||p+e.byteLength>16777216)&&(n.add(m),n.size>4096&&n.clear(),t.push(e),pc(t,a,i,e.byteLength),r.value||kc(t,n,r,o,a,i,s,c,l,d,u,h,f),!0)})(r,l,d,u,a,n,b.withPeerId,E,x,P,b,t,t.receiveMessageModule,h.signal);return void(e||(console.error("Closing message DataChannel: receive queue budget exceeded"),U(),"closed"!==b.readyState&&b.close()))}if(("main"===b.label||v)&&5===o.type&&r.length===H)return Gs(n,t.withPeerId,I)?void Hd(t,n,r):void console.error("Rejected PQ control cell before peer authentication");if(4===o.type&&r.length===H&&t.coverRuntime)return Gs(n,t.withPeerId,I)?void t.coverRuntime.processInboundCoverCell(r):void console.error("Rejected cover cell before peer authentication");if("main"===b.label){const{type:e,payload:r}=o;if(1===e)return void(C&&!((e,t,n,r)=>{const o=Kd.get(Ud(e,t));if(!o||o.lease!==r)return!1;if(null===o.nextStep||!hd(n,o.nextStep,o.pqMode))return _d(e,t,new Error("Malformed, surplus, or out-of-order handshake frame"),r),!1;o.nextStep=1===o.nextStep?2:2===o.nextStep&&o.expectFinish?3:null;const a=o.waiters.shift();return a?a.resolve(n):o.queue.push(n),!0})(n,t.withPeerId,r,C)&&(console.error("Closing main DataChannel: malformed or surplus handshake frame"),U(),"closed"!==b.readyState&&b.close()))}console.error(new Error("Wrong data length received"))},b.onopen=()=>{if("main"!==b.label&&!Qs(n,t.withPeerId,I))return U(),void("closed"!==b.readyState&&b.close());It(`Channel with label "${b.label}" and client ${t.withPeerId} is open.`),r.includes(b)||r.push(b),""===x&&E.length>0&&a.dispatch(nt({roomId:n,label:m,peerId:b.withPeerId})),"main"===b.label&&(async()=>{let e,r=!1,o=!1;a.dispatch(tt({roomId:n,peerId:t.withPeerId,peerPublicKey:t.withPeerPublicKey,status:"authenticating"}));try{if(!S||!C)throw new Error("Main channel has no transport ownership lease");const l=s[c];if(!l)throw new Error("Handshake room is unavailable");if("pin"===l.policy.authMode&&(r=!0,e=Nu(l.url),!e))throw new Error("PIN room has no local PIN");r&&await $u(n,t.withPeerPublicKey);const d=jo(i.publicKey,t.withPeerPublicKey),u=co(i.publicKey),h=co(t.withPeerPublicKey),f=Wl(t.localDescription?.sdp??""),m=Wl(t.remoteDescription?.sdp??""),p=await Ee(l.policy),y=fd({channelId:Qu(l.url,b.label,p),ikInitiator:d?u:h,ikResponder:d?h:u,fpInitiator:d?f:m,fpResponder:d?m:f,pqMode:l.policy.pqMode});o=!0,await Dd(t,n,l.policy.authMode,l.policy.pqMode,e??null,y,t.receiveMessageModule,C,S),t.remoteTransportRebinds=0,Du(t),a.dispatch(tt({roomId:n,peerId:t.withPeerId,peerPublicKey:t.withPeerPublicKey,status:"authenticated"})),((e,t,n)=>{e.pqHealingState||qd("cannot install an orchestrator without a PQ runtime"),jd(e);const r={roomId:t,hooks:n,now:n.now??Date.now,persistEdge:n.persistEdge??Ld,interval:null,busy:!1,inboundBlocked:!1,destroyed:!1,failed:!1};Td.set(e,r);const o=n.tickMs??1e3;o>0&&(r.interval=setInterval(()=>{$d(e)},o))})(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;wu(t),t.coverChannels??=new Set;const o=new mu({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"});r.binaryType="arraybuffer",r.withPeerId=t.withPeerId,r.roomIds=[n];try{yu(t.coverChannels,r)}catch(e){throw"closed"!==r.readyState&&r.close(),e}return{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=gu.get(t)?.get(e);n&&pi(n.roomId,n.peerId,n.transferId)}});t.coverRuntime=o,o.start()})({epc:t,roomId:n,policy:l.policy,policyHash:p,amInitiator:d,module:t.receiveMessageModule,onStatusChange:({status:e})=>{a.dispatch(et({roomId:n,peerId:t.withPeerId,status:e}))},onRemoteCancel:e=>{try{Pu(n,{merkleRootHex:e})}catch(e){console.error("scheduled CANCEL abort failed",e)}}}),r&&await Vu(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));if(S&&!Qs(n,t.withPeerId,S))return It(`Superseded handshake attempt for ${t.withPeerId} in ${n} failed after its transport was replaced: ${i.message}`),void("closed"!==b.readyState&&b.close());const s="closed"===t.connectionState;r&&o&&/key-confirmation/i.test(i.message)&&await Hu(n,t.withPeerPublicKey).catch(e=>{console.error("Could not persist PIN attempt state:",e)});let c,l="transport";const d=/throttled until (\S+)/.exec(i.message);if(d){l="pin-throttled";const e=Date.parse(d[1]);Number.isFinite(e)&&(c=e)}else if(o&&/key-confirmation/i.test(i.message)&&(l=r?"pin-mismatch":"policy",r))try{const e=await ni(n,t.withPeerPublicKey);e&&e.retryAfter>Date.now()&&(c=e.retryAfter)}catch{}s||a.dispatch(tt({roomId:n,peerId:t.withPeerId,peerPublicKey:t.withPeerPublicKey,status:"failed",reason:l,retryAfter:c})),S&&Xs(n,t.withPeerId,i,S),C&&_d(n,t.withPeerId,i,C),console.error("protocol-v4 handshake failed:",i),"closed"!==b.readyState&&b.close(),"closed"!==t.connectionState&&t.close(),"transport"!==l||s||Uu(a,n)}finally{e?.fill(0)}})(),""!==x&&"string"!=typeof e&&(async()=>{try{if(!await(async()=>!!Qs(n,t.withPeerId,I)&&(await Ws(n,t.withPeerId),Qs(n,t.withPeerId,I)))())return;const e=await(e=>Fa("getDBAllChunkLeafHashes",e))(x);if(0===e.length)return;let r=[];for(const{chunkIndex:t,leafHash:n}of e)if(n?.length===2*y&&(r.push(await Ei(P,t,co(n))),32===r.length)){if(!await ec(b,r))return;r=[]}if(r.length>0&&!await ec(b,r))return;const o=await Va(x);o&&o.totalSize>0&&o.savedSize===o.totalSize&&o.hash.length===2*y&&Zs(b,co(o.hash))}catch(e){console.error(e)}})()},b},Xu=/(?:^|\r?\n)a=ice-ufrag:([^\r\n]+)/g,Ju=/(?:^|\s)ufrag\s+([^\s]+)/i,Yu=(e,t)=>{const n=(e=>{const t=new Set,n=e?.sdp;if(!n)return t;for(const e of n.matchAll(Xu)){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(Ju)?.[1];return n?.trim()||null})(e);return null===r||n.has(r)},Zu=async(e,t)=>{if(!("closed"===e.connectionState||"closed"===e.signalingState)){const n=await(e.ensureFreshIceConfiguration?.());if("closed"===e.connectionState||"closed"===e.signalingState)return await t(),"disconnected";if(!0===n)return"restarted";try{return e.restartIce(),"restarted"}catch{}}return await t(),"disconnected"},eh=(e,t,n)=>e.findIndex(e=>((e,t,n)=>e.roomId===t&&e.withPeerId===n)(e,t,n)),th=(e,t,n)=>{const r=eh(e,t,n);return r<0?void 0:e[r]},nh=e=>"have-local-offer"===e.signalingState&&null==e.remoteDescription;class rh{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 oh=new Map,ah=new Map,ih=new Map,sh=new rh,ch=(e,t)=>`${String(e.length)}:${e}${t}`,lh=(e,t)=>`${String(e.length)}:${e}${t}`,dh=(e,t,n)=>{(async()=>{for(;;)if(await n.whenIdle(),n.isIdle())return void(e.get(t)===n&&e.delete(t))})()},uh=(e,t)=>{const n=ch(e,t),r=oh.get(n);r&&dh(oh,n,r)},hh=async(e,t,n)=>{const r=((e,t)=>{const n=ch(e,t);let r=oh.get(n);return r||(r=new rh,oh.set(n,r)),r})(e,t);try{return await r.runExclusive(n)}finally{uh(e,t)}},fh=e=>{let t=ih.get(e);return t||(t=new rh,ih.set(e,t)),t},mh=e=>{const t=ih.get(e);t&&dh(ih,e,t)},ph=async({peerId:t,peerPublicKey:n,roomId:r,peerConnections:o},a)=>{const{keyPair:i}=a.getState();if(!e.isUUID(t))throw new Error("PeerId is not a valid uuidv4");if(Fo(i.publicKey,"Self Ed25519 identity"),Fo(n,"Peer Ed25519 identity"),n===i.publicKey)throw new Error("Cannot connect to the same Ed25519 identity");const s=((e,t)=>{const n=lh(e,t);let r=ah.get(n);return r||(r=new rh,ah.set(n,r)),r})(r,n);await s.acquire();try{const e=()=>{const e=a.getState().rooms.find(e=>e.id===r&&!1!==e.signalingActive);if(!e)throw new Error("Cannot create a WebRTC transport for an inactive room");return e};e();const s=((e,t,n,r)=>e.filter(e=>e.roomId===t&&e.withPeerPublicKey===r&&e.withPeerId!==n))(o,r,t,n);for(const e of s)await a.dispatch(kf.endpoints.disconnectFromPeer.initiate({roomId:r,peerId:e.withPeerId}));let c,l=th(o,r,t);if(l&&l.withPeerPublicKey!==n&&(await a.dispatch(kf.endpoints.disconnectFromPeer.initiate({roomId:r,peerId:t})),l=void 0),l){if(await l.initialization,e(),!o.includes(l)||"closed"===l.connectionState)throw new Error("WebRTC transport was removed during initialization");return l}const d=e().url,u=fh(d);await u.acquire();try{const s=e();if(s.url!==d)throw new Error("Room identity changed during transport creation");const l=s.rtcConfig,u=a.getState().keyPair;((e,t)=>{if(Fo(t,"Current self Ed25519 identity"),t!==e)throw new Error("Identity changed during WebRTC transport creation")})(i.publicKey,u.publicKey),((e,t,n,r)=>{const o=new Set(t.map(e=>e.peerPublicKey));for(const t of n)t.roomId===e&&o.add(t.withPeerPublicKey);if(o.add(r),o.size>Re)throw new Error("WebRTC room edge budget is exhausted")})(r,s.peers,o,n);const h=Js(r,t,new Error("Ratchet transport replaced by a new room/peer connection")),f=new RTCPeerConnection(l);c=f,c.roomId=r,c.withPeerId=t,c.withPeerPublicKey=n,c.makingOffer=!1,c.ignoreOffer=!1,c.iceCandidates=[],c.ratchetGateLease=h,c.remoteTransportRebinds=0,c.ensureFreshIceConfiguration=async()=>{let e=a.getState();const t=((e,t=15e3,n=ia)=>{if(n!==ia)return Promise.reject(ca("socket proof lifecycle is stale"));if(e)return Promise.resolve();if(ta?.lifecycleEpoch===n)return ta.promise;let r,o;const a=new Promise((e,t)=>{r=e,o=t}),i={lifecycleEpoch:n,promise:a,resolve:r,reject:o,timeout:setTimeout(()=>{ta===i&&(ta=null,o(ca("fresh socket proof timed out")))},t)};return ta=i,a})(e.signalingServer.isVerified);if(!e.signalingServer.isConnected&&!e.signalingServer.isEstablishingConnection){if(0===e.signalingServer.serverUrl.length)throw new Error("Cannot refresh ICE without a signaling server URL");await a.dispatch(Xf.endpoints.connectWebSocket.initiate(e.signalingServer.serverUrl))}if(await t,e=a.getState(),!e.signalingServer.isConnected||!e.signalingServer.isVerified)throw new Error("Signaling socket did not complete identity proof");const n=e.rooms.find(e=>e.id===r&&!1!==e.signalingActive);if(!n)throw new Error("Cannot refresh ICE for an inactive room");return await wa(a,n.url,e=>Jf(a,e)),!0},xs(c,r),o.push(c)}finally{u.release()}const h=()=>{if(!o.includes(c))throw new Error("WebRTC transport was replaced during initialization")},f=(async()=>{const e=yo(),o=await _o(e);h(),c.receiveMessageModule=o;const i=a.getState().signalingServer;i.isConnected&&i.isVerified&&(await a.dispatch(Xf.endpoints.connectWithPeer.initiate({roomId:r,peerId:t,peerPublicKey:n})).unwrap(),h())})();c.initialization=f;try{await f}catch(e){const t=o.indexOf(c);throw t>-1&&o.splice(t,1),"closed"!==c.connectionState&&c.close(),e}finally{c.initialization=void 0}let m,p=!1;const y=()=>{m&&clearTimeout(m),m=setTimeout(()=>{m=void 0,o.includes(c)&&nh(c)&&(console.warn(`p2party: first offer to ${t} in room ${r} was never answered; rebuilding the transport`),a.dispatch(kf.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:r})).then(()=>{Uu(a,r)}))},15e3)};c.onnegotiationneeded=async()=>{if(c.makingOffer||"stable"!==c.signalingState)It(`Skipping negotiation with ${t} - already making offer: ${String(c.makingOffer)}, state: ${c.signalingState}`);else try{if(c.makingOffer=!0,await c.setLocalDescription(),nh(c)&&y(),c.localDescription){const e=a.getState().keyPair;await a.dispatch(Xf.endpoints.sendMessage.initiate({content:{type:"description",description:c.localDescription,fromPeerId:e.peerId,fromPeerPublicKey:e.publicKey,toPeerId:t,roomId:r,protocolVersion:4}})).unwrap(),It(`Negotiation was needed with ${t} and you sent a description ${c.localDescription.type}.`)}}catch(e){console.error(e)}finally{c.makingOffer=!1}},c.onicecandidate=async({candidate:e})=>{if(e&&""!==e.candidate){const n=a.getState().keyPair;await a.dispatch(Xf.endpoints.sendMessage.initiate({content:{type:"candidate",candidate:e,fromPeerId:n.peerId,toPeerId:t,roomId:r,protocolVersion:4}})).unwrap().catch(e=>{console.warn("p2party: ICE candidate signaling failed",e instanceof Error?e.message:String(e))})}},c.onicecandidateerror=e=>{console.error(e)};let g=0;const w=3e3;let b,v;const k=()=>v||(v=Zu(c,()=>{}).finally(()=>{v=void 0}),v);return c.oniceconnectionstatechange=async()=>{if("failed"===c.iceConnectionState||"disconnected"===c.iceConnectionState){const e=Date.now();e-g>w&&(g=e,It(`ICE ${c.iceConnectionState} with ${t}, restarting`),await k().catch(e=>{console.warn("p2party: ICE refresh/restart failed",e instanceof Error?e.message:String(e))}))}It(`ICE candidate connection state with ${t} is ${c.iceConnectionState}.`)},c.onicegatheringstatechange=()=>{It(`ICE gathering state with ${t} is ${c.iceGatheringState}.`)},c.onsignalingstatechange=async()=>{It(`Signaling state with ${t} is ${c.signalingState}.`),"stable"===c.signalingState&&c.remoteDescription&&await(async e=>{for(;e.iceCandidates.length>0&&"stable"===e.signalingState&&e.remoteDescription;){const t=e.iceCandidates.shift();if(t&&Yu(t,e.remoteDescription))try{await e.addIceCandidate(t)}catch(e){console.warn("Could not add queued ICE candidate:",e)}}})(c)},c.onconnectionstatechange=async()=>{"disconnected"===c.connectionState?(await k().catch(()=>{}),b&&clearTimeout(b),b=setTimeout(()=>{"disconnected"===c.connectionState&&(a.dispatch(kf.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:r})).then(()=>{p&&Uu(a,r)}),console.error(`RTC Connection with peer ${t} in room ${r} has disconnected.`))},8e3)):"closed"===c.connectionState||"failed"===c.connectionState?(b&&(clearTimeout(b),b=void 0),await a.dispatch(kf.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:r})),console.error(`RTC Connection with peer ${t} in room ${r} has ${c.connectionState}.`),p&&Uu(a,r)):(b&&(clearTimeout(b),b=void 0),"connected"===c.connectionState&&(p=!0,a.dispatch(Ze({roomId:r,peerId:t,peerPublicKey:n})),It(`RTC Connection status with peer ${t} is ${c.connectionState}.`)))},c}finally{s.release(),((e,t)=>{const n=lh(e,t),r=ah.get(n);r&&dh(ah,n,r)})(r,n)}},yh=(e,t,n)=>{e.ondatachannel=async r=>{try{const o=await Gu({channel:r.channel,epc:e,roomId:e.roomId,dataChannels:t,incoming:!0},n);"main"===o.label&&(e.mainChannel=o)}catch(e){console.error("Rejected incoming DataChannel:",e)}}},gh=new Map,wh=(e,t)=>`${String(e.length)}:${e}${t}`,bh=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},vh=e=>{if(null!=e){if("string"!=typeof e)return e;try{return Wl(e)}catch{return}}},kh=(e,t,n)=>{const r=t.filter(e=>n-e.retiredAt<12e4);return 0===r.length?gh.delete(e):r.length!==t.length&&gh.set(e,r),r},Ih=(e,t,n,r=Date.now())=>{const o=vh(n);if(!o)return!1;const a=wh(e,t),i=kh(a,gh.get(a)??[],r).filter(e=>!bh(e.fingerprint,o));for(i.push({fingerprint:o,retiredAt:r});i.length>4;)i.shift();return gh.set(a,i),!0},Sh=(e,t)=>{gh.delete(wh(e,t))},Ch=async(e,t,n)=>{const r=e.createDataChannel("main",{ordered:!0,protocol:"raw"});e.mainChannel=await Gu({channel:r,epc:e,roomId:e.roomId,dataChannels:t},n)},Ah=(e,t,n)=>{for(let r=e.length-1;r>=0;r--)e[r].roomId===t&&e[r].withPeerId===n&&e.splice(r,1)},Eh=(e,t,n,r)=>{e.length=0,Ah(t,n,r)},Ph=({epc:e,roomId:t,peerId:n,descriptionType:r,isInitiator:o})=>e.remoteTransportRebinds>0&&!((e,t,n)=>void 0!==e.ratchetState||Gs(t,n,e.ratchetGateLease))(e,t,n)||((e,t,n)=>void 0!==e.ratchetState||Gs(t,n,e.ratchetGateLease)||"open"===e.mainChannel?.readyState)(e,t,n)&&("offer"===r||o)?"replace":"reset-in-place",xh=(e,t)=>{for(let n=t.length-1;n>=0;n--)t[n]===e&&t.splice(n,1)},Rh=(e,t,n)=>{e.releaseProtocolResources?.(),e.onopen=null,e.onclose=null,e.onerror=null,e.onclosing=null,e.onmessage=null,e.onbufferedamountlow=null,"closed"!==e.readyState&&e.close(),t.messageChannels?.delete(e),xh(e,n)},Mh=({epc:e,roomId:t,peerId:n,api:r,dataChannels:o,disconnectPeer:a,deadlineMs:i,schedule:s,reason:c})=>{if(_d(t,n,c),e.ratchetGateLease=Js(t,n,c),jd(e),e.pqHealingState&&(e.pqHealingState.destroy(),e.pqHealingState=void 0),e.ratchetState&&(Zi(e.ratchetState),e.ratchetState=void 0),e.messageKeyCache){for(const t of e.messageKeyCache.values())t.fill(0);e.messageKeyCache.clear(),e.messageKeyCache=void 0}e.messageKeyByMerkleRoot?.clear(),e.messageKeyByMerkleRoot=void 0,e.serializeEdgeCryptoState=void 0;const l=new Set(e.coverChannels);wu(e),oc(e);const d=e.mainChannel;e.mainChannel=void 0;const u=new Set(e.messageChannels);for(const e of o)e!==d&&!l.has(e)&&e.withPeerId===n&&e.roomIds.includes(t)&&u.add(e);for(const t of u)Rh(t,e,o);d&&(xh(d,o),"closed"!==d.readyState&&d.close()),e.remoteTransportRebinds=(e.remoteTransportRebinds??0)+1,(({epc:e,roomId:t,peerId:n,api:r,disconnectPeer:o,deadlineMs:a=1e4,schedule:i=_u})=>{Du(e);const s=e.ratchetGateLease,c=i.setTimeout(()=>{e.rebindDeadline=void 0,e.rebindDeadlineClear=void 0,e.ratchetGateLease===s&&Qs(t,n,s)&&void 0===e.ratchetState&&(Gs(t,n,s)||(It(`In-place re-bind for ${n} in ${t} did not authenticate within ${String(a)} ms; rebuilding the edge`),Promise.resolve().then(()=>o({roomId:t,peerId:n})).catch(e=>{console.error(`Failed to tear down the stalled re-bind of ${n} in ${t}:`,e)}).then(()=>{Uu(r,t)})))},a);(e=>{const t=e;t&&"function"==typeof t.unref&&t.unref()})(c),e.rebindDeadline=c,e.rebindDeadlineClear=i.clearTimeout})({epc:e,roomId:t,peerId:n,api:r,disconnectPeer:a,deadlineMs:i,schedule:s}),r.dispatch(tt({roomId:t,peerId:n,peerPublicKey:e.withPeerPublicKey,status:"authenticating"})),It(`Remote DTLS certificate changed for ${n} in ${t}; edge authentication reset`)},Kh=e=>"closed"===e.signalingState||"closed"===e.connectionState,Uh=async(e,t,{pollMs:n=100,maxMs:r=8e3,name:o="operation"}={})=>{const a=t.then(e=>({kind:"value",value:e}),e=>({kind:"error",error:e})),i=Date.now();for(;;){const t=Math.max(0,Math.min(n,r-(Date.now()-i)));let s,c;try{c=await Promise.race([a,new Promise(e=>{s=setTimeout(()=>{e({kind:"tick"})},t)})])}finally{clearTimeout(s)}if("value"===c.kind)return c.value;if("error"===c.kind)throw c.error;if(Kh(e))return"closed";if(Date.now()-i>=r)return console.warn(`Peer connection ${o} did not settle within ${String(r)} ms on a live transport; abandoning it`),"timeout"}},_h=async({peerId:e,peerPublicKey:t,roomId:n,description:r,rtcConfig:o,peerConnections:a,iceCandidates:i,dataChannels:s,disconnectPeer:c},l)=>hh(n,e,async()=>{const{keyPair:d}=l.getState(),u=eh(a,n,e);if("answer"===r.type&&((e,t,n,r=Date.now())=>{const o=wh(e,t),a=gh.get(o);if(!a)return!1;const i=kh(o,a,r);if(0===i.length)return!1;const s=vh(n);return!!s&&i.some(e=>bh(e.fingerprint,s))})(n,e,r.sdp))return console.warn(`Ignoring ${r.type} from a retired remote transport of ${e} in ${n}`),Eh(u>-1?a[u].iceCandidates:[],i,n,e),{data:void 0};let h=u>-1?a[u]:await ph({peerId:e,peerPublicKey:t,roomId:n,peerConnections:a},l);-1!==u&&null!=a[u].ondatachannel||yh(h,s,l);const f=u>-1&&((e,t)=>{if(void 0===e)return!1;let n,r;try{n=Wl(e),r=Wl(t)}catch{return!1}if(n.length!==r.length)return!0;for(let e=0;e<n.length;e++)if(n[e]!==r[e])return!0;return!1})(h.remoteDescription?.sdp,r.sdp),m="offer"===r.type&&(h.makingOffer||"stable"!==h.signalingState),p=null==h.remoteDescription||d.peerId<h.withPeerId,y=!p&&m;h.ignoreOffer=y;const g=()=>{Eh(h.iceCandidates,i,n,e)};if(y)return g(),{data:void 0};if(m&&p)try{const t=await Uh(h,h.setLocalDescription({type:"rollback"}),{name:`rollback(${n}, ${e})`});if("closed"===t)return g(),{data:void 0};if("timeout"===t)throw new Error(`rollback did not settle for ${e}`);It(`Polite peer rolled back local description for ${e}`)}catch(t){console.error(`Failed to rollback for ${e}:`,t)}if(h.iceCandidates.push(...((e,t,n)=>{const r=[];for(let o=e.length-1;o>=0;o--){const a=e[o];a.roomId===t&&a.withPeerId===n&&(r.unshift(a),e.splice(o,1))}return r})(i,n,e)),-1===eh(a,n,e)&&a.push(h),"closed"===h.signalingState)return g(),{data:void 0};if("answer"===r.type&&"have-local-offer"!==h.signalingState)return console.warn(`Ignoring stale answer from ${e} in signaling state ${h.signalingState}`),g(),{data:void 0};if(f){const i=jo(d.publicKey,h.withPeerPublicKey);if("replace"===Ph({epc:h,roomId:n,peerId:e,descriptionType:r.type,isInitiator:i})){if(It(`Remote DTLS certificate changed for ${e} in ${n} on an authenticated transport; replacing it`),Ih(n,e,h.remoteDescription?.sdp),await c({roomId:n,peerId:e}),"offer"!==r.type)return Uu(l,n),{data:void 0};try{h=await ph({peerId:e,peerPublicKey:t,roomId:n,peerConnections:a,rtcConfig:o},l)}catch(e){throw Uu(l,n),e}yh(h,s,l),a.includes(h)||a.push(h),l.dispatch(Ze({roomId:n,peerId:e,peerPublicKey:t}))}else Mh({epc:h,roomId:n,peerId:e,api:l,dataChannels:s,disconnectPeer:c,reason:new Error(`Remote DTLS certificate changed (${n}, ${e})`)})}try{const t=await Uh(h,h.setRemoteDescription(r),{name:`setRemoteDescription(${n}, ${e})`});if("closed"===t)return g(),{data:void 0};if("timeout"===t)throw new Error(`setRemoteDescription did not settle for ${e}`)}catch(t){const o=t;if("answer"===r.type&&o.message?.includes("Called in wrong state"))return console.warn(`Ignoring late answer from ${e}: ${o.message}`),g(),{data:void 0};if(!o.message?.includes("ICE restart"))return console.error(`setRemoteDescription failed for ${e}:`,t),g(),{data:void 0};console.warn(`ICE restart mismatch with ${e}, accepting remote restart`);try{if("stable"!==h.signalingState){const r=await Uh(h,h.setLocalDescription({type:"rollback"}),{name:`restart rollback(${n}, ${e})`});if("closed"===r)return g(),{data:void 0};if("timeout"===r)throw new Error(`rollback did not settle for ${e}`,{cause:t})}const o=await Uh(h,h.setRemoteDescription(r),{name:`restart setRemoteDescription(${n}, ${e})`});if("closed"===o)return g(),{data:void 0};if("timeout"===o)throw new Error(`setRemoteDescription did not settle for ${e}`,{cause:t})}catch(t){return console.error(`Failed to handle ICE restart for ${e}:`,t),g(),{data:void 0}}}if(((e,t,n)=>{const r=vh(n);if(!r)return;const o=wh(e,t),a=gh.get(o);if(!a)return;const i=a.filter(e=>!bh(e.fingerprint,r));i.length!==a.length&&(0===i.length?gh.delete(o):gh.set(o,i))})(n,e,r.sdp),"offer"===r.type){try{const t=await Uh(h,h.setLocalDescription(),{name:`setLocalDescription(${n}, ${e})`});if("closed"===t)return g(),{data:void 0};if("timeout"===t)throw new Error(`setLocalDescription did not settle for ${e}`)}catch(t){return console.error(`setLocalDescription failed for ${e}:`,t),g(),{data:void 0}}const t=h.localDescription;t&&await l.dispatch(Xf.endpoints.sendMessage.initiate({content:{type:"description",description:t,fromPeerId:d.peerId,fromPeerPublicKey:d.publicKey,toPeerId:e,roomId:n,protocolVersion:4}}))}if(!(e=>"closed"===e.signalingState||"closed"===e.connectionState)(h)&&jo(d.publicKey,h.withPeerPublicKey)&&(!h.mainChannel||"closing"===h.mainChannel.readyState||"closed"===h.mainChannel.readyState)){const e=h.createDataChannel("main",{ordered:!0,protocol:"raw"});h.mainChannel=await Gu({channel:e,epc:h,roomId:h.roomId,dataChannels:s},l)}return{data:void 0}}),Dh=(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),o=Math.ceil(r.toString(2).length/8),a=(1n<<BigInt(8*o))/r*r,i=new Uint8Array(o);let s=a;for(;s>=a;){window.crypto.getRandomValues(i),s=0n;for(let e=0;e<o;e++)s=(s<<8n)+BigInt(i[e])}n(e+Number(s%r))}catch(e){r(e instanceof Error?e:new Error(String(e)))}}),Th=async(e,t,n=!0,r=!0,o=!0)=>{if(t??=e,0===t&&e===t)return"";const a=t>e?await Dh(e,t):e,i=await((e,t=!0,n=!0,r=!0)=>new Promise((o,a)=>{try{let a="";t&&(a+="abcdefghijklmnopqrstuvwxyz"),n&&(a+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"),r&&(a+="0123456789");let i="";for(let t=0;t<e;t++)i+=a[Lh(0,a.length)];o(i)}catch(e){a(e instanceof Error?e:new Error(String(e)))}}))(a,n,r,o);return i};function Lh(e,t){if(!(t>e))return e;const n=t-e,r=Math.floor(4294967296/n)*n;let o;do{o=crypto.getRandomValues(new Uint32Array(1))[0]}while(o>=r);return e+o%n}const qh=(e,t)=>{const n=t._malloc(g),r=t._malloc(1+e.length),o=t._malloc(y);try{const a=new Uint8Array(t.wasmMemory.buffer,r,1+e.length);if(a[0]=0,a.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,o))throw new Error("hashMerkleLeafWasm: sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,o,y))}finally{t._free(n),t._free(r),t._free(o)}},Oh=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)},Nh=async(e,t)=>{if(e.length%y!==0)throw new Error("Hashes were not passed");const n=e.length/y;if(0===n)throw new Error("Cannot calculate Merkle root of tree with no leaves.");if(1===n)return e;const r=t?.wasmMemory??go(n),o=t??await _o(r),a=o._malloc(n*y),i=new Uint8Array(r.buffer,a,n*y);i.set(e);const s=o._malloc(y),c=new Uint8Array(r.buffer,s,y),l=o._get_merkle_root(n,i.byteOffset,c.byteOffset);switch(o._free(a),l){case 0:{const e=Uint8Array.from([...c]);return o._free(s),e}case-1:throw o._free(s),new Error("Could not allocate memory for hash concatenation helper array.");case-2:throw o._free(s),new Error("Could not calculate hash.");default:throw o._free(s),new Error("Unexpected error occured.")}},Bh=async(e,t,n,r)=>{if(e.length%y!==0)throw new Error("Hashes were not passed");const o=e.length/y;if(0===o)throw new Error("Cannot calculate Merkle proof of element of empty tree.");if(1===o){const e=new Uint8Array(y+1);if(e.set(t),r){const t=y+1,n=globalThis.crypto.getRandomValues(new Uint8Array(r));let o=0;const a=4;return new DataView(n.buffer,o,a).setUint32(0,t,!1),o+=a,n.set(e,o),n}return e}const a=n?.wasmMemory??wo(o),i=n??await _o(a),s=i._malloc(o*y),c=new Uint8Array(a.buffer,s,o*y);c.set(e);const l=i._malloc(y),d=new Uint8Array(a.buffer,l,y);d.set(t);const u=o*(y+1),h=i._malloc(u),f=new Uint8Array(a.buffer,h,u),m=i._get_merkle_proof(o,c.byteOffset,d.byteOffset,f.byteOffset);switch(i._free(s),i._free(l),m){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(m>0){if(r&&r>=m){const e=globalThis.crypto.getRandomValues(new Uint8Array(r));let t=0;const n=4;return new DataView(e.buffer,t,n).setUint32(0,m,!1),t+=n,e.set(f.slice(0,m),t),i._free(h),e}{const e=Uint8Array.from([...f.slice(0,m)]);return i._free(h),e}}throw i._free(h),new Error("An unexpected error occured")}},Fh=[1],jh=(e,t=1,n=q,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>q||n<=O)throw new Error(`Chunk length needs to be between ${String(O)} and ${String(q)}`);if(!Number.isSafeInteger(e)||e<1)throw new Error("No data to split in chunks");if(e>_)throw new Error(`Message exceeds the ${String(_)} byte protocol limit`);const o=Math.ceil(n*r),a=Math.ceil(e/o);return Math.max(t,a)},zh=async(e,t,n,r,o,a,i=1,s=q,c=.9,l=1)=>{const{keyPair:d}=t.getState();if(!Fh.includes(l))throw new Error("Unknown metadata version schema.");const u=(e=>{if("string"==typeof e)return Ii.Text;const t=e.name.split(".").pop()?.toLowerCase()??"";return{png:Ii.ImagePNG,jpeg:Ii.ImageJPEG,jpg:Ii.ImageJPG,gif:Ii.ImageGIF,bmp:Ii.ImageBMP,tiff:Ii.ImageTIFF,svg:Ii.ImageSVG,webp:Ii.ImageWEBP,heic:Ii.ImageHEIC,pdf:Ii.DocumentPDF,doc:Ii.DocumentDOC,docx:Ii.DocumentDOCX,xls:Ii.DocumentXLS,xlsx:Ii.DocumentXLSX,ppt:Ii.DocumentPPT,pptx:Ii.DocumentPPTX,txt:Ii.DocumentTXT,rtf:Ii.DocumentRTF,odt:Ii.DocumentODT,mp3:Ii.AudioMP3,wav:Ii.AudioWAV,aac:Ii.AudioAAC,flac:Ii.AudioFLAC,ogg:Ii.AudioOGG,m4a:Ii.AudioM4A,mp4:Ii.VideoMP4,avi:Ii.VideoAVI,mkv:Ii.VideoMKV,mov:Ii.VideoMOV,wmv:Ii.VideoWMV,flv:Ii.VideoFLV,webm:Ii.VideoWEBM,zip:Ii.CompressedZIP,rar:Ii.CompressedRAR,"7z":Ii.Compressed7Z,tar:Ii.CompressedTAR,gz:Ii.CompressedGZ,html:Ii.CodeHTML,css:Ii.CodeCSS,js:Ii.CodeJS,ts:Ii.CodeTS,jsx:Ii.CodeJSX,tsx:Ii.CodeTSX,json:Ii.CodeJSON,xml:Ii.CodeXML,py:Ii.CodePY,java:Ii.CodeJAVA,c:Ii.CodeC,cpp:Ii.CodeCPP,cs:Ii.CodeCS,rb:Ii.CodeRB,php:Ii.CodePHP,sql:Ii.CodeSQL,epub:Ii.EbookEPUB,mobi:Ii.EbookMOBI,azw:Ii.EbookAZW,ttf:Ii.FontTTF,otf:Ii.FontOTF,ico:Ii.ImageICO,exe:Ii.ExecutableEXE,dmg:Ii.ExecutableDMG,apk:Ii.ExecutableAPK}[t]??Ii.Unknown})(e),h=u===Ii.Text?await Th(256):e.name.substring(0,255),f="string"==typeof e?(new TextEncoder).encode(e):e,m="string"==typeof e?f.length:f.size,p=jh(m,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+T+L+2048);return Number.isSafeInteger(r)?r:Number.POSITIVE_INFINITY})(m,p,s);if(I>k)throw new Error("Not enough space to stage the padded encrypted transfer in the browser.");const S=new Date;let C;if(a.signal.aborted)throw a.signal.reason instanceof Error?a.signal.reason:new Error("Message transfer cancelled");if("string"==typeof e){const e=await window.crypto.subtle.digest("SHA-512",f.buffer);C=new Uint8Array(e)}else C=await(async(e,t,n)=>{const r=()=>{if(n?.aborted){if(n.reason instanceof Error)throw n.reason;throw new Error("Message transfer cancelled")}},o=t._malloc(g),a=t._malloc(ee),i=t._malloc(y);try{if(r(),0!==t._sha512_init(o))throw new Error("sha512_init failed");const n=new Uint8Array(t.wasmMemory.buffer,a,ee);for(let i=0;i<e.size;i+=Z){r();const s=Math.min(i+Z,e.size),c=new Uint8Array(await e.slice(i,s).arrayBuffer());r();for(let e=0;e<c.length;e+=ee){r();const i=Math.min(ee,c.length-e);if(n.set(c.subarray(e,e+i),0),0!==t._sha512_update(o,a,i))throw new Error("sha512_update failed")}}if(r(),0!==t._sha512_final(o,i))throw new Error("sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,i,y))}finally{t._free(o),t._free(a),t._free(i)}})(f,o,a.signal);if(a.signal.aborted)throw a.signal.reason instanceof Error?a.signal.reason:new Error("Message transfer cancelled");const A=so(C);a.bindHash(A);const E={schemaVersion:l,messageType:u,hash:C,name:h,totalSize:m,date:S};let P=0;const x=new Uint8Array(s),R=new Uint8Array(p*y),M=Math.floor(s*(1-c)),K=Math.ceil(s*c);for(let o=0;o<p&&!a.signal.aborted;o++){window.crypto.getRandomValues(x);const i=await Dh(0,M),s=m-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(a.signal.aborted)break;x.set(new Uint8Array(e),i)}P+=c}else{const e=l+m+1,t=Number.MAX_SAFE_INTEGER-e;l+=await Dh(e,t)}const g=await Oh(x),w=so(g);R.set(g,o*y);const b=vi({...E,chunkStartIndex:i,chunkEndIndex:l,chunkIndex:o});await Ya({transferId:a.transferId,hash:A,merkleRoot:"",chunkIndex:o,leafHash:w,receiptToken:"",data:x.slice().buffer,metadata:b.buffer,merkleProof:(new Uint8Array).buffer}),t.dispatch(ot({roomId:r.id,transferId:a.transferId,merkleRootHex:"",sha512Hex:A,fromPeerId:d.peerId,chunkSize:0,totalSize:m,chunksCreated:o+1,totalChunks:p,messageType:u,filename:h,channelLabel:n,timestamp:S.getTime()}))}if(a.signal.aborted)return await Za({transferId:a.transferId}),t.dispatch(lt({roomId:r.id,transferId:a.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};const U=await Nh(R,o),_=so(U);try{const e=Ci(u);for(let t=0;t<p&&!a.signal.aborted;t++){const n=await Qa(a.transferId,t);if(!n)throw new Error(`Missing staged outbound chunk ${String(t)}`);const r=ki(new Uint8Array(n.metadata)),o=r.chunkEndIndex-r.chunkStartIndex;o<=0||o>r.totalSize||await Ga({merkleRoot:_,hash:A,chunkIndex:r.chunkIndex,data:n.data.slice(r.chunkStartIndex,r.chunkEndIndex),mimeType:e})}}catch(e){throw await Ja(_),e}if(a.signal.aborted)return await Za({transferId:a.transferId}),await Ja(_),t.dispatch(lt({roomId:r.id,transferId:a.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};try{await((e,t,n,r,o,a,i,s,c,l,d)=>Fa("setDBRoomMessageData",e,t,n,r,o,a,i,s,c,l,d))(r.id,_,A,d.peerId,m,m,u,h,n,S.getTime(),a.transferId)}catch(e){throw await Ja(_),e}return t.dispatch(ot({roomId:r.id,transferId:a.transferId,merkleRootHex:_,sha512Hex:A,fromPeerId:d.peerId,chunkSize:0,totalSize:m,chunksCreated:p,totalChunks:p,messageType:u,filename:h,channelLabel:n,timestamp:S.getTime()})),{merkleRoot:U,merkleRootHex:_,hash:C,hashHex:A,totalSize:m,totalChunks:p,messageType:u,chunkHashes:R}},$h=async(e,t=3e3,n=25,r)=>{const o=Date.now();for(;"connecting"===e.readyState&&Date.now()-o<t&&!r?.aborted;)await new Promise(e=>setTimeout(e,n));return!r?.aborted&&"open"===e.readyState},Hh="Peer is not authenticated on this transport: the handshake did not complete within the wait budget",Vh=e=>e instanceof Error&&e.message===Hh,Wh=async(e,t,n,r=45e3)=>{let o;Mu(n);const a=new Promise((e,t)=>{o=setTimeout(()=>{t(new Error(Hh))},r)});try{await Ku(Promise.race([Ws(e,t),a]),n)}finally{clearTimeout(o)}},Qh=(e,t)=>`${e}\0${t}`,Gh=async e=>{let t=e.inFlight(),n=Date.now();for(;e.isOpen()&&e.inFlight()>=e.windowSize;){Mu(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)),Mu(e.signal)}Mu(e.signal)},Xh=async(e,t,n,r,o,a,i,s,c,l,d,u,h,f)=>{Mu(u);const{merkleRootHex:m}=await li(e.label);if(m!==so(i))throw new Error("Outbound channel label does not match its Merkle root");const p=f?.()??0;let g=0;const w=function(e){const t=e.slice();for(let e=t.length-1;e>0;e--){const n=Lh(0,e+1);[t[e],t[n]]=[t[n],t[e]]}return t}(Array.from({length:o},(e,t)=>t));for(let b=0;b<o;b++){Mu(u);const o=w[b],v=await Qa(s,o);if(Mu(u),!v)throw new Error(`Missing staged outbound chunk ${String(o)}`);const k=new Uint8Array(v.metadata),I=ki(k);if(I.chunkIndex!==o||v.chunkIndex!==o)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 Gh({windowSize:32,stallTimeoutMs:1e4,pollMs:25,isOpen:()=>"open"===e.readyState,inFlight:()=>g-Math.max(0,f()-p),signal:u});const C=new Uint8Array(L);if(0===v.merkleProof.byteLength){const e=await Bh(a,co(v.leafHash),d,L);Mu(u),C.set(e)}else C.set(new Uint8Array(v.merkleProof));const A=v.receiptToken.length===2*y?v.receiptToken:so(await Ei(i,I.chunkIndex,co(v.leafHash)));if(Mu(u),0!==v.merkleProof.byteLength&&v.merkleRoot===m&&v.receiptToken===A||await Ya({transferId:s,hash:c,merkleRoot:m,leafHash:v.leafHash,receiptToken:A,chunkIndex:o,data:v.data,metadata:v.metadata,merkleProof:C.buffer}),N!==k.length+C.length+new Uint8Array(v.data).length)throw new Error("Outbound staged chunk has invalid cell length");const E=await ao([k,C,new Uint8Array(v.data)]);for(Mu(u);"open"===e.readyState&&e.bufferedAmount>=D;)await new Promise(e=>setTimeout(e,25)),Mu(u);if("open"!==e.readyState){It("Cannot send message because channel is "+e.readyState+" and bufferedAmount is "+String(e.bufferedAmount));break}let P;try{P=vs(t,n,E,i,l,r??void 0)}catch(e){throw new Error("Could not seal outbound message chunk",{cause:e})}Mu(u);try{e.send(P.buffer),S&&g++}catch(t){if("open"!==e.readyState)break;throw t}}},Jh=(e,t,n)=>"connected"===e.connectionState?Promise.resolve(!0):"closed"===e.connectionState||"failed"===e.connectionState||n?.aborted?Promise.resolve(!1):new Promise(r=>{let o=!1;const a=t=>{o||(o=!0,clearTimeout(c),e.removeEventListener("connectionstatechange",i),n?.removeEventListener("abort",s),r(t))},i=()=>{"connected"===e.connectionState?a(!0):"closed"!==e.connectionState&&"failed"!==e.connectionState||a(!1)},s=()=>{a(!1)},c=setTimeout(()=>{a(!1)},t);e.addEventListener("connectionstatechange",i),n?.addEventListener("abort",s,{once:!0})}),Yh=async(e,t,n,r,o,a,i,s)=>{const c=Date.now()+i;for(;Date.now()<c;){Mu(s);const i=o.find(e=>e.roomId===t&&e.withPeerId===n&&"connected"===e.connectionState);if(i)try{await ei(Qh(t,r),n);const o=await Gu({channel:r,epc:i,roomId:t,dataChannels:a},e);if(await $h(o,c-Date.now(),void 0,s))return{epc:i,channel:o};try{Zh(o)}catch(e){console.error(e)}Mu(s)}catch(e){console.error(e)}else await new Promise(e=>setTimeout(e,500)),Mu(s)}return null},Zh=e=>{e.releaseProtocolResources?.(),"closed"!==e.readyState&&e.close()},ef=async(e,t)=>{if(!e.pqHealingState)return;const n=Date.now()+6e4;for(;Nd(e);){if(Mu(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))}},tf=async(e,t,n,r,o=Wh,a=Ls,i)=>{if(Mu(i),e.epc===t&&e.lease===t.ratchetGateLease)return e;if(await Ku(o(n,t.withPeerId,i),i),!t.ratchetState)throw new Error("v3 send: replacement connection has no ratchet state");const s=await a(t,n,r);return i?.aborted&&(s.messageKey.fill(0),s.pqContext?.rootKey.fill(0),Mu(i)),e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),{epc:t,lease:t.ratchetGateLease,messageKey:s.messageKey,header:s.header,pqContext:s.pqContext}},nf=(e,t,n,r,o)=>"connected"===e.connectionState&&void 0!==o&&Qs(n,r,o)&&t.some(t=>t===e&&t.roomId===n&&t.withPeerId===r),rf=(e,t)=>!t?.aborted&&!Vh(e);class of 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 af=async(e,t,n,r,o,a,i,s,c,l,d,u,h,f,m)=>{Mu(m),gi(n,l,s);let p,y,g,w=r.ratchetGateLease;await ei(Qh(n,e.label),l),Mu(m);try{await Wh(n,l,m)}catch(e){if(Vh(e))throw e;throw new Error("v3 send: ratchet gate rejected",{cause:e})}if(!r.ratchetState)throw new Error("v3 send: no ratchet state for peer");await ef(r,m);try{const e=await Ls(r,n,d);m?.aborted&&(e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),Mu(m)),p=e.messageKey,y=e.header,g=e.pqContext}catch(e){throw new Error("v3 send: durable ratchet advance failed",{cause:e})}let b=e,v=r;const k=async()=>{const r=e.label;if(!await $h(b,void 0,void 0,m))throw new Error("Message DataChannel did not open before send timeout");Mu(m),await Xh(b,p,y,g,o,a,i,s,c,d,u,m,void 0,()=>mi(n,l,s));let k=0,I=0,S=!1;for(;k<5;){const e=await wi(n,l,s,2e3*(k+1),m);if(Mu(m),e){S=!0;break}if("closed"===b.readyState||"closing"===b.readyState){if(nf(v,h,n,l,w))throw new Error("Message transfer cancelled by peer");if(I>=3)break;I++;const e=await Yh(t,n,l,r,h,f,3e4,m);if(!e)break;let o;b=e.channel;try{o=await tf({epc:v,lease:w,messageKey:p,header:y,pqContext:g},e.epc,n,d,Wh,Ls,m)}catch(e){if(!rf(e,m))throw e;console.error(e),Zh(b);continue}v=o.epc,w=o.lease,p=o.messageKey,y=o.header,g=o.pqContext??null,k=0,t.dispatch(it({roomId:n,sha512Hex:c,retransmit:!0}));continue}await Xh(b,p,y,g,o,a,i,s,c,d,u,m,fi(n,l,s),()=>mi(n,l,s)),k++,t.dispatch(it({roomId:n,sha512Hex:c,retransmit:!0}))}if(!S)throw new Error("Message transfer ended without receiver confirmation")};try{await(async(e,t)=>{try{return await t()}finally{Zh(e())}})(()=>b,k)}finally{p.fill(0),g?.rootKey.fill(0),gi(n,l,s)}},sf=(e,t,n,r,o,a,i,s,c,l)=>async d=>{const u=await Qa(e,d);if(!u)return null;const h=new Uint8Array(u.metadata),f=ki(h),m=new Uint8Array(L);0===u.merkleProof.byteLength?m.set(await Bh(n,co(u.leafHash),l,L)):m.set(new Uint8Array(u.merkleProof));const p=u.receiptToken.length===2*y?u.receiptToken:so(await Ei(r,f.chunkIndex,co(u.leafHash)));0!==u.merkleProof.byteLength&&u.merkleRoot===o&&u.receiptToken===p||await Ya({transferId:e,hash:t,merkleRoot:o,leafHash:u.leafHash,receiptToken:p,chunkIndex:d,data:u.data,metadata:u.metadata,merkleProof:m.buffer});const g=await ao([h,m,new Uint8Array(u.data)]);return vs(a,i,g,r,c,s??void 0)},cf=12e4,lf=async(e,t,n,r,o,a,i,s,c,l=1,d=q,u=.9,h=1)=>{const f=((e,t)=>{const n=[...ku.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,Iu(e,n))}}:Eu(e,t)})(r,c);let m="",p=!1,y=!1;try{Mu(f.signal);const{rooms:c}=t.getState(),g=c.findIndex(e=>e.id===r);if(-1===g)throw new Error("No room with id "+r);if(g>-1){const w=c[g].channels.findIndex(e=>e.label===n);if(-1===w)throw new Error("No channel with label "+n);const{merkleRoot:b,merkleRootHex:k,hashHex:I,totalChunks:S,chunkHashes:C}=await zh(e,t,n,c[g],s,f,l,d,u,h);if(f.bindMerkleRoot(k),m=k,Mu(f.signal),0===b.length||0===I.length||0===S||0===C.length)return;p=!0;const A=await ci(n,k),E=c[g].channels[w].peerIds.map(e=>({peerId:e,epc:o.find(t=>t.roomId===r&&t.withPeerId===e)})),P="scheduled"===c[g].policy.coverMode?await(async(e,t,n,r,o,a,i,s,c,l,d,u,h)=>{const f=[];let m=0;for(const p of n){if(u?.aborted){f.push({peerId:p.peerId,status:"skipped",reason:"cancelled"});continue}const n=p.epc;if(n&&await Jh(n,12e3,u)&&n.coverRuntime)try{if(await Wh(e,p.peerId,u),!n.ratchetState)throw new Error("v4 scheduled send: no ratchet state");await ef(n,u);const y=await Ls(n,e,l),g=await ci(t,i),w=sf(s,c,o,a,i,y.messageKey,y.header,y.pqContext,l,d);if(!vu({epc:n,channelMessageLabel:g,totalChunks:r,sealSlotCell:w,getAckedChunks:()=>fi(e,p.peerId,s)}))throw new Error("v4 scheduled send: edge has no cover runtime");bu(n,e,p.peerId,i,s),m+=1,h?.();const b=await wi(e,p.peerId,s,cf,u);y.messageKey.fill(0),y.pqContext?.rootKey.fill(0),f.push(b?{peerId:p.peerId,status:"delivered"}:{peerId:p.peerId,status:"failed",phase:"transfer",reason:new Error("scheduled delivery not confirmed")})}catch(e){f.push({peerId:p.peerId,status:"failed",phase:"transfer",reason:e})}else f.push({peerId:p.peerId,status:"skipped",reason:"not-connected"})}return{outcomes:f,startedTransfers:m}})(r,n,E,S,C,b,k,f.transferId,I,i,s,f.signal,()=>{y=!0}):await(async(e,t,n,r,o)=>{const a=[];let i=0;for(const s of e){if(r?.aborted){a.push({peerId:s.peerId,status:"skipped",reason:"cancelled"});continue}if(!s.epc||!await Jh(s.epc,12e3,r)){a.push({peerId:s.peerId,status:"skipped",reason:"not-connected"});continue}if(s.epc.withPeerPublicKey.length!==2*v){a.push({peerId:s.peerId,status:"skipped",reason:"unauthenticated"});continue}const e=s;let c;try{c=await t(e)}catch(e){a.push({peerId:s.peerId,status:"failed",phase:"setup",reason:e});continue}if(r?.aborted)Zh(c),a.push({peerId:s.peerId,status:"skipped",reason:"cancelled"});else{i++,o?.();try{const t=n(e,c);a.push(Promise.resolve(t).then(()=>({peerId:s.peerId,status:"delivered"}),e=>({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})))}catch(e){Zh(c),a.push({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})}}}return{outcomes:await Promise.all(a),startedTransfers:i}})(E,({epc:e})=>Gu({channel:A,epc:e,roomId:r,dataChannels:a},t),({peerId:e,epc:n},c)=>af(c,t,r,n,S,C,b,f.transferId,I,e,i,s,o,a,f.signal),f.signal,()=>{y=!0}),x={transferId:f.transferId,merkleRootHex:k,...P};Mu(f.signal);const R=x.outcomes.filter(e=>"delivered"===e.status).length;if(0===x.startedTransfers)throw new of(x,"No authenticated connected peers accepted the send");if(0===R)throw new of(x,"Message was not delivered to any peer");return x}return}catch(e){if(((e,t,n)=>n||!e&&!t)(p,y,f.signal.aborted)&&(m.length>0&&await Ja(m),t.dispatch(lt({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 Za({transferId:f.transferId}),f.finish()}},df=async({alsoDeleteDB:e,peerConnections:t,dataChannels:n,disconnectPeer: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 o=[...new Set(t.map(e=>e.withPeerId))];for(const e of o)await r({peerId:e});return e&&await Fa("deleteDB"),{data:void 0}},uf={getMessages:Wa,deleteRoomRecord:e=>Fa("deleteDBUniqueRoom",e),deleteReceive:Ja,deleteOutgoing:async e=>await Za({merkleRootHex:e})},hf=async(e,t,n=uf)=>{const r=[];let o=[];try{o=await n.getMessages(e)}catch(e){r.push(e)}try{await n.deleteRoomRecord(e)}catch(e){r.push(e)}for(const e of o){try{await n.deleteReceive(e.merkleRoot)}catch(e){r.push(e)}try{await n.deleteOutgoing(e.merkleRoot)}catch(e){r.push(e)}t(e.merkleRoot)}if(r.length>0)throw new AggregateError(r,"Room data deletion did not fully settle")},ff=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{}},mf=e=>({...e,urls:Array.isArray(e.urls)?[...e.urls]:e.urls}),pf=e=>null!=e.localDescription||null!=e.remoteDescription,yf=(e,t,n,r=!1,o="rollback")=>{const a=e.filter(e=>e.roomId===t&&"closed"!==e.connectionState&&"closed"!==e.signalingState),i=(n.iceServers??[]).map(mf),s=a.map(e=>({connection:e,configuration:e.getConfiguration()}));try{for(const{connection:e,configuration:t}of s)e.setConfiguration({...t,iceServers:i.map(mf)});if(r)for(const{connection:e}of s)pf(e)&&e.restartIce()}catch(e){if("close"===o)for(const{connection:e}of s)e.close();else(()=>{for(const{connection:e,configuration:t}of s)try{e.setConfiguration(t),r&&pf(e)&&e.restartIce()}catch{e.close()}})();throw e}return a.length},gf=[],wf=[],bf=[],vf=e=>async t=>{await e.dispatch(kf.endpoints.disconnectFromPeer.initiate(t)).unwrap()},kf=to({reducerPath:"webrtcApi",baseQuery:async({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:o,dataChannels:a},i)=>hh(n,e,async()=>{const{keyPair:r}=i.getState();if(e===r.peerId)throw new Error("Cannot create a connection with oneself.");const s=jo(r.publicKey,t);if(await za(e))return{data:void 0};const c=eh(o,n,e);if(c>-1){const t=o[c];if("closed"!==t.connectionState&&"failed"!==t.connectionState)return!s||t.mainChannel&&"closing"!==t.mainChannel.readyState&&"closed"!==t.mainChannel.readyState||await Ch(t,a,i),{data:void 0};Ih(n,e,t.remoteDescription?.sdp),wu(t),(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})(t),"closed"!==t.connectionState&&t.close(),o.splice(c,1)}const l=await ph({peerId:e,peerPublicKey:t,roomId:n,peerConnections:o},i);return yh(l,a,i),o.includes(l)||o.push(l),s&&await Ch(l,a,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:gf,dataChannels:bf})}),setDescription:e.mutation({queryFn:(e,t,n)=>_h({...e,peerConnections:gf,iceCandidates:wf,dataChannels:bf,disconnectPeer:vf(t)},t)}),setCandidate:e.mutation({queryFn:(e,t,n)=>(async({peerId:e,roomId:t,candidate:n,peerConnections:r,iceCandidates:o},a)=>hh(t,e,async()=>{const{keyPair:i}=a.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=eh(r,t,e);if(c>-1){const n=r[c];if(n.ignoreOffer)return{data:void 0};if(n.remoteDescription&&"stable"===n.signalingState){if(Yu(s,n.remoteDescription)){let r;try{const a=await Uh(n,n.addIceCandidate(s),{name:`addIceCandidate(${t}, ${e})`});if("closed"===a)return Eh(n.iceCandidates,o,t,e),{data:void 0};r="timeout"===a}catch{r=!0}if(r){const e=n.makingOffer||"stable"!==n.signalingState;!(i.peerId<n.withPeerId)&&e||await Zu(n,async()=>{n.iceCandidates.length=0,await a.dispatch(kf.endpoints.disconnectFromPeer.initiate({peerId:n.withPeerId,roomId:n.roomId}))})}}}else((e,t)=>{for(;e.length>=64;)e.shift();e.push(t)})(n.iceCandidates,s)}else((e,t,n,r)=>{let o=0;for(let r=e.length-1;r>=0;r--)if(e[r].roomId===t&&e[r].withPeerId===n&&(o+=1,o>=64)){e.splice(r,1);break}for(;e.length>=1024;)e.shift();e.push({...r,roomId:t,withPeerId:n})})(o,t,e,s);return{data:void 0}}))({...e,peerConnections:gf,iceCandidates:wf},t)}),applyRoomConfiguration:e.mutation({queryFn:({roomId:e,rtcConfig:t,restartIce:n=!1,failurePolicy:r="rollback"})=>(yf(gf,e,t,n,r),{data:void 0})}),openChannel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,channel:t,withPeers:n,peerConnections:r,dataChannels:o},a)=>{const{keyPair:i}=a.getState(),s=async e=>{if("string"!=typeof t){const n=await Gu({channel:t,epc:e,roomId:e.roomId,dataChannels:o},a);return void("main"===n.label&&(e.mainChannel=n))}if(o.find(n=>n.withPeerId===e.withPeerId&&n.roomIds.includes(e.roomId)&&n.label===t&&"closing"!==n.readyState&&"closed"!==n.readyState))return;if("main"===t&&!jo(i.publicKey,e.withPeerPublicKey))return;const n=e.createDataChannel(t,{ordered:"main"===t,protocol:"raw"}),r=await Gu({channel:n,epc:e,roomId:e.roomId,dataChannels:o},a);"main"===r.label&&(e.mainChannel=r)};if(n&&n.length>0){const t=n.length;for(let o=0;o<t;o++){if(i.peerId===n[o].peerId)continue;const t=th(r,e,n[o].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:gf,dataChannels:bf},t)}),sendMessage:e.mutation({queryFn:(e,t,n)=>(async({data:e,transferId:t,label:n,roomId:r,peerConnections:o,dataChannels:a,minChunks:i,chunkSize:s,percentageFilledChunk:c,metadataSchemaVersion:l},d)=>{const u=i??1,h=s??q,f=c??.9,m="string"==typeof e?(new TextEncoder).encode(e).length:e.size,p=jh(m,u,h,f),y=await _o(yo()),g=await _o(wo(p));try{return{data:await async function(){return await lf(e,d,n,r,o,a,y,g,t,u,h,f,l)}()}}catch(e){if(e instanceof of)return{error:e};throw e}})({...e,peerConnections:gf,dataChannels:bf},t)}),disconnect:e.mutation({queryFn:(e,t,n)=>df({...e,peerConnections:gf,dataChannels:bf,disconnectPeer:vf(t)})}),disconnectFromRoom:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,deleteMessages:t,peerConnections:n,dataChannels:r,disconnectPeer:o},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 i=n.filter(t=>t.roomId===e).map(e=>e.withPeerId);for(const t of i)await o({peerId:t,roomId:e}),a.dispatch(st({peerId:t,roomId:e})),Sh(e,t);return t&&await hf(e,t=>{a.dispatch(dt({roomId:e,merkleRootHex:t}))}),{data:void 0}})({...e,peerConnections:gf,dataChannels:bf,disconnectPeer:vf(t)},t)}),disconnectFromAllRooms:e.mutation({queryFn:(e,t,n)=>(async({deleteMessages:e,exceptionRoomIds:t,peerConnections:n,dataChannels:r,disconnectPeer:o},a)=>{const i=new Set(t??[]);for(let e=r.length-1;e>=0;e--){const t=r[e];t.roomIds.some(e=>i.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 s=n.filter(e=>!i.has(e.roomId)).map(e=>({roomId:e.roomId,peerId:e.withPeerId}));for(const e of s)await o(e),a.dispatch(st(e)),Sh(e.roomId,e.peerId);if(e){const{rooms:e}=a.getState(),t=[];for(const n of e)if(!i.has(n.id))try{await hf(n.id,e=>{a.dispatch(dt({roomId:n.id,merkleRootHex:e}))})}catch(e){t.push(e)}if(t.length>0)throw new AggregateError(t,"All-room data deletion did not fully settle")}return{data:void 0}})({...e,peerConnections:gf,dataChannels:bf,disconnectPeer:vf(t)},t)}),disconnectFromPeer:e.mutation({queryFn:(e,t,n)=>(({peerId:e,roomId:t,alsoDeleteData:n,peerConnections:r,dataChannels:o,iceCandidates:a},i)=>{const s=new Set;for(let n=r.length-1;n>=0;n--){const o=r[n];if(o.withPeerId!==e||void 0!==t&&o.roomId!==t)continue;s.add(o.roomId),Ih(o.roomId,o.withPeerId,o.remoteDescription?.sdp);const a=new Error(`Room/peer transport closed (${o.roomId}, ${o.withPeerId})`);if(_d(o.roomId,o.withPeerId,a),Xs(o.roomId,o.withPeerId,a),o.ratchetState&&(Zi(o.ratchetState),o.ratchetState=void 0),wu(o),oc(o),jd(o),o.pqHealingState&&(o.pqHealingState.destroy(),o.pqHealingState=void 0),o.serializeEdgeCryptoState=void 0,o.messageKeyCache){for(const e of o.messageKeyCache.values())e.fill(0);o.messageKeyCache.clear(),o.messageKeyCache=void 0}o.messageKeyByMerkleRoot?.clear(),o.messageKeyByMerkleRoot=void 0,o.messageChannels?.clear(),o.messageChannels=void 0,o.mainChannel=void 0,Du(o),o.ontrack=null,o.ondatachannel=null,o.onicecandidate=null,o.onicecandidateerror=null,o.onnegotiationneeded=null,o.onsignalingstatechange=null,o.onconnectionstatechange=null,o.onicegatheringstatechange=null,o.oniceconnectionstatechange=null,"closed"!==o.connectionState&&o.close(),r.splice(n,1)}void 0!==t&&s.add(t);for(const t of s)Ah(a,t,e),uh(t,e);i.dispatch(st({peerId:e,roomId:t})),i.dispatch(ct({peerId:e,roomId:t}));for(let n=o.length-1;n>=0;n--){const r=o[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(),o.splice(n,1))}if(n){const{rooms:n}=i.getState(),r=n.length;for(let o=0;o<r;o++){if(void 0!==t&&n[o].id!==t)continue;const r=n[o].messages.length;for(let t=0;t<r;t++)n[o].messages[t].fromPeerId===e&&i.dispatch(lt({roomId:n[o].id,merkleRootHex:n[o].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:gf,dataChannels:bf,iceCandidates:wf},t)}),disconnectFromChannelLabel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,label:t,messageHash:n,alsoDeleteData:r,alsoSendFinishedMessage:o,dataChannels:a},i)=>{const s=a.length;if(0===s)return{data:void 0};for(let c=0;c<s;c++){if(a[c]?.label!==t||!a[c].roomIds.includes(e)||"open"!==a[c].readyState)continue;const s=a[c];if(r&&s.cancelReceiveTransfer?await s.cancelReceiveTransfer():s.releaseProtocolResources?.(),n&&o&&n.length===y&&Zs(a[c],n),await ff(a[c]),r){const{merkleRootHex:n}=await li(t);i.dispatch(lt({roomId:e,merkleRootHex:n}))}}return{data:void 0}})({...e,dataChannels:bf},t)}),disconnectFromPeerChannelLabel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,peerId:t,label:n,messageHash:r,alsoDeleteData:o,alsoSendFinishedMessage:a,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]&&(o&&c[h].cancelReceiveTransfer?await c[h].cancelReceiveTransfer():c[h].releaseProtocolResources?.(),r&&a&&r.length===y&&Zs(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 ff(c[h]),c.splice(h,1),await ei(Qh(e,n),t));const{merkleRootHex:f}=await li(n);f.length>0?o&&l.dispatch(lt({roomId:e,merkleRootHex:f})):u.isConnected&&!o||l.dispatch(ct({roomId:e,peerId:t,label:n}));const m=d.find(t=>t.id===e);if(!m?.channels.some(e=>e.peerIds.includes(t))){const n=eh(s,e,t);n>-1&&await l.dispatch(kf.endpoints.disconnectFromPeer.initiate({peerId:s[n].withPeerId,roomId:e}))}return{data:void 0}})({...e,peerConnections:gf,dataChannels:bf},t)})})}),If=(e,t)=>e.findIndex(e=>e.id===t&&!1!==e.signalingActive);const Sf=new class{#ve=new Map;shouldSend(e,t,n,r=Date.now()){const o=`${e}:${t}`,a=this.#ve.get(o);return!(void 0!==a&&r-a<n)&&(this.#ve.set(o,r),!0)}resetSocketLifecycle(){this.#ve.clear()}},Cf=e=>{if("PING"===e)return"raw";if("string"!=typeof e||0===e.length||e.length>32)return null;if(1!==(e.match(/"type"\s*:/g)??[]).length)return null;try{const t=JSON.parse(e);if("object"!=typeof t||null===t||Array.isArray(t)||Object.getPrototypeOf(t)!==Object.prototype)return null;const n=t;return 1===Object.keys(n).length&&"ping"===n.type?"json":null}catch{return null}};class Af{#ke=!0;isCurrent(e){return this.#ke&&e()}invalidate(){this.#ke=!1}}class Ef{#Ie;#Se;#Ce;#Ae;#Ee=Promise.resolve();#Pe=0;#xe=0;#Re=!1;constructor(e){const t=e.maxPending??128;if(!Number.isSafeInteger(t)||t<1)throw new Error("Signaling ingress capacity must be a positive integer");const n=e.maxPendingBytes??2097152;if(!Number.isSafeInteger(n)||n<1)throw new Error("Signaling ingress byte capacity must be a positive integer");this.#Ie=t,this.#Se=n,this.#Ce=e.onOverflow,this.#Ae=e.onTaskError??(()=>{})}get pendingCount(){return this.#Pe}get pendingBytes(){return this.#xe}get isClosed(){return this.#Re}enqueue(e,t=1){if(!Number.isSafeInteger(t)||t<0)throw new Error("Signaling ingress weight must be a nonnegative integer");if(this.#Re)return!1;if(this.#Pe>=this.#Ie||this.#xe+t>this.#Se){this.#Re=!0;try{this.#Ce()}catch(e){this.#Me(e)}return!1}this.#Pe+=1,this.#xe+=t;const n=this.#Ee.then(async()=>{this.#Re||await e()});return this.#Ee=n.catch(e=>{this.#Me(e)}).finally(()=>{this.#Pe-=1,this.#xe-=t}),!0}close(){this.#Re=!0}#Me(e){try{this.#Ae(e)}catch{}}}const Pf=/^[0-9a-f]{64}$/u;class xf extends Error{roomUrl;roomLeaveId;reason;constructor(e,t,n,r){super(`Remote room revocation was not confirmed (${n})${r?`: ${r}`:""}`),this.name="RemoteRoomRevocationUnconfirmedError",this.roomUrl=e,this.roomLeaveId=t,this.reason=n}}const Rf=new Map,Mf=new Map,Kf=(e,t)=>Rf.get(e.roomLeaveId)===e&&(Rf.delete(e.roomLeaveId),Mf.get(e.roomUrl)===e.roomLeaveId&&Mf.delete(e.roomUrl),clearTimeout(e.timeout),t?e.reject(t):e.resolve(),!0),Uf=(e,t,n,r,o={})=>{const a=Mf.get(t);if(a){const e=Rf.get(a);if(e)return e.socketToken===n?e.promise:Promise.reject(new xf(t,o.roomLeaveId??Zo(),"socket-replaced","another socket owns the pending leave"));Mf.delete(t)}if(Rf.size>=256)return Promise.reject(new xf(t,o.roomLeaveId??Zo(),"send-failed","pending leave bound is exhausted"));const i=((e,t,n=Zo())=>{if(!Yo(e))throw new Error("roomLeave: fromPeerId must be a UUIDv4");if(!Pf.test(t))throw new Error("roomLeave: roomUrl must be 32-byte lowercase hex");if(!Yo(n))throw new Error("roomLeave: roomLeaveId must be a UUIDv4");return{type:"leaveRoom",protocolVersion:4,fromPeerId:e,roomUrl:t,roomLeaveId:n}})(e,t,o.roomLeaveId??Zo());let s,c;const l=new Promise((e,t)=>{s=e,c=t}),d=o.timeoutMs??2e3;if(!Number.isSafeInteger(d)||d<1)return Promise.reject(new Error("roomLeave: timeout must be a positive integer"));const u={roomUrl:t,roomLeaveId:i.roomLeaveId,socketToken:n,promise:l,resolve:s,reject:c,timeout:void 0};u.timeout=setTimeout(()=>{Kf(u,new xf(t,i.roomLeaveId,"ack-timeout"))},d),Rf.set(i.roomLeaveId,u),Mf.set(t,i.roomLeaveId);try{Promise.resolve(r(i)).catch(e=>{Kf(u,new xf(t,i.roomLeaveId,"send-failed",e instanceof Error?e.message:String(e)))})}catch(e){Kf(u,new xf(t,i.roomLeaveId,"send-failed",e instanceof Error?e.message:String(e)))}return l},_f=e=>{if("object"!=typeof e||null===e||Object.getPrototypeOf(e)!==Object.prototype)return!1;const t=Object.keys(e).sort();return 4===t.length&&"protocolVersion"===t[0]&&"roomLeaveId"===t[1]&&"roomUrl"===t[2]&&"type"===t[3]&&"roomLeft"===e.type&&4===e.protocolVersion&&Pf.test(e.roomUrl)&&Yo(e.roomLeaveId)},Df=(e,t)=>{if(!_f(e))return!1;const n=Rf.get(e.roomLeaveId);return!(!n||n.socketToken!==t||n.roomUrl!==e.roomUrl)&&Kf(n)},Tf=(e,t)=>{let n=0;for(const r of[...Rf.values()])r.socketToken===e&&Kf(r,new xf(r.roomUrl,r.roomLeaveId,t))&&(n+=1);return n},Lf=async(t,n,r,o=()=>!0,a=()=>{})=>{try{if(!o())return;if("PING"===t.data){if(!o())return;return n.send("PONG"),void a()}const l=String(t.data);if(l.length>xe)return void console.error("Rejecting oversized signaling message");const h=JSON.parse(l);switch(h.type){case"ping":{if("json"!==Cf(t.data)){console.error("Rejecting malformed signaling heartbeat");break}const{keyPair:e}=r.getState();await r.dispatch(Xf.endpoints.sendMessage.initiate({content:{type:"pong",fromPeerId:e.peerId}})),a();break}case"roomLeft":Df(h,n)||console.error("Rejecting unsolicited, stale, or malformed room leave acknowledgement");break;case"peerId":{if(!($o(c=h)&&Ho(c,["type","peerId","challenge","protocolVersion","message"])&&"peerId"===c.type&&"string"==typeof c.peerId&&e.isUUID(c.peerId)&&"string"==typeof c.challenge&&/^[0-9a-f]{64}$/.test(c.challenge)&&"number"==typeof c.protocolVersion&&zo(c.protocolVersion)&&"string"==typeof c.message)){console.error("Rejecting malformed or incompatible auth challenge"),n.close(1002,"protocol-v4 auth required");break}const{keyPair:t}=r.getState(),a=await(async(e,t,n,r,o=()=>!0)=>{const a=co(e.secretKey);try{const e=n.match(/.{1,2}/g);if(!e)throw new Error("Invalid challenge format");const i=Uint8Array.from(e.map(e=>parseInt(e,16))),s=await qo(i,a),c=[...new Uint8Array(s)].map(e=>e.toString(16).padStart(2,"0")).join("");return o()?(r.dispatch(d({peerId:t,challenge:n,signature:c})),{type:"challenge",fromPeerId:t,challenge:n,signature:c,protocolVersion:4}):null}finally{a.fill(0)}})(t,h.peerId,h.challenge,r,o);if(!a||!o())break;n.send(JSON.stringify(a));break}case"roomId":{const t=(t=>{if(!Go(t))return null;const{roomUrl:n,roomRequestId:r}=t;return"string"==typeof n&&Vo.test(n)&&"string"==typeof r&&e.isUUID(r,4)?{roomUrl:n,roomRequestId:r}:null})(h);if(!t){console.error("Rejecting malformed room response correlation");break}const n=((e,t)=>{const n=ea.get(e);return!n||n.claimed||n.roomRequestId!==t?null:(n.claimed=!0,{roomUrl:e,roomRequestId:t,requestGeneration:n.requestGeneration})})(t.roomUrl,t.roomRequestId);if(!n){console.error("Rejecting unsolicited or stale room response");break}const{keyPair:a,rooms:i}=r.getState(),c=Xo(h,i,n,a.publicKey);if(!c.accepted){da(n.roomUrl,n.roomRequestId,new Error(`roomRequest: ${c.reason}`)),console.error("malformed-turn-credentials"===c.reason?"Rejecting malformed TURN credentials":"Rejecting incompatible or malformed room response");break}let l,d=c;try{l=((e,t)=>{if(oa.has(e))throw ca("room refresh slot is already reserved");if(!ma(e,t))throw ca("room refresh timer bound is exhausted");const n=Symbol(e);return oa.set(e,{token:n,expiresAtUnixSeconds:t}),{roomUrl:e,token:n}})(d.roomUrl,d.expiresAtUnixSeconds)}catch(e){da(d.roomUrl,d.roomRequestId,e instanceof Error?e:new Error("roomRequest: TURN refresh capacity is exhausted"));break}try{const t=()=>{return o()&&(e=>{const t=ea.get(e.roomUrl);return!0===t?.claimed&&t.roomRequestId===e.roomRequestId&&t.requestGeneration===e.requestGeneration})(n)&&(e=l,oa.get(e.roomUrl)?.token===e.token);var e},a=()=>{if(!t())return!1;const n=r.getState().rooms.find(e=>e.url===d.roomUrl);return void 0!==n&&!1!==n.signalingActive&&(!e.isUUID(n.id)||n.id===d.roomId)&&n.roomResponseGeneration<d.requestGeneration},i=await(s=()=>fh(d.roomUrl).runExclusive(async()=>{const e=r.getState(),o=Xo(h,e.rooms,n,e.keyPair.publicKey);if(!o.accepted)throw new Error(`roomRequest: ${o.reason}`);return d=o,await(async(e,t,n,r,o,a=()=>{})=>{if(!n())return!1;const i=o(e.roomUrl);if(!i)return!1;if(await t(e.roomId,e.nextRtcConfig,"rollback"),!n()){const n=o(e.roomUrl);return await t(e.roomId,n?.rtcConfig??i.rtcConfig,"close"),!1}let s;try{s=r()}catch(n){a(i);const r=o(e.roomUrl);throw await t(e.roomId,r?.rtcConfig??i.rtcConfig,"close"),n}if(!s){a(i);const n=o(e.roomUrl);await t(e.roomId,n?.rtcConfig??i.rtcConfig,"close")}return s})(d,async(e,t,n)=>{await r.dispatch(kf.endpoints.applyRoomConfiguration.initiate({roomId:e,rtcConfig:t,restartIce:!0,failurePolicy:n})).unwrap()},a,()=>{r.dispatch(d.action);const e=r.getState().rooms.find(e=>e.url===d.roomUrl);return!(!e||e.id!==d.roomId||e.roomResponseGeneration!==d.requestGeneration)&&!!t()&&(((e,t,n,r=()=>{},o={})=>{const a=oa.get(e.roomUrl);if(a?.token!==e.token||a.expiresAtUnixSeconds!==t)throw ca("room refresh reservation is stale");oa.delete(e.roomUrl),fa(e.roomUrl,t,n,r,o,e.token)})(l,d.expiresAtUnixSeconds,()=>wa(r,d.roomUrl,e=>Jf(r,e)),async()=>{const e=d.expiresAtUnixSeconds;null!==e&&await fh(d.roomUrl).runExclusive(async()=>{r.dispatch(We({roomUrl:d.roomUrl,expiresAtUnixSeconds:e,requestGeneration:d.requestGeneration}));const t=r.getState().rooms.find(e=>e.url===d.roomUrl);((e,t)=>void 0!==e&&e.signalingActive&&e.id===t.roomId&&e.roomResponseGeneration===t.requestGeneration&&null===e.signalingTurnCredentials)(t,d)&&await r.dispatch(kf.endpoints.applyRoomConfiguration.initiate({roomId:t.id,rtcConfig:t.rtcConfig,restartIce:!0,failurePolicy:"close"})).unwrap()})}),(e=>{const t=ea.get(e.roomUrl);return!(!t||!t.claimed||t.roomRequestId!==e.roomRequestId||t.requestGeneration!==e.requestGeneration||(clearTimeout(t.timeout),ea.delete(e.roomUrl),t.resolve(e),0))})({roomUrl:d.roomUrl,roomId:d.roomId,roomRequestId:d.roomRequestId,requestGeneration:d.requestGeneration,expiresAtUnixSeconds:d.expiresAtUnixSeconds}))},e=>r.getState().rooms.find(t=>t.url===e),e=>{r.dispatch(Ve({roomUrl:d.roomUrl,failedRoomId:d.roomId,failedRequestGeneration:d.requestGeneration,previousRoomId:e.id,previousRequestGeneration:e.roomResponseGeneration,previousTurnCredentials:e.signalingTurnCredentials,previousSignalingActive:e.signalingActive}))})}),sh.runExclusive(s));if(!i)throw new Error("roomRequest: atomic room transition was rejected")}catch(e){(e=>{const t=oa.get(e.roomUrl);if(t?.token===e.token)return oa.delete(e.roomUrl),!0;const n=ra.get(e.roomUrl);n?.token===e.token&&(n.timeout&&clearTimeout(n.timeout),ra.delete(e.roomUrl))})(l),mh(d.roomUrl),da(d.roomUrl,d.roomRequestId,e instanceof Error?e:new Error("roomRequest: failed to apply ICE configuration"));break}if(!o())break;r.dispatch(Ge({roomId:d.roomId,connectingToPeers:!0}));break}case"challenge":if(!(t=>!!$o(t)&&Ho(t,["type","challengeId","protocolVersion"])&&"challenge"===t.type&&"string"==typeof t.challengeId&&e.isUUID(t.challengeId)&&"number"==typeof t.protocolVersion&&zo(t.protocolVersion))(h)){console.error("Rejecting malformed or incompatible auth success"),n.close(1002,"protocol-v4 auth required");break}o()&&r.dispatch(u(h));break;case"peerConnection":{if(!(zo(h.protocolVersion)&&e.isUUID(h.peer.id)&&e.isUUID(h.roomId,4)&&Bo(h.peer.publicKey)))break;const t=await za(h.peer.id,h.peer.publicKey);if(!o())break;if(t)break;const{keyPair:n,rooms:a}=r.getState(),i=If(a,h.roomId);if(-1===i)break;if(a[i].onlyConnectWithKnownAddresses){const e=await ja(h.peer.id,h.peer.publicKey);if(!o())break;if(!e)break}if(!o())break;await r.dispatch(Xf.endpoints.sendMessage.initiate({content:{type:"peerConnection",roomId:h.roomId,fromPeerId:n.peerId,toPeerId:h.peer.id,protocolVersion:4}}));break}case"peers":{if(!zo(h.protocolVersion)||!e.isUUID(h.roomId)||!Array.isArray(h.peers)){console.error("Rejecting incompatible or malformed peer roster");break}It("[handleWebSocketMessage] Received peers response:",{roomId:h.roomId,peersCount:h.peers.length,peers:h.peers});const{keyPair:t,rooms:n}=r.getState(),a=If(n,h.roomId);if(a>-1){const i=((t,n,r)=>{if(t.length>Re||n.length>Re)throw new Error("Signaling peer roster exceeds the room edge cap");const o=t.map(e=>({...e})),a=new Map(o.map(e=>[e.peerId,e])),i=new Map(o.map(e=>[e.peerPublicKey,e]));for(const t of n){if(!e.isUUID(t.id)||!Bo(t.publicKey)||t.id===r.peerId||t.publicKey===r.publicKey)continue;if(a.has(t.id))continue;if(i.get(t.publicKey))continue;if(o.length>=Re)throw new Error("Signaling peer roster exceeds the room edge cap");const n={peerId:t.id,peerPublicKey:t.publicKey};o.push(n),a.set(n.peerId,n),i.set(n.peerPublicKey,n)}return o})(n[a].peers,h.peers,t);for(const e of i)r.dispatch(Ze({roomId:h.roomId,...e}));const s=h.peers.length;if(0===s){const{signalingServer:n}=r.getState(),o=Date.now();n.isConnected&&n.isVerified&&e.isUUID(t.peerId)&&Sf.shouldSend("empty-roster",h.roomId,5e3,o)&&await r.dispatch(Xf.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:t.peerId,roomId:h.roomId,protocolVersion:4}}));break}const c=n[a].onlyConnectWithKnownAddresses;for(let l=0;l<s;l++){if(h.peers[l].publicKey===t.publicKey||h.peers[l].id===t.peerId||!e.isUUID(h.peers[l].id)||!Bo(h.peers[l].publicKey))continue;if(!i.some(e=>e.peerId===h.peers[l].id&&e.peerPublicKey===h.peers[l].publicKey))continue;const s=await za(h.peers[l].id,h.peers[l].publicKey);if(!o())return;if(!s){if(c){const e=await ja(h.peers[l].id,h.peers[l].publicKey);if(!o())return;if(!e)continue}if(!o())return;await r.dispatch(kf.endpoints.connectWithPeer.initiate({roomId:h.roomId,peerId:h.peers[l].id,peerPublicKey:h.peers[l].publicKey,rtcConfig:n[a].rtcConfig}))}}}break}case"description":{if(!(zo(h.protocolVersion)&&e.isUUID(h.fromPeerId)&&Bo(h.fromPeerPublicKey)&&e.isUUID(h.roomId)&&(i=h.description,("offer"===i.type||"answer"===i.type||"pranswer"===i.type||"rollback"===i.type)&&"string"==typeof i.sdp&&i.sdp.length<=262144))){zo(h.protocolVersion)||console.error(`Rejecting SDP from ${h.fromPeerId}: incompatible protocol version ${String(h.protocolVersion)} (expected v4). No fallback.`);break}const t=await za(h.fromPeerId,h.fromPeerPublicKey);if(!o())break;if(!t){const{rooms:e}=r.getState(),t=If(e,h.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses){const e=await ja(h.fromPeerId,h.fromPeerPublicKey);if(!o())break;if(!e)break}if(!o())break;await r.dispatch(kf.endpoints.setDescription.initiate({peerId:h.fromPeerId,peerPublicKey:h.fromPeerPublicKey,roomId:h.roomId,description:h.description,rtcConfig:e[t].rtcConfig}))}break}case"candidate":{if(!(zo(h.protocolVersion)&&e.isUUID(h.fromPeerId)&&e.isUUID(h.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)})(h.candidate))){console.error(`Rejecting ICE from ${h.fromPeerId}: incompatible protocol version ${String(h.protocolVersion)} (expected v4). No fallback.`);break}const t=await za(h.fromPeerId);if(!o())break;if(!t){const{rooms:e}=r.getState(),t=If(e,h.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses){const e=await ja(h.fromPeerId);if(!o())break;if(!e)break}if(!o())break;await r.dispatch(kf.endpoints.setCandidate.initiate({peerId:h.fromPeerId,roomId:h.roomId,candidate:h.candidate}))}break}case"connection":{const{keyPair:t,rooms:n}=r.getState(),a=If(n,h.roomId);if(zo(h.protocolVersion)&&e.isUUID(t.peerId)&&e.isHexadecimal(t.challenge)&&e.isHexadecimal(t.signature)&&128===t.signature.length&&64===t.challenge.length&&e.isUUID(h.fromPeerId)&&Bo(h.fromPeerPublicKey)&&h.fromPeerId!==t.peerId&&h.fromPeerPublicKey!==t.publicKey&&e.isUUID(h.roomId)&&a>-1&&Me(h.labels)){const e=await za(h.fromPeerId,h.fromPeerPublicKey);if(!o())break;if(e)break;if(n[a].onlyConnectWithKnownAddresses){const e=await ja(h.fromPeerId,h.fromPeerPublicKey);if(!o())break;if(!e)break}if(!o())break;await(async(e,t,n)=>{await n.ensureConnection({roomId:e.roomId,peerId:e.fromPeerId,peerPublicKey:e.fromPeerPublicKey,rtcConfig:t}),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})})(h,n[a].rtcConfig,{recordPeer:e=>{o()&&r.dispatch(Ze(e))},recordChannel:e=>{o()&&(r.dispatch(nt(e)),It(`Connected with ${t.peerId} on websocket channel ${e.label}`))},ensureConnection:async e=>{o()&&await r.dispatch(kf.endpoints.connectWithPeer.initiate(e)).unwrap()}})}else zo(h.protocolVersion)||console.error(`Rejecting peer ${h.fromPeerId}: incompatible protocol version ${String(h.protocolVersion)} (expected v4). No fallback.`);break}case"error":console.error(h);break;default:console.error("Unknown message type "+JSON.stringify(h))}}catch(e){return void console.error("[p2party] WebSocket message handling error:",e)}var i,s,c};const qf=new class{activeToken=null;cancelCurrent=null;identityPurgeRequests=0;bootstrapMutex=new rh;begin(e){if(this.identityPurgeRequests>0)throw new Error("Identity purge is in progress");const t=Symbol(e);let n;const r=new Promise(e=>{n=e});return this.activeToken=t,this.cancelCurrent=n,{token:t,cancelled:r}}isCurrent(e){return this.activeToken===e}hasActiveAttempt(){return null!==this.activeToken}assertCurrent(e){if(!this.isCurrent(e))throw new Error("WebSocket connection attempt was cancelled")}addCancellationEffect(e,t){if(!this.isCurrent(e))return!1;const n=this.cancelCurrent;return this.cancelCurrent=()=>{n?.(),t()},!0}disarmCancellation(e){return!!this.isCurrent(e)&&(this.cancelCurrent=null,!0)}clear(e){return!!this.isCurrent(e)&&(this.activeToken=null,this.cancelCurrent=null,!0)}cancelActive(){const e=this.cancelCurrent;this.activeToken=null,this.cancelCurrent=null,e?.()}isIdentityPurgeActive(){return this.identityPurgeRequests>0}async acquireBootstrap(e){await this.bootstrapMutex.acquire();try{this.assertCurrent(e)}catch(e){throw this.bootstrapMutex.release(),e}let t=!1;return()=>{t||(t=!0,this.bootstrapMutex.release())}}async cancelAndAcquireBootstrap(){this.identityPurgeRequests+=1,this.cancelActive();try{await this.bootstrapMutex.acquire()}catch(e){throw this.identityPurgeRequests-=1,e}let e=!1;return()=>{e||(e=!0,this.bootstrapMutex.release(),this.identityPurgeRequests-=1)}}},Of=e=>{const t=new URL(e);if("ws:"!==t.protocol&&"wss:"!==t.protocol)throw new Error("Signaling server URL must use ws: or wss:");return t},Nf=e=>Of(e).toString(),Bf=(t,n,r,o)=>{if(1!==t.readyState||!o())return{error:"WebSocket is not open"};const{keyPair:a,signalingServer:i}=r.getState();if(!((t,n)=>n.isConnected&&n.isVerified&&e.isUUID(t.peerId)&&/^[0-9a-f]{64}$/u.test(t.challenge)&&/^[0-9a-f]{128}$/u.test(t.signature))(a,i))return{error:"WebSocket identity is not authenticated"};if(n.content.fromPeerId!==a.peerId)return{error:"Signaling frame identity is stale"};if(!o())return{error:"WebSocket connection was replaced"};try{return t.send(JSON.stringify(n.content)),{data:void 0}}catch(e){return{error:e instanceof Error?e.message:"WebSocket rejected the signaling frame"}}},Ff=(e,t)=>{if(!Number.isFinite(e)||e<=0)throw new Error(`Signaling heartbeat ${t} must be a positive duration`)};let jf=null,zf=null,$f=null;const Hf=()=>{$f?.stop(),$f=null},Vf=()=>{if("undefined"==typeof window||"undefined"==typeof document)return;const e=e=>"visibilitychange"===e?document:window;return{addListener:(t,n)=>e(t).addEventListener(t,n),removeListener:(t,n)=>e(t).removeEventListener(t,n),isVisible:()=>"visible"===document.visibilityState}},Wf=(e,t)=>{const n=jf,r=zf;return jf=null,zf=null,Hf(),qf.cancelActive(),n&&(r?.invalidate(),Tf(n,"socket-closed"),n.onmessage=null,n.onopen=null,n.onclose=null,n.onerror=null,n.close(),It("WebSocket manually disconnected")),t.dispatch(wt.disconnect()),{data:void 0}},Qf=(e,t)=>{const n=jf,r=zf;return n&&r?Bf(n,e,t,()=>jf===n&&zf===r&&r.isCurrent(()=>!0)):{error:"WebSocket is not open"}},Gf=(t,n)=>{const r=jf,o=zf;return r&&o?((t,{peerId:n,peerPublicKey:r,roomId:o},a,i)=>{if(!e.isUUID(n,4))return{error:"Peer connection target must be a UUIDv4"};if(!Bo(r))return{error:"Peer connection target identity is invalid"};const{keyPair:s}=a.getState(),c=Bf(t,{content:{type:"connection",roomId:o,fromPeerId:s.peerId,toPeerId:n,labels:["main"],protocolVersion:4}},a,i);return"error"in c?c:i()?(a.dispatch(Ze({roomId:o,peerId:n,peerPublicKey:r})),a.dispatch(nt({roomId:o,label:"main",peerId:n})),It(`Connected with ${s.peerId} on channel main`),c):{error:"WebSocket connection was replaced during send"}})(r,t,n,()=>Boolean(jf===r&&zf===o&&o.isCurrent(()=>!0))):{error:"WebSocket is not open"}},Xf=to({reducerPath:"signalingServerApi",baseQuery:async({signalingServerUrl:e},t)=>{let n;try{n=Nf(e)}catch(e){return{error:e instanceof Error?e.message:"Invalid signaling URL"}}if(qf.isIdentityPurgeActive())return{error:"Identity purge is in progress"};const{keyPair:r,signalingServer:o}=t.getState();if(jf||o.isConnected||o.isEstablishingConnection&&qf.hasActiveAttempt())return Nf(o.serverUrl)!==n?{error:"A different signaling server is already active"}:(It("WebSocket already connected"),{data:void 0});let a;try{a=qf.begin(n)}catch(e){return{error:e instanceof Error?e.message:"WebSocket connection attempt was rejected"}}t.dispatch(wt.startConnecting(n));const{token:i,cancelled:s}=a,l=s.then(()=>({error:"WebSocket connection attempt was cancelled"}));return await Promise.race([(async()=>{let e=null,o=null;const a=()=>qf.assertCurrent(i);try{o=await qf.acquireBootstrap(i);const l=e=>{const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t};let d=r.publicKey,u=r.secretKey;const h=await ai();a();const f=h?so(new Uint8Array(h.pub)):"",m=h?new Uint8Array(h.secret):void 0,p=m?so(m):"";m?.fill(0);const y=/^[0-9a-f]{128}$/;if(Bo(d)&&y.test(u)){if(!h||f!==d||p!==u){const e=co(u);try{await ii({pub:l(co(d)),secret:l(e)})}finally{e.fill(0)}a()}}else{if(h)d=f,u=p;else{const e=localStorage.getItem("publicKey")??"",t=localStorage.getItem("secretKey")??"";if(Bo(e)&&y.test(t)){d=e,u=t;const n=co(u);try{await ii({pub:l(co(d)),secret:l(n)})}finally{n.fill(0)}a(),await si("random"),a()}else{const e=await To();try{a(),d=so(e.publicKey),u=so(e.secretKey),await ii({pub:l(e.publicKey),secret:l(e.secretKey)}),a(),await si("random"),a()}finally{e.secretKey.fill(0)}}}t.dispatch(c({publicKey:d,secretKey:u}))}Fo(d,"Self Ed25519 identity"),localStorage.removeItem("secretKey");const g=u.length>0?u:r.secretKey,w=d.length>0?d:r.publicKey;if(g.length>0&&w.length>0){const e=await ri();a();const t=null!=e&&await sd(new Uint8Array(e.pub),new Uint8Array(e.crossSig),co(w));if(a(),!t){const e=await Ui();try{a();const t=await id(e.publicKey,co(g));a(),await(s={pub:l(e.publicKey),secret:l(e.secretKey),crossSig:l(t)},Fa("setIdentityX25519",s)),a()}finally{e.secretKey.fill(0)}}}const b=((e,t)=>{const n=Of(e);return n.searchParams.set("publickey",t),n.toString()})(n,d);return a(),o(),o=null,e=new WebSocket(b),jf=e,e.binaryType="arraybuffer",await new Promise((n,r)=>{if(!e)return void r(new Error("WebSocket is null"));const o=e,a=()=>jf===o&&qf.isCurrent(i),s=new Af;zf=s;const c=()=>zf===s&&s.isCurrent(a),l=e=>{s.invalidate(),Tf(o,e),zf===s&&(zf=null)},d=new Ef({onOverflow:()=>{l("ingress-rejected"),a()&&(o.onmessage=null,o.close(1008,"signaling ingress backlog exceeded"))},onTaskError:e=>{console.error("Signaling ingress task failed",e)}});let u=!1;const h=e=>{u||(u=!0,n(e))},f=e=>{u||(u=!0,r(e))};c()&&qf.addCancellationEffect(i,()=>{h({error:"WebSocket connection attempt was cancelled"}),jf===o&&(Hf(),l("socket-replaced"),d.close(),o.onmessage=null,o.onopen=null,o.onclose=null,o.onerror=null,o.close(),jf=null)});let m=!1;const p=e=>{m||(m=!0,Hf(),l("socket-closed"),d.close(),o.onmessage=null,o.onopen=null,o.onclose=null,o.onerror=null,e&&o.close(e.code,e.reason),jf=null,qf.clear(i),t.dispatch(wt.disconnect()),h({data:void 0}))};let y=null;const g=()=>y?.beat();try{o.onopen=()=>{if(!c())return;It("WebSocket connected to:",b);const e=(e=>{const{now:t,timeoutMs:n,checkEveryMs:r,schedule:o,env:a,onDead:i}=e;Ff(n,"timeout"),Ff(r,"check interval");let s=t(),c=!1,l=null;const d=()=>{if(!c){c=!0,null!==l&&(o.clearInterval(l),l=null);for(const[e,t]of f)a?.removeListener(e,t)}},u=()=>{c||t()-s<=n||(d(),i())},h=()=>u(),f=a?[["visibilitychange",()=>{a?.isVisible()&&u()}],["pageshow",h],["online",h],["focus",h]]:[];for(const[e,t]of f)a?.addListener(e,t);return l=o.setInterval(u,r),{beat:()=>{c||(s=t())},check:u,stop:d}})({now:()=>Date.now(),timeoutMs:25e3,checkEveryMs:5e3,schedule:{setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},env:Vf(),onDead:()=>{a()&&(console.warn("p2party: no signaling heartbeat for 25000 ms; marking the socket disconnected"),p({code:4e3,reason:"signaling heartbeat lost"}))}});y=e,$f=e,t.dispatch(wt.connectionEstablished()),qf.disarmCancellation(i),h({data:void 0})},o.onerror=e=>{a()&&(console.error("WebSocket error:",e),Hf(),l("socket-closed"),d.close(),o.onmessage=null,o.onopen=null,o.onclose=null,o.onerror=null,o.close(),jf=null,qf.clear(i),t.dispatch(wt.disconnect()),f(new Error("WebSocket connection failed")))},o.onmessage=e=>{if(!c())return;const n="string"==typeof e.data?e.data.length:e.data instanceof ArrayBuffer?e.data.byteLength:e.data instanceof Blob?e.data.size:524289;if(n>xe)return l("ingress-rejected"),d.close(),o.onmessage=null,void o.close(1009,"signaling frame too large");const r=(e=>{if("string"!=typeof e||0===e.length||e.length>256)return null;for(const t of["type","protocolVersion","roomUrl","roomLeaveId"])if(1!==(e.match(new RegExp(`"${t}"\\s*:`,"g"))??[]).length)return null;try{const t=JSON.parse(e);return _f(t)?t:null}catch{return null}})(e.data);if(r)Df(r,o)||console.error("Rejecting unsolicited or stale room leave acknowledgement");else{try{if(((e,t)=>{const n=Cf(e);return null!==n&&(t[n](),!0)})(e.data,{raw:()=>o.send("PONG"),json:()=>{const{keyPair:e}=t.getState(),n=Bf(o,{content:{type:"pong",fromPeerId:e.peerId}},t,c);if("error"in n)throw new Error(n.error)}}))return void g()}catch(e){return console.error("Could not answer signaling heartbeat",e),l("ingress-rejected"),d.close(),o.onmessage=null,void o.close(1011,"signaling heartbeat failed")}d.enqueue(async()=>await Lf(e,o,t,c,g),n)}},o.onclose=()=>{a()&&(p(),It("WebSocket disconnected"))}}catch(e){qf.disarmCancellation(i),f(e instanceof Error?e:new Error(String(e)))}return()=>{a()&&(It("Cleaning up WebSocket connection..."),qf.cancelActive(),Hf(),l("socket-closed"),d.close(),o.onmessage=null,o.onopen=null,o.onclose=null,o.onerror=null,o.close(),jf=null)}})}catch(n){o?.();const r=qf.isCurrent(i);return r&&e&&jf===e&&(Hf(),zf?.invalidate(),zf=null,Tf(e,"socket-closed"),e.onmessage=null,e.onopen=null,e.onclose=null,e.onerror=null,e.close(),jf=null),r&&(qf.clear(i),t.dispatch(wt.disconnect())),n instanceof Error&&"WebSocket connection attempt was cancelled"===n.message||console.error("Error during WebSocket setup:",n),{error:"WebSocket connection failed"}}var s})(),l])},endpoints:e=>({connectWebSocket:e.mutation({query:e=>({signalingServerUrl:e})}),disconnectWebSocket:e.mutation({queryFn:Wf}),sendMessage:e.mutation({queryFn:Qf}),connectWithPeer:e.mutation({queryFn:Gf})})}),Jf=async(e,t)=>{await e.dispatch(Xf.endpoints.sendMessage.initiate({content:t})).unwrap()},Yf=e=>{const{schedule:t,delaysMs:n,maxAttempts:r}=e;if(0===n.length)throw new Error("roomRosterReconciler: needs at least one backoff delay");for(const e of n)if(!Number.isFinite(e)||e<=0)throw new Error("roomRosterReconciler: every backoff delay must be a positive duration");if(!Number.isInteger(r)||r<=0)throw new Error("roomRosterReconciler: needs a positive attempt cap");const o=new Map,a=e=>{const n=o.get(e);n&&(null!==n.timer&&t.clearTimeout(n.timer),o.delete(e))},i=(e,s)=>{var c;s.timer=t.setTimeout(()=>{const t=o.get(e);if(!t||t.timer!==s.timer)return;let n;t.timer=null;try{n=t.tick(e)}catch(t){return console.error("p2party: room roster reconciliation failed",t),void a(e)}const c=o.get(e);c&&c===t&&null===c.timer&&(n?(c.attempts+=1,c.attempts>=r||i(e,c)):a(e))},(c=s.attempts,n[Math.min(c,n.length-1)]))};return{arm:(e,t)=>{const n=o.get(e);if(n)return void(n.tick=t);const r={attempts:0,tick:t,timer:null};o.set(e,r),i(e,r)},cancel:a,cancelAll:()=>{for(const e of[...o.keys()])a(e)},armedRooms:()=>[...o.keys()]}},Zf=(t,n)=>{if(!n.isConnected||!n.isVerified)return!1;if(!1===t.signalingActive)return!1;if(!e.isUUID(t.id))return!1;if(0===t.peers.length)return!0;const r=t.handshakeStatusByPeer??{};return!t.peers.some(e=>"authenticated"===r[e.peerId]?.status)},em=((n=(()=>Yf({schedule:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>{clearTimeout(e)}},delaysMs:te,maxAttempts:8}))())=>{const r=t.createListenerMiddleware();return r.startListening({matcher:t.isAnyOf(Ge,$e,He,ot,lt,Ze,st,tt,ut,ht,wt.startConnecting,wt.connectionEstablished,wt.connectionVerified,wt.disconnect),effect:async(t,r)=>{try{if(wt.startConnecting.match(t)||wt.disconnect.match(t))Sf.resetSocketLifecycle();else if(Ge.match(t)){const{roomId:n,connectingToPeers:o,reason:a}=t.payload;if(It("[roomListenerMiddleware] setConnectingToPeers:",{roomId:n,connectingToPeers:o,reason:a}),o){const{signalingServer:t,keyPair:o,rooms:i}=r.getState(),s=i.findIndex(e=>e.id===n);if(It("[roomListenerMiddleware] setConnectingToPeers check:",{isConnected:t.isConnected,peerId:o.peerId,isPeerIdUUID:e.isUUID(o.peerId),roomIndex:s,roomId:s>-1?i[s].id:"N/A"}),t.isConnected&&t.isVerified&&e.isUUID(o.peerId)&&s>-1&&e.isUUID(i[s].id)){const e=Date.now(),t="redial"===a?"redial":"reconcile"===a?"reconcile":"join";Sf.shouldSend(t,n,"reconcile"===a?4e3:2e3,e)?(It("[roomListenerMiddleware] Sending peers request from setConnectingToPeers"),await r.dispatch(Xf.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:o.peerId,roomId:n,protocolVersion:4}}))):It("[roomListenerMiddleware] Skipping peers request - debounced")}r.dispatch(Ge({roomId:n,connectingToPeers:!1}))}}else if($e.match(t)){const{signalingServer:n,keyPair:o,rooms:a}=r.getState(),{url:i,id:s,onlyConnectWithKnownPeers:c}=t.payload;if(It("[roomListenerMiddleware] setRoom:",{url:i,id:s,onlyConnectWithKnownPeers:c}),64===i.length&&null!=c&&localStorage.setItem(i+"-onlyConnectWithKnownPeers",String(c)),64===i.length&&e.isUUID(s)){It("[roomListenerMiddleware] setRoom processed:",{url:i,id:s,isConnected:n.isConnected,peerId:o.peerId,roomsLen:a.length});const t=a.findIndex(e=>e.id===s);if(-1===t)return;const c=Ie(a[t].policy).slice().buffer;await Ha(i,s,c);const l=await Wa(s),d=l.length;for(let e=0;e<d;e++)r.dispatch(ot({roomId:l[e].roomId,transferId:l[e].transferId,merkleRootHex:l[e].merkleRoot,sha512Hex:l[e].hash,fromPeerId:l[e].fromPeerId,filename:l[e].filename,messageType:l[e].messageType,chunkSize:l[e].savedSize,totalSize:l[e].totalSize,channelLabel:l[e].channelLabel,timestamp:l[e].timestamp}));It("[roomListenerMiddleware] Checking peers request conditions:",{isConnected:n.isConnected,isPeerIdUUID:e.isUUID(o.peerId),peerId:o.peerId,roomIndex:t,roomId:t>-1?a[t].id:"N/A"}),n.isConnected&&n.isVerified&&e.isUUID(o.peerId)&&t>-1&&e.isUUID(a[t].id)&&(It("[roomListenerMiddleware] Sending peers request for room:",a[t].id),await r.dispatch(Xf.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:o.peerId,roomId:a[t].id,protocolVersion:4}})))}}else if(He.match(t)){const{roomUrl:e,roomId:n}=t.payload,o=r.getOriginalState().rooms.find(t=>t.url===e);if(!o||o.id===n)return;const a=r.getState().rooms.find(t=>t.url===e&&t.id===n);if(!a)return;const i=Ie(a.policy);await Ha(e,n,i.slice().buffer);const s=await Wa(n);for(const e of s)r.dispatch(ot({roomId:e.roomId,transferId:e.transferId,merkleRootHex:e.merkleRoot,sha512Hex:e.hash,fromPeerId:e.fromPeerId,filename:e.filename,messageType:e.messageType,chunkSize:e.savedSize,totalSize:e.totalSize,channelLabel:e.channelLabel,timestamp:e.timestamp}))}else if(ot.match(t)){const{roomId:e,merkleRootHex:n,sha512Hex:o,chunkSize:a,totalSize:i}=t.payload,{rooms:s,keyPair:c}=r.getOriginalState(),l=s.findIndex(t=>t.id===e);if(l>-1){const t=s[l].messages.findLastIndex(e=>e.merkleRootHex===n&&e.fromPeerId!==c.peerId&&e.savedSize+a===i);if(t>-1){const n=await ci(s[l].messages[t].channelLabel,s[l].messages[t].merkleRootHex),a=co(o);await r.dispatch(kf.endpoints.disconnectFromChannelLabel.initiate({roomId:e,label:n,messageHash:a,alsoDeleteData:!1,alsoSendFinishedMessage:!0}))}}}else if(lt.match(t)){const{merkleRootHex:e,hashHex:n}=t.payload;if(!e&&!n)return;if(e&&e.length!==2*y)return;if(n&&n.length!==2*y)return;e?(await Ja(e),await Za({merkleRootHex:e})):n&&await Za({hashHex:n})}}catch(e){console.error("p2party: room listener effect failed",e)}finally{try{((t,n)=>{const{rooms:r,signalingServer:o,keyPair:a}=n.getState(),i=new Set;if(e.isUUID(a.peerId))for(const a of r)Zf(a,o)&&(i.add(a.id),t.arm(a.id,t=>{const r=n.getState(),o=r.rooms.find(e=>e.id===t);return!!(o&&e.isUUID(r.keyPair.peerId)&&Zf(o,r.signalingServer))&&(n.dispatch(Ge({roomId:t,connectingToPeers:!0,reason:"reconcile"})),!0)}));for(const e of t.armedRooms())i.has(e)||t.cancel(e)})(n,r)}catch(e){console.error("p2party: room roster reconciliation failed",e)}}}}),r})(),tm=t.createListenerMiddleware();tm.startListening({matcher:t.isAnyOf(c,d,u,h,wt.disconnect),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(d.match(t)){const{peerId:n,challenge:r,signature:o}=t.payload;e.isUUID(n)&&e.isHexadecimal(r)&&e.isHexadecimal(o)&&64===r.length&&128===o.length&&(localStorage.setItem("peerId",n),localStorage.setItem("challenge",r),localStorage.setItem("signature",o))}else if(u.match(t)){const{challengeId:r}=t.payload;e.isUUID(r)&&(n.dispatch(wt.connectionVerified()),((e=ia)=>{if(e!==ia)return;const t=ta;t&&t.lifecycleEpoch===e&&(ta=null,clearTimeout(t.timeout),t.resolve())})(),localStorage.setItem("challengeId",r),await(async()=>{try{await va(n,e=>Jf(n,e))}catch(e){console.warn("p2party: failed to refresh one or more active rooms",e instanceof Error?e.message:String(e))}})())}else h.match(t)?(ga("identity reset"),console.trace("[keyPairListenerMiddleware] resetIdentity dispatched"),localStorage.setItem("peerId",""),localStorage.setItem("challengeId",""),localStorage.setItem("publicKey",""),localStorage.removeItem("secretKey"),localStorage.setItem("challenge",""),localStorage.setItem("signature","")):wt.disconnect.match(t)&&ga()}});const nm=t.configureStore({reducer:{commonState:a,keyPair:m,rooms:mt,signalingServer:bt,[Xf.reducerPath]:Xf.reducer,[kf.reducerPath]:kf.reducer},middleware:e=>e({serializableCheck:{ignoredPaths:[`${kf.reducerPath}.mutations`,`${kf.reducerPath}.queries`,`${Xf.reducerPath}.mutations`,`${Xf.reducerPath}.queries`],ignoredActionPaths:["payload","error","meta.arg.originalArgs","meta.baseQueryMeta"]}}).concat([Xf.middleware,kf.middleware,em.middleware,tm.middleware])}),rm=nm.dispatch,om=new Uint8Array([80,50,80,83,69,83,83,0]),am=262144,im=om.length+4+24+32+32+32+2,sm="p2party-session",cm=e=>Uint8Array.from(e);function lm(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 dm=(e,t)=>{if(!Number.isSafeInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new RangeError(`${t} must be a non-negative safe integer`)},um=(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},hm=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),fm=async e=>new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",e.slice().buffer)),mm=async e=>{const t=new WebAssembly.Memory({initial:32,maximum:32});return e?.wasmBinary?await Co({wasmBinary:(n=e.wasmBinary,n instanceof Uint8Array?n.slice().buffer:n.slice(0)),wasmMemory:t,getRandomValue:Eo}):await _o(t);var n},pm=async(e,t)=>{const n=((e,t)=>_i(e,xi,t))(e.x25519SecretKey,t);try{if(!um(n,e.x25519PublicKey))throw new Error("identity X25519 public and secret keys do not match")}finally{n.fill(0)}if(!await sd(e.x25519PublicKey,e.x25519CrossSignature,e.ed25519PublicKey,t))throw new Error("identity X25519 cross-signature is invalid")},ym=async(e={})=>{const t=await mm(e);let n=null,r=null,o=null;try{if(e.ed25519KeyPair)lm(e.ed25519KeyPair.publicKey,"ed25519KeyPair.publicKey",v),lm(e.ed25519KeyPair.secretKey,"ed25519KeyPair.secretKey",k),n=cm(e.ed25519KeyPair.publicKey),r=cm(e.ed25519KeyPair.secretKey);else{const e=await To(t);n=e.publicKey,r=e.secretKey}const a=await Ui(t);o=a.secretKey;const i=await id(a.publicKey,r,t);if(!await sd(a.publicKey,i,n,t))throw new Error("ed25519KeyPair public and secret keys do not match");const s={ed25519PublicKey:n,ed25519SecretKey:r,x25519PublicKey:a.publicKey,x25519SecretKey:o,x25519CrossSignature:i};return n=null,r=null,o=null,s}finally{n?.fill(0),r?.fill(0),o?.fill(0)}},gm=(e,t)=>e.N===t.N&&e.PN===t.PN&&um(e.dhPub,t.dhPub);class wm{protocolVersion=4;#e;#Ke=new rh;#Ue;#_e;#De;#g=!1;constructor(e,t,n,r){this.#_e=e,this.#e=t,this.#De=n,this.#Ue=r}get pqMode(){return oe(this.#_e.rootSuite)}get canEncrypt(){return!this.#g&&null!==this.#_e.sendingChainKey&&!this.#De.trafficBlocked}get pqEpoch(){return this.#V(),this.#De.epoch}get healingInProgress(){return!this.#g&&this.#De.trafficBlocked}#V(){if(this.#g)throw new Error("session: session is destroyed")}async encrypt(e){lm(e,"plaintext");const t=cm(e);return this.#Ke.runExclusive(async()=>{let e=null,n=null,r=null,o=null,a=!1;try{if(this.#V(),this.#De.trafficBlocked)throw new Error("session: sparse-PQ healing is in progress");if(!this.#_e.sendingChainKey)throw new Error("ratchet: no sending chain");e=await(async(e,t)=>{const n=e.length,r=Math.max(1,Math.ceil(n/q)),o=[],a=[];try{for(let t=0;t<r;t++){const r=t*q,a=Math.min(q,Math.max(0,n-r)),i=globalThis.crypto.getRandomValues(new Uint8Array(q));i.set(e.subarray(r,r+a),0),o.push(i)}const i=await fm(e),s=new Uint8Array(r*y);for(let e=0;e<o.length;e++)s.set(qh(o[e],t),e*y);const c=Uint8Array.from(await Nh(s,t));for(let e=0;e<o.length;e++){const r=await Bh(s,qh(o[e],t),t,L),c=Math.min(q,Math.max(0,n-e*q)),l=vi({schemaVersion:1,messageType:Ii.Unknown,hash:i,totalSize:n,date:new Date(0),name:sm,chunkStartIndex:0,chunkEndIndex:c,chunkIndex:e}),d=new Uint8Array(N);d.set(l,0),d.set(r,T),d.set(o[e],T+L),a.push(d)}return i.fill(0),s.fill(0),{root:c,chunks:o,plaintexts:a}}catch(e){for(const e of o)e.fill(0);for(const e of a)e.fill(0);throw e}})(t,this.#e),n=Yi(this.#_e);const i=$i(n,this.#e);r=i.messageKey,o=this.#De.currentMessageContext();const s=e.plaintexts.map(t=>vs(r,i.header,t,e.root,this.#e,o));return es(this.#_e,n),this.#De.noteApplicationMessage(),a=!0,{protocolVersion:4,root:cm(e.root),frames:s}}finally{t.fill(0),r?.fill(0),n&&!a&&Zi(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(lm(e.root,"message.root",y),!Array.isArray(e.frames)||0===e.frames.length)throw new Error("session: encrypted message has no frames");for(const t of e.frames)if(lm(t,"message frame"),t.length!==H)throw new Error("session: invalid encrypted frame length");const t=cm(e.root),n=e.frames.map(cm);return this.#Ke.runExclusive(async()=>{this.#V();const e=n.map(e=>as(e));for(let t=1;t<e.length;t++)if(!gm(e[0].header,e[t].header))throw new Error("session: mixed ratchet headers");const r=new Set;for(const t of e){const e=hm(t.nonce);if(r.has(e))throw new Error("session: duplicate chunk nonce");r.add(e)}const o=Yi(this.#_e),a=new Map(this.#De.activeReceiveKeys),i=[];let s=!1;try{const e=[];for(const r of n){const n=ks(o,r,a,t,this.#e,e=>this.#De.resolveMessageContext(e));if(!n.ok||!n.decrypted)throw new Error("session: encrypted frame authentication failed");i.push(n.decrypted);const s=ki(n.decrypted.subarray(0,T));e.push({metadata:s,chunk:n.decrypted.subarray(T+L)})}const r=await(async e=>{if(0===e.length)throw new Error("session: encrypted message has no frames");const t=e[0].metadata;dm(t.totalSize,"metadata.totalSize");const n=Math.max(1,Math.ceil(t.totalSize/q));if(e.length!==n)throw new Error("session: incomplete or excessive frame set");const r=new Map;for(const o of e){const e=o.metadata;if(dm(e.chunkIndex,"metadata.chunkIndex"),dm(e.chunkStartIndex,"metadata.chunkStartIndex"),dm(e.chunkEndIndex,"metadata.chunkEndIndex"),dm(e.totalSize,"metadata.totalSize"),1!==e.schemaVersion||e.messageType!==Ii.Unknown||e.name!==sm||0!==e.date.getTime())throw new Error("session: unsupported encrypted metadata");if(e.totalSize!==t.totalSize||!um(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 a=Math.min(q,Math.max(0,t.totalSize-e.chunkIndex*q));if(e.chunkEndIndex!==a)throw new Error("session: invalid encrypted chunk length");if(r.has(e.chunkIndex))throw new Error("session: duplicate encrypted chunk");r.set(e.chunkIndex,o)}const o=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;o.set(t.chunk.subarray(0,n),e*q)}const a=await fm(o),i=um(a,t.hash);if(a.fill(0),!i)throw o.fill(0),new Error("session: plaintext hash mismatch");return o})(e);return es(this.#_e,o),this.#Te(a),this.#De.noteApplicationMessage(),s=!0,r}finally{t.fill(0);for(const e of i)e.fill(0);if(!s){for(const[e,t]of a)this.#De.activeReceiveKeys.has(e)||t.fill(0);Zi(o)}}})}#Te(e){const t=this.#De.activeReceiveKeys;for(const[n,r]of e)t.has(n)||t.set(n,r)}async prepareHealing(){return this.#Ke.runExclusive(async()=>{if(this.#V(),!this.#De.healingDue())return bm;const e=await this.#De.prepareHealingOffer();return this.#De.markPendingDispatched(),{frame:e,requiresPersistBeforeSend:!0}})}async acceptControlFrame(e){lm(e,"control frame",H);const t=cm(e);return this.#Ke.runExclusive(async()=>{this.#V();const e=await this.#De.acceptControlFrame(t);return e.changed&&e.dispatch&&null!==this.#De.pendingRetryAt&&this.#De.markPendingDispatched(),{frame:e.dispatch,requiresPersistBeforeSend:e.changed}})}async pendingControl(){return this.#Ke.runExclusive(async()=>(this.#V(),this.#De.copyPendingFrame()))}async serialize(){return this.#Ke.runExclusive(async()=>(this.#V(),km(this.#_e,this.#De,this.#Ue)))}async destroy(){await this.#Ke.runExclusive(async()=>{this.#g||(Zi(this.#_e),this.#De.destroy(),this.#g=!0)})}}const bm={frame:null,requiresPersistBeforeSend:!1},vm=(e,t,n)=>(dm(n,"snapshot counter"),e.setBigUint64(t,BigInt(n),!1),t+8),km=(e,t,n)=>{(e=>{if(lm(e.rootKey,"snapshot.rootKey",32),lm(e.dhSelfPub,"snapshot.dhSelfPub",32),lm(e.dhSelfSec,"snapshot.dhSelfSec",32),e.sendingChainKey&&lm(e.sendingChainKey,"snapshot.sendingChainKey",32),e.receivingChainKey&&lm(e.receivingChainKey,"snapshot.receivingChainKey",32),e.dhRemotePub&&lm(e.dhRemotePub,"snapshot.dhRemotePub",32),dm(e.Ns,"snapshot.Ns"),dm(e.Nr,"snapshot.Nr"),dm(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>Y)throw new Error("snapshot: too many skipped message keys")})(e);const r=Xi(e),o=t.serialize();if(0===o.length||o.length>am)throw o.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)),a=new Uint8Array(im+32*t+72*r.skippedMessageKeys.length+4+o.length),i=new DataView(a.buffer);let s=0;a.set(om,s),s+=om.length,a[s++]=4,a[s++]=4,a[s++]=e,a[s++]=(e=>{if(e===Q)return 3;if(e===W)return 4;if(e===G)return 5;throw new Error("snapshot: unsupported root suite")})(r.rootSuite),s=vm(i,s,r.Ns),s=vm(i,s,r.Nr),s=vm(i,s,r.PN),a.set(new Uint8Array(r.rootKey),s),s+=32,r.sendingChainKey&&(a.set(new Uint8Array(r.sendingChainKey),s),s+=32),r.receivingChainKey&&(a.set(new Uint8Array(r.receivingChainKey),s),s+=32),a.set(new Uint8Array(r.dhSelfPub),s),s+=32,a.set(new Uint8Array(r.dhSelfSec),s),s+=32,r.dhRemotePub&&(a.set(new Uint8Array(r.dhRemotePub),s),s+=32),i.setUint16(s,r.skippedMessageKeys.length,!1),s+=2;for(const e of r.skippedMessageKeys)lm(new Uint8Array(e.dhPub),"snapshot.skipped.dhPub",32),lm(new Uint8Array(e.messageKey),"snapshot.skipped.messageKey",32),a.set(new Uint8Array(e.dhPub),s),s+=32,s=vm(i,s,e.n),a.set(new Uint8Array(e.messageKey),s),s+=32;return i.setUint32(s,o.length,!1),s+=4,a.set(o,s),s+=o.length,a}finally{o.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)}},Im=e=>{lm(e,"snapshot");const t=cm(e);let n=0,r=!1;const o=[],a=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=a(e).slice().buffer;return t&&o.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(!um(a(om.length),om))throw new Error("snapshot: invalid magic");if(4!==a(1)[0])throw new Error("snapshot: unsupported snapshot version");if(4!==a(1)[0])throw new Error("snapshot: unsupported protocol version");const e=a(1)[0];if(-16&e)throw new Error("snapshot: unknown flags");const c=(e=>{if(3===e)return Q;if(4===e)return W;if(5===e)return G;throw new Error("snapshot: unsupported root suite")})(a(1)[0]),l=s(),d=s(),u=s(),h=i(32,!0),f=1&e?i(32,!0):null,m=2&e?i(32,!0):null,p=i(32),y=i(32,!0),g=4&e?i(32):null;if((f||m)&&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>Y)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=a(32),t=s(),n=a(32),r=`${hm(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 o.push(new Uint8Array(e)),e})()})}const I=new DataView(t.buffer,t.byteOffset+n,4).getUint32(0,!1);if(n+=4,0===I||I>am)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=a(I).slice();o.push(S);const C=Ji({rootSuite:c,rootKey:h,sendingChainKey:f,receivingChainKey:m,dhSelfPub:p,dhSelfSec:y,dhRemotePub:g,Ns:l,Nr:d,PN:u,skippedMessageKeys:v});return r=!0,{state:C,pqCheckpoint:S,amInitiator:!!(8&e)}}finally{if(t.fill(0),!r)for(const e of o)e.fill(0)}},Sm=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");lm(e.ed25519PublicKey,"identity.ed25519PublicKey",v),lm(e.x25519PublicKey,"identity.x25519PublicKey",R),lm(e.x25519SecretKey,"identity.x25519SecretKey",M),lm(e.x25519CrossSignature,"identity.x25519CrossSignature",w)})(e.identity),lm(e.peerIdentityEd25519PublicKey,"peerIdentityEd25519PublicKey",v),!e.channel||"object"!=typeof e.channel)throw new TypeError("channel binding is required");if(lm(e.channel.channelId,"channel.channelId"),0===e.channel.channelId.length)throw new RangeError("channel.channelId must not be empty");lm(e.channel.localFingerprint,"channel.localFingerprint",32),lm(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 o=null;if("pin"===n){if(lm(t.pin,"pin"),0===t.pin.length)throw new RangeError("pin must not be empty");o=cm(t.pin)}else if(void 0!==t.pin)throw new Error("pin must not be provided in nopin mode");const a=cm(e.identity.x25519SecretKey),i=cm(e.identity.ed25519PublicKey),s=cm(e.identity.x25519PublicKey),c=cm(e.identity.x25519CrossSignature),l=cm(e.peerIdentityEd25519PublicKey),d=cm(e.channel.channelId),u=cm(e.channel.localFingerprint),h=cm(e.channel.remoteFingerprint);let f=null,m=null,p=null,y=null,g=null;try{const t=await mm(e.crypto);await pm({ed25519PublicKey:i,x25519PublicKey:s,x25519SecretKey:a,x25519CrossSignature:c},t);const w="initiator"===e.role,b=fd({channelId:d,ikInitiator:w?i:l,ikResponder:w?l:i,fpInitiator:w?u:h,fpResponder:w?h:u,pqMode:r}),v=await xd(e.transport,{mode:n,pqMode:r,pin:o,channelInput:b,amInitiator:w,idSelfSec:a,selfIdentityX25519Pub:s,selfIdentityCrossSignature:c,peerIdentityEd25519Pub:l},t);y=v.state,f=v.secret,m=v.pqHealing.rootKey,p=v.pqHealing.binding,g=new Hl({module:t,pqMode:r,rootSuite:y.rootSuite,binding:p,rootKey:m,nextOfferer:v.pqHealing.nextOfferer,amInitiator:w});const k=new wm(y,t,g,w);return y=null,g=null,k}finally{a.fill(0),o?.fill(0),f?.fill(0),m?.fill(0),p?.fill(0),y&&Zi(y),g?.destroy()}},Cm=async(e,t)=>{const n=Im(e);let r=null;try{const e=await mm(t),o=Hl.readCheckpointBinding(n.pqCheckpoint);try{r=Hl.restore(n.pqCheckpoint,{module:e,pqMode:oe(n.state.rootSuite),rootSuite:n.state.rootSuite,binding:o,amInitiator:n.amInitiator})}finally{o.fill(0)}const a=new wm(n.state,e,r,n.amInitiator);return r=null,a}catch(e){throw Zi(n.state),r?.destroy(),e}finally{n.pqCheckpoint.fill(0)}};var Am=["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 Em=new Map(Am.map((e,t)=>[e,t])),Pm=e=>e.normalize("NFKD"),xm=e=>Pm(e).replace(/\s+/g," ").trim().toLowerCase(),Rm=async e=>{const t=globalThis.crypto?.subtle;if("function"!=typeof t?.digest)throw new Error("Web Crypto SHA-512 is unavailable");return new Uint8Array(await t.digest("SHA-512",e.slice()))},Mm=e=>e.reduce((e,t)=>e+t.toString(2).padStart(8,"0"),""),Km=e=>{const t=new Uint8Array(e);return Po(t),t},Um=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=Km(e/8),n=Mm(t),r=e/32,o=await Rm(t),a=(n+Mm(o).slice(0,r)).match(/(.{1,11})/g).map(e=>{const t=parseInt(e,2);return Am[t]});return t.fill(0),o.fill(0),a.join(" ")},_m=async e=>{const t=xm(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=Em.get(e);if(void 0===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),o=n.slice(0,r),a=n.slice(r),i=o.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 Rm(c),d=Mm(l).slice(0,s);if(c.fill(0),l.fill(0),d!==a)throw new Error("Invalid checksum.");return!0},Dm=async e=>{try{return await _m(e)}catch{return!1}},Tm=e=>{const t=xm(e);if(0===t.length)return{ok:!1,reason:"The recovery phrase is empty."};const n=t.split(" ");if(n.length<12||n.length>48)return{ok:!1,reason:`A recovery phrase has between ${String(12)} and ${String(48)} words, not ${String(n.length)}.`};if(n.length%3!=0)return{ok:!1,reason:`The number of words must be a multiple of three, not ${String(n.length)}.`};for(let e=0;e<n.length;e++)if(!Em.has(n[e]))return{ok:!1,reason:`Word ${String(e+1)}, "${n[e]}", is not in the wordlist.`};return{ok:!0}},Lm=async(e,t,n)=>{const r=xm(e);if(!await Dm(r))throw new Error("Invalid mnemonic.");const o=new TextEncoder,a=new Uint8Array(A);if(t){const e=o.encode(t);let n;try{n=await Rm(e),a.set(n.subarray(y-A,y))}finally{e.fill(0),n?.fill(0)}}else o.encodeInto("password12345678",a);const i=await(async(e,t,n)=>{const r=Pm(e),o=(new TextEncoder).encode(r).buffer,a=new Int8Array(o),i=a.length;t=t??Km(A);const s=n?.wasmMemory??bo(i),c=(n=n??await _o(s))._malloc(b),l=new Uint8Array(s.buffer,c,b),d=n._malloc(i*Uint8Array.BYTES_PER_ELEMENT),u=new Int8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT),h=n._malloc(A),f=new Uint8Array(s.buffer,h,A);try{if(Po(l),u.set(a),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{Do(n,l),Do(n,new Uint8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT)),n._free(h),a.fill(0)}})(r,a,n);try{return await Lo(i,n)}finally{i.fill(0),a.fill(0)}},qm=32,Om=`v${String(1)}.`,Nm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Bm=/^[0-9a-fA-F]{64}$/u,Fm=/^[A-Za-z0-9_-]{43}$/u,jm=(new TextEncoder).encode("p2party/room-invite/checksum/v1\0");if(2048!==Am.length||2048!==new Set(Am).size)throw new Error("Room invite word list must contain 2,048 unique words");const zm=new Map(Am.map((e,t)=>[e,t])),$m=e=>{if(!(e instanceof Uint8Array))throw new TypeError("Room capability must be a Uint8Array");if(e.length!==qm)throw new Error("Room capability must be exactly 32 bytes");return e},Hm=()=>globalThis.crypto.getRandomValues(new Uint8Array(qm)),Vm=e=>{const t=$m(e);let n="";for(let e=0;e<t.length;e+=3){const r=t.length-e,o=t[e]<<16|(r>1?t[e+1]:0)<<8|(r>2?t[e+2]:0);n+=Nm[o>>>18&63],n+=Nm[o>>>12&63],r>1&&(n+=Nm[o>>>6&63]),r>2&&(n+=Nm[63&o])}return n},Wm=e=>{if("string"!=typeof e||!Fm.test(e))throw new Error("Room capability must be exactly 43 unpadded base64url characters");if(3&Nm.indexOf(e.at(-1)??""))throw new Error("Room capability base64url encoding is not canonical");const t=new Uint8Array(qm);let n=0,r=0,o=0;for(const a of e)for(n=n<<6|Nm.indexOf(a),r+=6;r>=8;)r-=8,t[o]=n>>>r&255,o+=1,n&=(1<<r)-1;if(o!==qm||Vm(t)!==e)throw new Error("Room capability base64url encoding is not canonical");return t},Qm=e=>{if("string"!=typeof e)throw new TypeError("Room capability must be a string");return e.startsWith(Om)||e.startsWith(`#${Om}`)?Jm(e):64===e.length?(e=>{if(!Bm.test(e))throw new Error("Room capability hex must contain exactly 64 hex digits");const t=new Uint8Array(qm);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(2*n,2*n+2),16);return t})(e):Wm(e)},Gm=e=>(e=>{let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t})(Qm(e)),Xm=e=>`${Om}${Vm(e)}`,Jm=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(Om))throw new Error("Unsupported room invite version");return Wm(t.slice(Om.length))},Ym=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})(jm,e));return new Uint8Array(t)[0]};const Zm=new class{#Ke=new rh;runJoin(e){return this.#Ke.runExclusive(e)}runRoomTerminal(e,t){return this.#Ke.runExclusive(t)}runGlobalTerminal(e){return this.#Ke.runExclusive(e)}},ep=async(e,t)=>{const n=[];for(const e of t)try{await e()}catch(e){n.push(e)}if(n.length>0)throw new AggregateError(n,e)};class tp extends Error{constructor(e){super(e),this.name="InvalidRecoveryPhraseError"}}const np=async(e,t,n)=>{const r=await(async e=>{const t=Tm(e);if(!t.ok)return t;try{return await _m(e),{ok:!0}}catch(e){return{ok:!1,reason:e instanceof Error?e.message:"The recovery phrase is invalid."}}})(t);if(!r.ok)throw new tp(r.reason??"The recovery phrase is invalid.");const o=await e.deriveIdentity(t,n);try{return await e.runExclusive(async()=>{await ep("Identity restore could not reach a terminal boundary",[e.disconnectSignaling,e.teardownRooms,e.deleteIdentityX25519]),await e.writeIdentityEd25519(o),await e.recordDerivation();const t=so(o.publicKey),n=so(o.secretKey);return await e.resetIdentityState(),e.adoptIdentity(t,n),{publicKey:t}})}finally{o.secretKey.fill(0)}},rp=e=>{const{rooms:t,signalingServer:n}=nm.getState(),r=t.some(e=>!1!==e.signalingActive);return(({requestedServerUrl:e,currentServerUrl:t,hasActiveRooms:n,isConnected:r,isEstablishingConnection:o})=>{const a=Nf(e);if((n||r||o)&&Nf(t)!==a)throw new Error("Cannot join a room through a different active signaling server");return a})({requestedServerUrl:e,currentServerUrl:n.serverUrl,hasActiveRooms:r,isConnected:n.isConnected,isEstablishingConnection:n.isEstablishingConnection})},op=(t,n)=>{const{keyPair:r,signalingServer:o}=nm.getState(),a=o.isConnected||o.isEstablishingConnection;var i;o.isConnected&&o.isVerified&&e.isUUID(r.peerId,4)?ba(nm,t,e=>Jf(nm,e)).catch(e=>{console.warn("p2party: background room join failed",e instanceof Error?e.message:String(e))}):a||(i=n,rm(wt.startConnecting(i)),rm(Xf.endpoints.connectWebSocket.initiate(i)).unwrap().catch(e=>{const t=nm.getState().signalingServer;t.isEstablishingConnection&&Nf(t.serverUrl)===i&&rm(wt.disconnect()),console.warn("p2party: signaling connection attempt failed",e instanceof Error?e.message:String(e))}))},ap=async(t,n="wss://signaling.p2party.com/ws",r,a={})=>{if(t=Gm(t),null===a||"object"!=typeof a||Array.isArray(a))throw new Error("Invalid room connection options");await Zm.runJoin(async()=>{const{rooms:i}=nm.getState(),s=i.findIndex(e=>e.url===t);let c;if(-1===s){const e=(await $a()).find(e=>e.roomUrl===t);e?.roomPolicy&&(c=Se(new Uint8Array(e.roomPolicy)))}const l=(({existingPolicy:e,persistedPolicy:t,requestedPolicy:n,providedPin:r,hasTransientPin:o})=>{if(t&&n&&!Ae(t,n))throw new Error("Persisted room policy is immutable");const a=Ce(n??e??t??Pe);if("legacy-signaling"!==a.rendezvousMode)throw new Error("Private rendezvous room connections are not wired yet");if("pin"===a.authMode){if(void 0!==r){if(!(r instanceof Uint8Array)||0===r.length)throw new Error("roomPinVault: PIN must be a non-empty Uint8Array")}else if(!o)throw new Error("PIN room connection requires a PIN")}else if(void 0!==r)throw new Error("PIN must not be provided for a no-PIN room");return a})({existingPolicy:s>-1?i[s].policy:void 0,persistedPolicy:c,requestedPolicy:a.policy,providedPin:a.pin,hasTransientPin:(d=t,qu.has(d))});var d;const u=rp(n);if("pin"===l.authMode&&void 0!==a.pin){const e=nm.getState().rooms.find(e=>e.url===t)?.id??"";e&&await Vu(e)}await(async(t,n={})=>{await fh(t).runExclusive(async()=>{const r=nm.getState().rooms,o=r.find(e=>e.url===t);if((!o||!1===o.signalingActive)&&r.filter(e=>!1!==e.signalingActive).length>=K)throw new Error(`Cannot activate more than ${String(K)} rooms`);const a=void 0!==o&&void 0!==n.rtcConfig&&!Te(o.callerRtcConfig,n.rtcConfig),i=o?.rtcConfig,s=a&&o&&n.rtcConfig?qe(n.rtcConfig,o.signalingTurnCredentials):void 0,c=a&&void 0!==o&&e.isUUID(o.id,4)&&void 0!==s;c&&await rm(kf.endpoints.applyRoomConfiguration.initiate({roomId:o.id,rtcConfig:s,restartIce:!0,failurePolicy:"rollback"})).unwrap();try{if(rm($e({...n,url:t,id:o?.id??""})),a&&n.rtcConfig){const e=nm.getState().rooms.find(e=>e.url===t);if(!e||!Te(e.callerRtcConfig,n.rtcConfig)||void 0!==s&&!Te(e.rtcConfig,s))throw new Error("Caller RTC configuration publication was rejected")}}catch(e){throw c&&o&&i&&await rm(kf.endpoints.applyRoomConfiguration.initiate({roomId:o.id,rtcConfig:i,restartIce:!0,failurePolicy:"close"})).unwrap(),e}})})(t,{rtcConfig:r,policy:l});const h=Nu(t);let f=!1;try{"pin"===l.authMode&&void 0!==a.pin?(Ou(t,a.pin),f=!0):"nopin"===l.authMode&&(Bu(t),f=!0),((e,t)=>{nm.getState().commonState.currentRoomUrl!==e&&rm(o(e)),op(e,t)})(t,u)}catch(e){throw f&&(h?Ou(t,h):Bu(t)),e}finally{h?.fill(0)}})},ip=3e4,sp=async(e,t={})=>{const n=Gm(e),{timeoutMs:r=ip,signal:o}=t,a=()=>{const e=ft(nm.getState()).find(e=>e.url===n);return e?.id?e:void 0},i=a();if(i)return i;if(o?.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),o?.removeEventListener("abort",c),i(),e())}const d=()=>{const t=a();t&&l(()=>{e(t)})};o?.addEventListener("abort",c,{once:!0}),i=nm.subscribe(d),d()})},cp=async(e,t,n,r={})=>{const{timeoutMs:o,signal:a,...i}=r;return await ap(e,t,n,i),await sp(e,{timeoutMs:o,signal:a})},lp=async(e,t={})=>{const{count:n=1,timeoutMs:r=ip,signal:o}=t,a=()=>{const t=ft(nm.getState()).find(t=>t.id===e);if(!t)return;const r=t.handshakeStatusByPeer,o=r?t.peers.filter(e=>"authenticated"===r[e.peerId]?.status):t.peers;return o.length>=n?o:void 0},i=a();if(i)return i;if(o?.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(a()?.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),o?.removeEventListener("abort",l),s(),e())}const u=()=>{const t=a();t&&d(()=>{e(t)})};o?.addEventListener("abort",l,{once:!0}),s=nm.subscribe(u),u()})},dp=(e,t)=>{const n=new Set,r=()=>{const r=ft(nm.getState()).find(t=>t.id===e);if(r)for(const o of r.messages){const r=o.merkleRootHex;r&&!n.has(r)&&(o.totalSize>0&&o.savedSize>=o.totalSize&&(n.add(r),up(r,o.sha512Hex).then(n=>{try{t({roomId:e,fromPeerId:o.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)})))}},o=nm.subscribe(r);return r(),o},up=async(e,t,n=!0)=>{if(!e&&!t)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"txt",category:Si.Text};try{const{keyPair:r,rooms:o}=nm.getState(),a=o.length;let i=-1,s=-1;for(let n=0;n<a;n++)if(s=o[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:Si.Text};const c=o[i].messages[s].messageType,l=Ci(c),d=(e=>{switch(e){case Ii.ImagePNG:return"png";case Ii.ImageJPEG:return"jpeg";case Ii.ImageJPG:return"jpg";case Ii.ImageGIF:return"gif";case Ii.ImageBMP:return"bmp";case Ii.ImageTIFF:return"tiff";case Ii.ImageSVG:return"svg";case Ii.ImageWEBP:return"webp";case Ii.ImageHEIC:return"heic";case Ii.DocumentPDF:return"pdf";case Ii.DocumentDOC:return"doc";case Ii.DocumentDOCX:return"docx";case Ii.DocumentXLS:return"xls";case Ii.DocumentXLSX:return"xlsx";case Ii.DocumentPPT:return"ppt";case Ii.DocumentPPTX:return"pptx";case Ii.DocumentTXT:return"txt";case Ii.DocumentRTF:return"rtf";case Ii.DocumentODT:return"odt";case Ii.AudioMP3:return"mp3";case Ii.AudioWAV:return"wav";case Ii.AudioAAC:return"aac";case Ii.AudioFLAC:return"flac";case Ii.AudioOGG:return"ogg";case Ii.AudioM4A:return"m4a";case Ii.VideoMP4:return"mp4";case Ii.VideoAVI:return"avi";case Ii.VideoMKV:return"mkv";case Ii.VideoMOV:return"mov";case Ii.VideoWMV:return"wmv";case Ii.VideoFLV:return"flv";case Ii.VideoWEBM:return"webm";case Ii.CompressedZIP:return"zip";case Ii.CompressedRAR:return"rar";case Ii.Compressed7Z:return"7z";case Ii.CompressedTAR:return"tar";case Ii.CompressedGZ:return"gz";case Ii.CodeHTML:return"html";case Ii.CodeCSS:return"css";case Ii.CodeJS:return"js";case Ii.CodeTS:return"ts";case Ii.CodeJSX:return"jsx";case Ii.CodeTSX:return"tsx";case Ii.CodeJSON:return"json";case Ii.CodeXML:return"xml";case Ii.CodePY:return"py";case Ii.CodeJAVA:return"java";case Ii.CodeC:return"c";case Ii.CodeCPP:return"cpp";case Ii.CodeCS:return"cs";case Ii.CodeRB:return"rb";case Ii.CodePHP:return"php";case Ii.CodeSQL:return"sql";case Ii.EbookEPUB:return"epub";case Ii.EbookMOBI:return"mobi";case Ii.EbookAZW:return"azw";case Ii.FontTTF:return"ttf";case Ii.FontOTF:return"otf";case Ii.ImageICO:return"ico";case Ii.ExecutableEXE:return"exe";case Ii.ExecutableDMG:return"dmg";case Ii.ExecutableAPK:return"apk";default:return""}})(c),u=(e=>{switch(e){case Ii.Text:return Si.Text;case Ii.ImagePNG:case Ii.ImageJPEG:case Ii.ImageJPG:case Ii.ImageGIF:case Ii.ImageBMP:case Ii.ImageTIFF:case Ii.ImageSVG:case Ii.ImageWEBP:case Ii.ImageHEIC:case Ii.ImageICO:return Si.Image;case Ii.DocumentPDF:case Ii.DocumentDOC:case Ii.DocumentDOCX:case Ii.DocumentXLS:case Ii.DocumentXLSX:case Ii.DocumentPPT:case Ii.DocumentPPTX:case Ii.DocumentTXT:case Ii.DocumentRTF:case Ii.DocumentODT:return Si.Document;case Ii.AudioMP3:case Ii.AudioWAV:case Ii.AudioAAC:case Ii.AudioFLAC:case Ii.AudioOGG:case Ii.AudioM4A:return Si.Audio;case Ii.VideoMP4:case Ii.VideoAVI:case Ii.VideoMKV:case Ii.VideoMOV:case Ii.VideoWMV:case Ii.VideoFLV:case Ii.VideoWEBM:return Si.Video;case Ii.CompressedZIP:case Ii.CompressedRAR:case Ii.Compressed7Z:case Ii.CompressedTAR:case Ii.CompressedGZ:return Si.Compressed;case Ii.CodeHTML:case Ii.CodeCSS:case Ii.CodeJS:case Ii.CodeJSX:case Ii.CodeTS:case Ii.CodeTSX:case Ii.CodeJSON:case Ii.CodeXML:case Ii.CodePY:case Ii.CodeJAVA:case Ii.CodeC:case Ii.CodeCPP:case Ii.CodeCS:case Ii.CodeRB:case Ii.CodePHP:case Ii.CodeSQL:return Si.Code;case Ii.EbookEPUB:case Ii.EbookMOBI:case Ii.EbookAZW:return Si.Ebook;case Ii.FontTTF:case Ii.FontOTF:return Si.Font;case Ii.ExecutableEXE:case Ii.ExecutableDMG:case Ii.ExecutableAPK:return Si.Executable;default:return Si.Unknown}})(c),h=o[i].messages[s].fromPeerId===r.peerId?100:Math.floor(o[i].messages[s].savedSize/o[i].messages[s].totalSize*100),f={chunksReceivedTotal:o[i].messages[s].chunksReceivedTotal??0,chunksReceivedReal:o[i].messages[s].chunksReceivedReal??0,retransmits:o[i].messages[s].retransmits??0};if(c!==Ii.Text&&!n)return{message:"",percentage:h,size:o[i].messages[s].totalSize,filename:o[i].messages[s].filename,mimeType:l,extension:d,category:u,...f};if(c!==Ii.Text&&100===h){const e=o[i].messages[s].filename,t=o[i].messages[s].fromPeerId===r.peerId?await((e,t,n,r)=>Fa("assembleToOPFS",e,t,n,r))(o[i].messages[s].merkleRootHex,o[i].messages[s].totalSize,e,l):await((e,t,n,r)=>Fa("getReceiveFile",e,t,n,r))(o[i].messages[s].merkleRootHex,o[i].messages[s].totalSize,e,l);if(t)return{message:t,percentage:h,size:o[i].messages[s].totalSize,filename:e,mimeType:l,extension:d,category:u,...f}}const m=100===h?await((e,t)=>Fa("getDBAllChunks",e,t))(o[i].messages[s].merkleRootHex,o[i].messages[s].sha512Hex):[],p=m.map(e=>e.data).filter(e=>null!=e);try{const e=new Blob(p,{type:l});return c===Ii.Text?{message:p.length>0?await e.text():o[i].messages[s].fromPeerId===r.peerId?"Outgoing message...":"Incoming message...",percentage:h,size:o[i].messages[s].totalSize,filename:"",mimeType:l,extension:d,category:u,...f}:100===h&&e.size!==o[i].messages[s].totalSize?{message:"Irretrievable message",percentage:0,size:o[i].messages[s].totalSize,filename:o[i].messages[s].filename,mimeType:l,extension:d,category:u}:{message:e,percentage:h,size:o[i].messages[s].totalSize,filename:o[i].messages[s].filename,mimeType:l,extension:d,category:u,...f}}catch{return{message:"Invalid message",percentage:0,size:o[i].messages[s].totalSize,filename:o[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:Si.Text}}},hp=async(e,t,n,r,o)=>{if(!o&&!n&&!r)throw new Error("Need to provide a transfer ID, Merkle root, or hash");if(o&&!/^[0-9a-f]{64}$/.test(o))throw new Error("Invalid transfer ID");if(n&&"string"==typeof n&&n.length!==2*y)throw new Error("Invalid Merkle root length");if(n&&"string"!=typeof n&&n.length!==y)throw new Error("Invalid Merkle root length");if(r&&"string"==typeof r&&r.length!==2*y)throw new Error("Invalid hash length");if(r&&"string"!=typeof r&&r.length!==y)throw new Error("Invalid hash length");const a=n&&"string"==typeof n?n:n&&"string"!=typeof n?so(n):"",i=r&&"string"==typeof r?r:r&&"string"!=typeof r?so(r):"";Pu(e,{transferId:o,merkleRootHex:a||void 0,hashHex:i||void 0});const{rooms:s}=nm.getState(),c=s.findIndex(t=>t.id===e),l=c>-1?o?s[c].messages.findIndex(e=>e.transferId===o):n?s[c].messages.findIndex(e=>e.merkleRootHex===a):s[c].messages.findIndex(e=>e.sha512Hex===i):-1;if(c>-1&&l>-1&&s[c].messages[l].merkleRootHex.length===2*y){const n=await ci(t,s[c].messages[l].merkleRootHex);await nm.dispatch(kf.endpoints.disconnectFromChannelLabel.initiate({roomId:s[c].id,label:n,alsoDeleteData:!0})),nm.dispatch(lt({roomId:e,merkleRootHex:s[c].messages[l].merkleRootHex}))}},fp=async(e=async()=>{})=>{const t=await qf.cancelAndAcquireBootstrap();try{await(async e=>ep("Identity purge did not fully settle",[e.disconnectSignaling,e.clearRoomPins,e.resetIdentity,e.teardownRooms,e.deleteIdentityX25519,e.deleteIdentityEd25519,e.deleteIdentityDerivation]))({disconnectSignaling:async()=>{await rm(Xf.endpoints.disconnectWebSocket.initiate(void 0)).unwrap()},clearRoomPins:()=>{qu.clear()},resetIdentity:()=>{rm(h())},teardownRooms:e,deleteIdentityX25519:()=>oi(),deleteIdentityEd25519:()=>Fa("deleteIdentityEd25519"),deleteIdentityDerivation:()=>Fa("deleteIdentityDerivation")})}finally{qf.cancelActive(),rm(wt.disconnect()),t()}},mp=async e=>{const{rooms:t}=nm.getState();await ep(e,t.map(e=>async()=>await rm(kf.endpoints.disconnectFromRoom.initiate({roomId:e.id})).unwrap()))},pp=e=>{const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},yp={deriveIdentity:async(e,t)=>await Lm(e,t),runExclusive:async e=>await Zm.runGlobalTerminal(async()=>{Ru();const t=await qf.cancelAndAcquireBootstrap();try{return await e()}finally{qf.cancelActive(),rm(wt.disconnect()),t()}}),disconnectSignaling:async()=>{await rm(Xf.endpoints.disconnectWebSocket.initiate(void 0)).unwrap()},teardownRooms:async()=>await mp("One or more WebRTC rooms could not be disconnected during identity restore"),deleteIdentityX25519:()=>oi(),writeIdentityEd25519:async({publicKey:e,secretKey:t})=>{const n=pp(t);try{await ii({pub:pp(e),secret:n})}finally{n.byteLength>0&&new Uint8Array(n).fill(0)}},recordDerivation:async()=>{await si("mnemonic")},resetIdentityState:()=>{rm(h())},adoptIdentity:(e,t)=>{rm(c({publicKey:e,secretKey:t}))}},gp=async(e,t)=>await np(yp,e,t),wp=async e=>await(async(e,t)=>{const n=await Um(t?.strength??256),{publicKey:r}=await np(e,n,t?.password);return{mnemonic:n,publicKey:r}})(yp,e),bp=async()=>{let e=f(nm.getState()).publicKey;if(!Bo(e)){const t=await ai();e=t?so(new Uint8Array(t.pub)):"",t&&new Uint8Array(t.secret).fill(0)}return{publicKey:e,derivation:await Fa("getIdentityDerivation")}},vp={store:nm,commonStateSelector:e=>e.commonState,signalingServerSelector:e=>e.signalingServer,roomSelector:ft,keyPairSelector:f,connect:ap,connectToSignalingServer:async(e,t="wss://signaling.p2party.com/ws")=>{await ap(e,t)},disconnectFromSignalingServer:async()=>{await Zm.runGlobalTerminal(async()=>{await rm(Xf.endpoints.disconnectWebSocket.initiate(void 0)).unwrap()})},disconnectFromRoom:async(e,t=!1)=>{await rm(kf.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:t}))},disconnectFromAllRooms:async(e=!1,t=[])=>{await rm(kf.endpoints.disconnectFromAllRooms.initiate({deleteMessages:e,exceptionRoomIds:t}))},disconnectFromPeer:async e=>{await rm(kf.endpoints.disconnectFromPeer.initiate({peerId:e}))},allowConnectionRelay:(e,t=!0)=>{const{rooms:n}=nm.getState(),r=n.findIndex(t=>t.id===e);r>-1&&rm(Je({roomId:n[r].id,canBeConnectionRelay:t}))},onlyAllowConnectionsFromAddressBook:async(e,t)=>{let n;try{n=Gm(e)}catch{return}e=n;const{rooms:r}=nm.getState(),o=r.findIndex(t=>t.url===e);if(-1!==o&&!1!==r[o].signalingActive){if(o>-1&&!r[o].onlyConnectWithKnownAddresses&&t&&r[o].peers.length>0){const e=r[o].peers.length;for(let t=0;t<e;t++){await ja(r[o].peers[t].peerId,r[o].peers[t].peerPublicKey)||await rm(kf.endpoints.disconnectFromPeer.initiate({peerId:r[o].peers[t].peerId,roomId:r[o].id,alsoDeleteData:!1}))}}rm(Ye({roomId:r[o].id,roomUrl:e,onlyConnectWithKnownPeers:t}))}},addPeerToAddressBook:(e,t,n)=>Fa("setDBAddressBookEntry",e,t,n),getPeerAddressBookEntry:ja,getAllPeersInAddressBook:()=>Fa("getAllDBAddressBookEntries"),getAllPeersInBlacklist:()=>Fa("getAllDBBlacklisted"),deletePeerFromAddressBook:async(t,n,r)=>{const o=await((e,t,n)=>Fa("deleteDBAddressBookEntry",e,t,n))(t,n,r);e.isUUID(o)&&await rm(kf.endpoints.disconnectFromPeer.initiate({peerId:o,alsoDeleteData:!1}))},blacklistPeer:async(e,t)=>{await((e,t)=>Fa("setDBPeerInBlacklist",e,t))(e,t),await rm(kf.endpoints.disconnectFromPeer.initiate({peerId:e,alsoDeleteData:!0}))},getPeerIsBlacklisted:za,removePeerFromBlacklist:(e,t)=>Fa("deleteDBPeerFromBlacklist",e,t),getAllExistingRooms:$a,getRoomStats:e=>Fa("getDBRoomStats",e),sendMessage:(e,t,n,r=.9,o=3,a=q,i=1,s=Cu())=>{if(!/^[0-9a-f]{64}$/.test(s))throw new Error("Invalid transfer ID");const c=Eu(n,s),l=rm(kf.endpoints.sendMessage.initiate({transferId:s,data:e,label:t,roomId:n,minChunks:o,chunkSize:a,percentageFilledChunk:r,metadataSchemaVersion:i})).unwrap().finally(()=>c.finish());return{transferId:s,done:l,cancel:()=>hp(n,t,void 0,void 0,s)}},readMessage:up,getTransferAcks:(e,t)=>{const n=`${e}\0`,r=`\0${t}`,o=[];for(const[e,t]of di)e.startsWith(n)&&e.endsWith(r)&&o.push({peerId:e.slice(n.length,e.length-r.length),ackedChunks:t.acked.size,complete:t.complete});return o},getSendChunksCount:e=>Fa("getDBAllNewChunksCount",e),cancelMessage:hp,createTransferId:Cu,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*y)throw new Error("Invalid Merkle root length");if(t&&"string"!=typeof t&&t.length!==y)throw new Error("Invalid Merkle root length");if(n&&"string"==typeof n&&n.length!==2*y)throw new Error("Invalid hash length");if(n&&"string"!=typeof n&&n.length!==y)throw new Error("Invalid hash length");const r=t&&"string"==typeof t?t:t&&"string"!=typeof t?so(t):"",o=n&&"string"==typeof n?n:n&&"string"!=typeof n?so(n):"";Pu(e,{merkleRootHex:r||void 0,hashHex:o||void 0});const{rooms:a}=nm.getState(),i=a.findIndex(t=>t.id===e),s=i>-1?t?a[i].messages.findIndex(e=>e.merkleRootHex===r):n?a[i].messages.findIndex(e=>e.sha512Hex===o):-1:-1;if(i>-1&&s>-1&&a[i].messages[s].merkleRootHex.length===2*y){const t=await ci(a[i].messages[s].channelLabel,a[i].messages[s].merkleRootHex);await nm.dispatch(kf.endpoints.disconnectFromChannelLabel.initiate({roomId:a[i].id,label:t,alsoDeleteData:!0})),nm.dispatch(lt({roomId:e,merkleRootHex:a[i].messages[s].merkleRootHex}))}},purgeIdentity:async()=>{await Zm.runGlobalTerminal(async()=>{Ru(),await fp(async()=>await mp("One or more WebRTC rooms could not be disconnected during identity purge"))})},purgeRoom:async e=>{e=Gm(e),await Zm.runRoomTerminal(e,async()=>{const{rooms:t}=nm.getState(),n=t.findIndex(t=>t.url===e);if(-1===n)return;const r=t[n];Bu(e),xu(r.id),ya(e,"room was purged"),rm(ut(e));const o=!1!==r.signalingActive;await(async e=>{const t=[];try{await e.closeLocalTransport()}catch(e){t.push(e)}let n;try{n=Promise.resolve(e.startRemoteRevocation()).then(()=>({confirmed:!0}),e=>({confirmed:!1,error:e}))}catch(e){n=Promise.resolve({confirmed:!1,error:e})}for(const n of[e.deleteLocalData,e.clearPinAttempts])try{await n()}catch(e){t.push(e)}const r=await n;if(r.confirmed||t.push(r.error),1===t.length)throw t[0];if(t.length>1)throw new AggregateError(t,"Room purge did not fully settle")})({closeLocalTransport:async()=>{try{await fh(e).runExclusive(async()=>{await rm(kf.endpoints.disconnectFromRoom.initiate({roomId:r.id})).unwrap()})}finally{mh(e)}},startRemoteRevocation:async()=>{o&&await((e,t,n={})=>{const r=jf,o=zf,a=n.roomLeaveId??Zo();if(!r||!o)return Promise.reject(new xf(t,a,"no-current-socket"));const i=()=>jf===r&&zf===o&&o.isCurrent(()=>!0),{keyPair:s}=e.getState();return Uf(s.peerId,t,r,t=>{const n=Bf(r,{content:t},e,i);if("error"in n)throw new Error(n.error)},{...n,roomLeaveId:a})})(nm,e)},deleteLocalData:async()=>{await rm(kf.endpoints.disconnectFromRoom.initiate({roomId:r.id,deleteMessages:!0})).unwrap()},clearPinAttempts:async()=>{r.id&&await Vu(r.id)}})})},purge:async()=>{await Zm.runGlobalTerminal(async()=>{Ru(),await fp(async()=>{await ep("Full purge did not fully settle local data",[async()=>{await rm(kf.endpoints.disconnect.initiate({alsoDeleteDB:!0})).unwrap()},()=>{rm(ht()),rm(o(""))}])})})},generateRandomRoomUrl:async()=>Vm(Hm()),generateRoomInvite:()=>Xm(Hm()),generateRoomCapability:Hm,encodeRoomCapabilityBase64Url:Vm,decodeRoomCapabilityBase64Url:Wm,decodeRoomCapability:Qm,normalizeRoomCapability:Gm,encodeRoomInviteFragment:Xm,decodeRoomInviteFragment:Jm,encodeRoomCapabilityWords:async e=>{const t=$m(e),n=new Uint8Array(33);n.set(t),n[32]=await Ym(t);const r=(e=>{const t=[];let n=0,r=0;for(const o of e)for(n=n<<8|o,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=>Am[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,o=0;for(const a of e)for(n=n<<11|a,r+=11;r>=8;)r-=8,t[o]=n>>>r&255,o+=1,n&=(1<<r)-1;if(0!==r||o!==t.length)throw new Error("Room invite word encoding is not canonical");return t})(n.map(e=>{const t=zm.get(e);if(void 0===t)throw new Error(`Unknown room invite word: ${e}`);return t})),o=r.slice(0,qm),a=await Ym(o);if(r[32]!==a)throw new Error("Room invite checksum is invalid");return o},ROOM_INVITE_WORDLIST_ID:"p2party-invite-en-v1",sign:qo,verify:Oo,createSession:Sm,restoreSession:Cm,generateSessionIdentity:ym,setWasmSourceUrl:Uo,DEFAULT_ROOM_POLICY_V1:Pe,encodeRoomPolicyV1:Ie,decodeRoomPolicyV1:Se,hashRoomPolicyV1:Ee,roomPoliciesEqualV1:Ae,generateKeyPair:To,newKeyPair:To,generateMnemonic:Um,keyPairFromMnemonic:Lm,validateMnemonic:Dm,validateMnemonicWords:Tm,createRecoverableIdentity:wp,restoreIdentityFromMnemonic:gp,getIdentityBackupStatus:bp,InvalidRecoveryPhraseError:tp,MIN_CHUNKS:1,MIN_CHUNK_SIZE:O+1,MAX_CHUNK_SIZE:q,WIRE_CHUNK_FRAME_LEN:H,MIN_COVER_CADENCE_MS:ae,MAX_COVER_CADENCE_MS:ie,MAX_COVER_LANES:16,MAX_COVER_FRAMES_PER_CELL:se,MIN_COVER_SLOT_MS:25,validateRoomPolicyV1:ke,MessageDeliveryError:of,RemoteRoomRevocationUnconfirmedError:xf,joinRoom:cp,waitForRoom:sp,waitForPeers:lp,onMessage:dp,setDebugLogging:kt,MIN_PERCENTAGE_FILLED_CHUNK:.1,MAX_PERCENTAGE_FILLED_CHUNK:.99,ROOM_URL_LENGTH:64,MessageType:Ii,MessageCategory:Si,VERSION:n};"undefined"!=typeof window&&(window.p2party=vp),exports.DEFAULT_ROOM_POLICY_V1=Pe,exports.InvalidRecoveryPhraseError=tp,exports.MAX_COVER_CADENCE_MS=ie,exports.MAX_COVER_FRAMES_PER_CELL=se,exports.MAX_COVER_LANES=16,exports.MIN_COVER_CADENCE_MS=ae,exports.MIN_COVER_SLOT_MS=25,exports.MessageDeliveryError=of,exports.RemoteRoomRevocationUnconfirmedError=xf,exports.WIRE_CHUNK_FRAME_LEN=H,exports.canonicalizeRoomPolicyV1=Ce,exports.createRecoverableIdentity=wp,exports.createSession=Sm,exports.decodeRoomPolicyV1=Se,exports.default=vp,exports.encodeRoomPolicyV1=Ie,exports.generateSessionIdentity=ym,exports.getIdentityBackupStatus=bp,exports.hashRoomPolicyV1=Ee,exports.joinRoom=cp,exports.onMessage=dp,exports.p2party=vp,exports.restoreIdentityFromMnemonic=gp,exports.restoreSession=Cm,exports.roomPoliciesEqualV1=Ae,exports.setDebugLogging=kt,exports.setWasmSourceUrl=Uo,exports.validateMnemonic=Dm,exports.validateMnemonicWords=Tm,exports.validateRoomPolicyV1=ke,exports.waitForPeers=lp,exports.waitForRoom=sp;
|