openrtc 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ import {a as a$1}from'./chunk-BGQX25BO.js';import {h,a as a$2,c as c$4,b as b$4,d as d$3}from'./chunk-L6OUJ6YN.js';import {w,c as c$1,B as B$1,D,o,q as q$1,b as b$2,d as d$2,e as e$1,f as f$2,k as k$1,g as g$1,h as h$1,i,j as j$1,n as n$1,m as m$1,l as l$1}from'./chunk-MESPJTUA.js';import {w as w$1,x as x$1,u,t,g,q,r,s,c as c$3,G,k,j,l,m,o as o$1,n,b as b$3,E,e as e$2,f as f$3,a as a$3,i as i$1,h as h$2,y,z,B as B$2,A,C as C$1,D as D$1}from'./chunk-34LATQZZ.js';import {b as b$1,e,c as c$2,f as f$1,g as g$2}from'./chunk-QT2ASNI3.js';import {c,a,d as d$1}from'./chunk-C7YN5MSV.js';import {x25519}from'@noble/curves/ed25519.js';import {hkdf}from'@noble/hashes/hkdf.js';import {sha256}from'@noble/hashes/sha2.js';import {getFirestore,collection,onSnapshot,query,limit}from'firebase/firestore';import*as Jt from'@moq/net';var vi=3e4,we=class we{constructor(){this.name="webrtc";this.pc=null;this.dc=null;this.state="disconnected";this.pendingCandidates=[];this.connectTimeoutId=null;this.iceDisconnectedGraceTimer=null;this.iceRestartAttempted=false;this.localNodeId="";this.remoteNodeId="";this.candidatesGathered=0;this.sdpOfferSent=false;this.sdpAnswerReceived=false;this._terminalFailure=false;this.activeAttemptId=0;this.negotiationId=null;this.disconnectedGraceExtensions=0;this.offerInFlight=false;this.messageListeners=[];this.stateListeners=[];this.internalSignalSender=null;}get isReady(){return this.state==="connected"}isTerminalFailure(){return this._terminalFailure}getNegotiationId(){return this.negotiationId}getDataChannelReadyState(){return this.dc?.readyState??null}getNativeTransport(){return this.pc}setSignalSender(e){this.internalSignalSender=e;}async init(e,t,n){this.closePeerResources();let i=++this.activeAttemptId;this.localNodeId=e,this.remoteNodeId=t,this.candidatesGathered=0,this.sdpOfferSent=false,this.sdpAnswerReceived=false,this._terminalFailure=false,this.offerInFlight=false,this.pendingCandidates=[],this.disconnectedGraceExtensions=0,this.negotiationId=typeof n?.negotiationId=="string"&&n.negotiationId.trim().length>0?n.negotiationId.trim():this.createNegotiationId(),this.setState("connecting"),this.startConnectTimeout(i);let o=n.rtcConfig||{},s=typeof n?.forceRole=="string"&&(n.forceRole==="initiator"||n.forceRole==="responder")?n.forceRole:null,a=s?s==="initiator":e>t;d$2(`[WebRTCTransport] init \u2014 role=${a?"initiator":"responder"}`,{local:e.slice(0,12),remote:t.slice(0,12),negotiationId:this.negotiationId,forcedRole:s});try{d$2("[WebRTCTransport] Creating RTCPeerConnection",{iceServers:o.iceServers?.length??0}),this.pc=new RTCPeerConnection(o);}catch(l){console.error("[WebRTCTransport] RTCPeerConnection constructor failed",l),this.setState("failed");return}let c=this.pc.createDataChannel("pluto-dc",{negotiated:true,id:0});this.setupDataChannel(c,i),this.setupPCHandlers(a,i),a&&queueMicrotask(()=>{this.createAndSendOffer(i,"initial-initiator");});}setupDataChannel(e,t){this.dc=e,e.onopen=()=>{this.isCurrentAttempt(t,e)&&(d$2("[WebRTCTransport] DataChannel opened \u2014 upgrade complete"),this.promoteConnectedIfReady("datachannel-open"));},e.onmessage=n=>{if(!this.isCurrentAttempt(t,e))return;let i=typeof n.data=="string"?new TextEncoder().encode(n.data):new Uint8Array(n.data);this.messageListeners.forEach(o=>o(i));},e.onclose=()=>{this.isCurrentAttempt(t,e)&&(d$2("[WebRTCTransport] DataChannel closed"),(this.state==="connected"||this.state==="connecting")&&this.setState("disconnected"));},e.onerror=n=>{if(!this.isCurrentAttempt(t,e))return;console.warn("[WebRTCTransport] DataChannel error",n);let i=n?.error?.message??"";if((i.includes("User-Initiated Abort")||i.includes("Close called"))&&this.state==="connected"&&e.readyState!=="open"){console.warn("[WebRTCTransport] DataChannel aborted post-connect; forcing disconnected state",{readyState:e.readyState,connectionState:this.pc?.connectionState,iceConnectionState:this.pc?.iceConnectionState}),this.setState("disconnected");return}this.state==="connecting"&&this.setState("failed");};}setupPCHandlers(e,t){let n=this.pc;n&&(n.onicecandidate=i=>{this.isCurrentAttempt(t,void 0,n)&&(i.candidate?(this.candidatesGathered++,d$2(`[WebRTCTransport] ICE candidate #${this.candidatesGathered}: ${i.candidate.type} ${i.candidate.protocol} ${i.candidate.address??"?"}:${i.candidate.port}`),this.internalSignalSender?this.internalSignalSender({transport:"webrtc",type:"candidate",candidate:i.candidate,negotiationId:this.negotiationId??void 0}).catch(o=>{console.warn("[WebRTCTransport] Failed sending local ICE candidate signal",{error:o,gatheringState:n?.iceGatheringState,iceConnectionState:n?.iceConnectionState});}):console.warn("[WebRTCTransport] ICE candidate dropped \u2014 no signal sender!")):this.candidatesGathered===0?(console.warn("[WebRTCTransport] ICE gathering complete with 0 candidates \u2014 failing immediately.","If both peers are on the same page, WebRTC requires separate tabs or devices.",{local:this.localNodeId.slice(0,12),remote:this.remoteNodeId.slice(0,12)}),this._terminalFailure=true,this.setState("failed")):d$2(`[WebRTCTransport] ICE gathering complete \u2014 ${this.candidatesGathered} candidate(s)`));},n.onnegotiationneeded=async()=>{e&&await this.createAndSendOffer(t,"negotiationneeded");},n.onconnectionstatechange=()=>{if(!this.isCurrentAttempt(t,void 0,n))return;let i=n.connectionState;if(d$2(`[WebRTCTransport] Connection state: ${i}`),i==="connected")this.promoteConnectedIfReady("pc-connected");else if(i==="failed"){if(this.iceDisconnectedGraceTimer){console.warn("[WebRTCTransport] pc.connectionState=failed during grace window \u2014 deferring to grace timer",{iceState:n.iceConnectionState,iceRestartAttempted:this.iceRestartAttempted});return}console.error("[WebRTCTransport] Connection failed",{iceState:n.iceConnectionState,gatheringState:n.iceGatheringState,signalingState:n.signalingState,candidatesGathered:this.candidatesGathered,sdpOfferSent:this.sdpOfferSent,sdpAnswerReceived:this.sdpAnswerReceived}),this.clearIceDisconnectedGrace("pc-failed"),this.setState("failed");}else i==="closed"?(this.clearIceDisconnectedGrace("pc-closed"),this.setState("disconnected")):i==="disconnected"&&(d$2("[WebRTCTransport] pc.connectionState=disconnected, deferring to ICE grace period"),this.startIceDisconnectedGrace(t,n,e,"pc-disconnected"));},n.oniceconnectionstatechange=()=>{if(!this.isCurrentAttempt(t,void 0,n))return;let i=n.iceConnectionState;if(d$2(`[WebRTCTransport] ICE connection state: ${i}`,{gatheringState:n.iceGatheringState,signalingState:n.signalingState,candidatesGathered:this.candidatesGathered,hasSdpOffer:this.sdpOfferSent,hasSdpAnswer:this.sdpAnswerReceived,hasRemoteDescription:!!n.remoteDescription,hasLocalDescription:!!n.localDescription}),i==="failed"){if(this.iceDisconnectedGraceTimer){console.warn("[WebRTCTransport] ice failed during grace window \u2014 deferring to grace timer");return}console.error("[WebRTCTransport] ICE failed \u2014 likely NAT traversal issue or no matching candidates",{gatheringState:n.iceGatheringState,signalingState:n.signalingState,candidatesGathered:this.candidatesGathered}),this.clearIceDisconnectedGrace("ice-failed"),this.setState("failed");}else i==="disconnected"?this.startIceDisconnectedGrace(t,n,e,"ice-disconnected"):(i==="connected"||i==="completed")&&(this.iceDisconnectedGraceTimer&&d$2("[WebRTCTransport] ice-recovered \u2014 cancelling grace timer"),this.clearIceDisconnectedGrace("ice-recovered"),this.iceRestartAttempted=false,this.promoteConnectedIfReady("ice-connected"));},n.onicegatheringstatechange=()=>{this.isCurrentAttempt(t,void 0,n)&&d$2(`[WebRTCTransport] ICE gathering state: ${n.iceGatheringState}`,{iceConnectionState:n.iceConnectionState,signalingState:n.signalingState,hasLocalDesc:!!n.localDescription,hasRemoteDesc:!!n.remoteDescription});});}async createAndSendOffer(e,t){let n=this.pc;if(!(!n||!this.isCurrentAttempt(e,void 0,n))&&n.signalingState==="stable"&&!(this.sdpOfferSent&&n.localDescription?.type==="offer")&&!this.offerInFlight){d$2(`[WebRTCTransport] Creating offer (${t})`),this.offerInFlight=true;try{let i=await n.createOffer();if(await n.setLocalDescription(i),!this.isCurrentAttempt(e,void 0,n))return;if(this.sdpOfferSent=!0,this.internalSignalSender)try{await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:i,negotiationId:this.negotiationId??void 0});}catch(o){console.warn("[WebRTCTransport] Offer signaling failed (non-fatal)",{error:o,negotiationId:this.negotiationId,signalingState:n.signalingState,iceConnectionState:n.iceConnectionState});}else console.warn("[WebRTCTransport] No signal sender \u2014 offer not transmitted");}catch(i){console.error("[WebRTCTransport] Offer creation failed",i),this.closePeerResources(),this.setState("failed");}finally{this.isCurrentAttempt(e,void 0,n)&&(this.offerInFlight=false);}}}handleSignalingMessage(e){if(!this.pc||e.transport!=="webrtc")return;let t=this.normalizeNegotiationId(e?.negotiationId);if(t&&this.negotiationId&&t!==this.negotiationId){c$1("[WebRTCTransport] Ignoring stale signaling message for a different negotiation",{signalType:e?.type??null,signalNegotiationId:t,activeNegotiationId:this.negotiationId});return}if(e.type==="candidate"){let n=e.candidate;d$2("[WebRTCTransport] Received remote ICE candidate",{hasRemoteDesc:!!this.pc.remoteDescription,type:n?.type,protocol:n?.protocol,address:n?.address}),this.pc.remoteDescription?this.pc.addIceCandidate(n).catch(i=>{console.warn("[WebRTCTransport] addIceCandidate failed",i);}):(this.pendingCandidates.push(n),d$2(`[WebRTCTransport] Buffered remote candidate \u2014 ${this.pendingCandidates.length} pending`));}else if(e.type==="sdp"){let n=e.sdp,i=n.type==="offer",o=n.type==="answer";if(o&&this.pc.signalingState!=="have-local-offer"){c$1("[WebRTCTransport] Ignoring SDP answer because no local offer is pending",{signalingState:this.pc.signalingState,iceConnectionState:this.pc.iceConnectionState,signalNegotiationId:t,activeNegotiationId:this.negotiationId,hasLocalDescription:!!this.pc.localDescription,hasRemoteDescription:!!this.pc.remoteDescription});return}d$2(`[WebRTCTransport] Received SDP ${n.type} \u2014 applying remote description`),o&&(this.sdpAnswerReceived=true),this.pc.setRemoteDescription(n).then(async()=>{if(o&&(d$2("[WebRTCTransport] Remote SDP answer applied",{signalingState:this.pc?.signalingState,iceConnectionState:this.pc?.iceConnectionState,hasLocalDescription:!!this.pc?.localDescription,hasRemoteDescription:!!this.pc?.remoteDescription}),this.promoteConnectedIfReady("sdp-answer-applied")),this.pendingCandidates.length&&(d$2(`[WebRTCTransport] Flushing ${this.pendingCandidates.length} buffered candidate(s)`),this.pendingCandidates.forEach(s=>this.pc?.addIceCandidate(s)),this.pendingCandidates=[]),i){d$2("[WebRTCTransport] Creating answer (responder)");let s=await this.pc.createAnswer();if(await this.pc.setLocalDescription(s),d$2("[WebRTCTransport] Answer sent"),this.internalSignalSender)try{await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:s,negotiationId:t??this.negotiationId??void 0});}catch(a){throw console.warn("[WebRTCTransport] Failed sending SDP answer signal",{error:a,signalingState:this.pc?.signalingState,hasLocalDescription:!!this.pc?.localDescription,hasRemoteDescription:!!this.pc?.remoteDescription}),a}else console.warn("[WebRTCTransport] No signal sender \u2014 answer not transmitted");}}).catch(s=>{console.error(`[WebRTCTransport] setRemoteDescription (${n.type}) failed`,s),this.setState("failed");});}}async send(e){if(this.dc&&this.dc.readyState==="open"){let t=new Uint8Array(e);this.dc.send(t);}else throw new Error("WebRTC DataChannel not open")}getBufferedAmount(){return this.dc?.bufferedAmount??0}async waitForDrain(e){!this.dc||this.dc.bufferedAmount<=e||await new Promise(t=>{let n=this.dc;if(!n){t();return}n.bufferedAmountLowThreshold=e,n.onbufferedamountlow=()=>{n.onbufferedamountlow=null,t();};});}close(){this.closePeerResources(),this.setState("disconnected");}onMessage(e){this.messageListeners.push(e);}onStateChange(e){this.stateListeners.push(e);}setState(e){this.state!==e&&(this.state=e,(e==="connected"||e==="failed"||e==="disconnected")&&this.clearConnectTimeout(),this.stateListeners.forEach(t=>t(e)));}startConnectTimeout(e){this.clearConnectTimeout(),this.connectTimeoutId=setTimeout(()=>{this.activeAttemptId===e&&this.state==="connecting"&&(console.warn(`[WebRTCTransport] Timed out after ${we.ICE_CONNECT_TIMEOUT_MS}ms`,{iceState:this.pc?.iceConnectionState,gatheringState:this.pc?.iceGatheringState,signalingState:this.pc?.signalingState,candidatesGathered:this.candidatesGathered,sdpOfferSent:this.sdpOfferSent,sdpAnswerReceived:this.sdpAnswerReceived,hasRemoteDescription:!!this.pc?.remoteDescription,hasLocalDescription:!!this.pc?.localDescription}),this.setState("failed"));},we.ICE_CONNECT_TIMEOUT_MS);}clearConnectTimeout(){this.connectTimeoutId&&(clearTimeout(this.connectTimeoutId),this.connectTimeoutId=null);}startIceDisconnectedGrace(e,t,n,i){if(!this.iceDisconnectedGraceTimer){if(this.iceRestartAttempted)d$2("[WebRTCTransport] ice-disconnected grace (restart already attempted)",{reason:i});else if(this.iceRestartAttempted=true,n){try{d$2("[WebRTCTransport] ice-restart-attempted",{reason:i,isInitiator:n}),t.restartIce();}catch(o){console.warn("[WebRTCTransport] restartIce threw",o);}this.sendIceRestartOffer(e,t);}else d$2("[WebRTCTransport] ice-restart deferred to initiator",{reason:i});this.iceDisconnectedGraceTimer=setTimeout(()=>{if(this.iceDisconnectedGraceTimer=null,this.activeAttemptId!==e||this.pc!==t)return;let o=t.iceConnectionState,s=t.connectionState,a=this.dc?.readyState??"missing";if(o==="connected"||o==="completed"||s==="connected"||a==="open"){d$2("[WebRTCTransport] ice-grace expired \u2014 recovered",{ice:o,conn:s,dcReadyState:a});return}if(this.disconnectedGraceExtensions<1){this.disconnectedGraceExtensions+=1,console.warn("[WebRTCTransport] ice-grace expired \u2014 extending once before fail",{ice:o,conn:s,dcReadyState:a,extension:this.disconnectedGraceExtensions}),this.startIceDisconnectedGrace(e,t,n,`${i}:extended`);return}console.warn("[WebRTCTransport] ice-grace expired \u2014 marking failed",{ice:o,conn:s}),this.setState("failed");},we.ICE_DISCONNECTED_GRACE_MS);}}async sendIceRestartOffer(e,t){try{let n=await t.createOffer({iceRestart:!0});if(!this.isCurrentAttempt(e,void 0,t)||(await t.setLocalDescription(n),!this.isCurrentAttempt(e,void 0,t)))return;this.internalSignalSender?(await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:n,negotiationId:this.negotiationId??void 0}),d$2("[WebRTCTransport] ice-restart re-offer sent",{negotiationId:this.negotiationId})):console.warn("[WebRTCTransport] ice-restart re-offer dropped \u2014 no signal sender");}catch(n){console.warn("[WebRTCTransport] ice-restart re-offer failed",n);}}clearIceDisconnectedGrace(e){this.iceDisconnectedGraceTimer&&(clearTimeout(this.iceDisconnectedGraceTimer),this.iceDisconnectedGraceTimer=null);}promoteConnectedIfReady(e){let t=this.dc?.readyState??"missing";if(t!=="open"){d$2("[WebRTCTransport] Deferring connected state until DataChannel is open",{reason:e,dcReadyState:t,iceConnectionState:this.pc?.iceConnectionState,connectionState:this.pc?.connectionState});return}this.clearIceDisconnectedGrace(`connected:${e}`),this.disconnectedGraceExtensions=0,this.setState("connected");}closePeerResources(){this.activeAttemptId+=1,this.clearConnectTimeout(),this.clearIceDisconnectedGrace("close"),this.iceRestartAttempted=false,this.pendingCandidates=[],this._terminalFailure=false,this.negotiationId=null,this.disconnectedGraceExtensions=0,this.offerInFlight=false,this.dc&&(this.dc.onopen=null,this.dc.onmessage=null,this.dc.onclose=null,this.dc.onerror=null,this.dc.readyState!=="closed"&&this.dc.close(),this.dc=null),this.pc&&(this.pc.onicecandidate=null,this.pc.onnegotiationneeded=null,this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.connectionState!=="closed"&&this.pc.close(),this.pc=null);}isCurrentAttempt(e,t,n){return !(this.activeAttemptId!==e||t&&this.dc!==t||n&&this.pc!==n)}createNegotiationId(){return `ts-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}normalizeNegotiationId(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}};we.ICE_CONNECT_TIMEOUT_MS=vi,we.ICE_DISCONNECTED_GRACE_MS=3e4;var Pt=we;var Qs={iroh:{available:false,reason:"iroh is constructed by the OpenRTC runtime, not the legacy ITransport factory."},"iroh-quic":{available:false,reason:"iroh-quic is a path label, not a standalone transport."},"iroh-relay":{available:false,reason:"iroh-relay is a path label, not a standalone transport."},"iroh-lan":{available:false,reason:"iroh-lan is a path label, not a standalone transport."},ble:{available:false,reason:"ble requires a separately licensed native host companion and current physical-device evidence."},webrtc:{available:true},"webrtc-lan":{available:false,reason:"webrtc-lan is a path label, not a standalone transport."},"webrtc-turn":{available:false,reason:"webrtc-turn is a path label, not a standalone transport."},moq:{available:false,reason:"MoQ is constructed by the route lifecycle, not the legacy ITransport factory."}};function $s(r){return r.implementation==="route-adapter"?"plugin":r.implementation==="core"?"native":"path-label"}function Vs(){return Object.fromEntries(a.map(r=>[r.id,{...r,routeImplementation:r.implementation,implementation:$s(r),protocol:r.id,preferredRank:d$1[r.id],...Qs[r.id]}]))}var Ce=class{static createTransport(e){if(this.assertProtocolAvailable(e),e==="webrtc")return new Pt;throw new Error(`[TransportFactory] '${e}' is not implemented as an ITransport plugin.`)}static getProtocolCapability(e){return {...this.capabilityMap[e]}}static getProtocolCapabilities(){return Object.fromEntries(a.map(e=>[e.id,this.getProtocolCapability(e.id)]))}static getPreferredProtocolOrder(e={}){let t=e.runtime??"any",n=e.includePathLabels??true;return a.filter(i=>n||i.implementation!=="path-label").filter(i=>t==="browser"?i.browser:t==="native"?i.native:i.browser||i.native).sort((i,o)=>d$1[i.id]-d$1[o.id]).map(i=>i.id)}static assertProtocolAvailable(e){let t=this.capabilityMap[e];if(!t.available||t.maturity==="unsupported"){let n=t.reason?` ${t.reason}`:"";throw new Error(`[TransportFactory] Protocol '${e}' is unsupported.${n}`)}}};Ce.capabilityMap=Vs();function Oc(r){return Ce.getPreferredProtocolOrder(r)}var _t=32,Bo="openrtc:x25519-hkdf:v1",Ci=new TextEncoder().encode("openrtc:application-crypto:v1");function wt(r,e){if(!(e instanceof Uint8Array)||e.byteLength!==_t)throw new Error(`[OpenRTC] ${r} must be ${_t} bytes`)}function Js(r,e){let[t,n]=r<=e?[r,e]:[e,r],i=new TextEncoder().encode(t),o=new TextEncoder().encode(n),s=new Uint8Array(Ci.byteLength+1+i.byteLength+1+o.byteLength),a=0;return s.set(Ci,a),a+=Ci.byteLength,s[a]=0,a+=1,s.set(i,a),a+=i.byteLength,s[a]=0,a+=1,s.set(o,a),s}function Wo(r=e=>{let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),t}){let e=r(_t);return wt("key agreement secret",e),{publicKey:x25519.getPublicKey(e),secretKey:e}}function Oo(r,e,t,n){wt("key agreement local secret",r),wt("key agreement remote public key",e);let i=x25519.getSharedSecret(r,e);return hkdf(sha256,i,void 0,Js(t,n),32)}function Ye(r){return Array.from(sha256(r).slice(0,6),e=>e.toString(16).padStart(2,"0")).join("")}function Ho(r){wt("key agreement public key",r);let e="";for(let n=0;n<r.byteLength;n+=1)e+=String.fromCharCode(r[n]);let t=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return {algorithm:Bo,publicKey:t}}function Uo(r){if(!r||r.algorithm!==Bo)return null;let e=typeof r.publicKey=="string"?r.publicKey.trim():"";if(!e)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.length%4===0?t:t+"=".repeat(4-t.length%4),i=Uint8Array.from(atob(n),o=>o.charCodeAt(0));return i.byteLength!==_t?null:i}var Tt=class{constructor(e,t){this._disposed=false;this.cleanups=[];this.runtime=e,this.scope=t.scope,this.allowAllPeers=t.allowAllPeers??false,this.allowedPeerIds=new Set(t.allowPeers??[]);}get disposed(){return this._disposed}matchesPeer(e){if(this.allowAllPeers||e.scopes?.includes(this.scope))return true;if(this.allowedPeerIds.size>0){let t=[e.peerId,e.deviceId,e.deviceIdHint,e.connectionId];for(let n of t)if(n&&this.allowedPeerIds.has(n))return true}return false}matchesConnectionState(e){if(this.allowAllPeers)return true;let t=e.scopes;if(Array.isArray(t)&&t.includes(this.scope))return true;if(this.allowedPeerIds.size>0){let n=[e.connectionId,e.deviceId,e.deviceIdHint,e.remoteNodeId];for(let i of n)if(i&&this.allowedPeerIds.has(i))return true}return false}matchesStream(e){if(this.allowAllPeers)return true;let t=e.scopes;return !!(Array.isArray(t)&&t.includes(this.scope)||this.allowedPeerIds.size>0&&this.allowedPeerIds.has(e.remoteNodeId))}watchPeerStates(e){this.assertNotDisposed();let t=this.runtime.watchPeerStates(n=>{if(this._disposed)return;let i=this.allowAllPeers?n:n.filter(o=>this.matchesPeer(o));e(i);});return this.cleanups.push(t),t}onConnectionStateChange(e){this.assertNotDisposed();let t=o=>{this._disposed||this.matchesConnectionState(o)&&e(o);},n=this.runtime.onConnectionStateChange(t);return typeof n=="function"?(this.cleanups.push(n),n):n.then(o=>this._disposed?(o(),()=>{}):(this.cleanups.push(o),o))}listConnectedPeers(){this.assertNotDisposed();let e=this.runtime.listConnectedPeers();return this.allowAllPeers?e:e.filter(t=>this.matchesPeer(t))}async getPeerReadiness(e){return this.assertNotDisposed(),this.runtime.getPeerReadiness(e)}connectPeer(e){return this.assertNotDisposed(),this.runtime.connectPeer({...e,scope:e.scope??this.scope})}async disconnectPeer(e){return this.assertNotDisposed(),this.runtime.disconnectPeer(e,this.scope)}onIncomingStream(e){this.assertNotDisposed();let t=this.runtime.onIncomingStream(n=>{this._disposed||this.matchesStream(n)&&e(n);});return this.cleanups.push(t),t}dispose(){if(!this._disposed){this._disposed=true;for(let e of this.cleanups)try{e();}catch{}this.cleanups.length=0,this.releaseScopedPeersOnDispose();}}releaseScopedPeersOnDispose(){let e;try{e=this.runtime.listConnectedPeers();}catch{return}for(let t of e){if(!t.scopes?.includes(this.scope))continue;let n=t.peerId||t.connectionId||t.deviceId||t.deviceIdHint;n&&this.runtime.disconnectPeer(n,this.scope).catch(()=>{});}}assertNotDisposed(){if(this._disposed)throw new Error(`[Session] Session '${this.scope}' has been disposed.`)}};var At=class{constructor(e,t,n=()=>{}){this.client=e;this.backend=t;this.onLifecycleMutation=n;}async connectToDevice(e){let t=this.backend;if(!t||typeof t.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return e.deviceId&&(this.clearManualDisconnectProjection(e.deviceId),await t.setAutoConnectExcluded?.(e.deviceId,false).catch(()=>{})),t.connectToDevice(e)}async connectRaw(e){return this.client.connectRaw(e.ticket,e.timeoutMs)}async openBi(e){return this.client.openBi(e)}async openUni(e){return this.client.openUni(e)}async isConnected(e){return this.client.isConnected(e)}async disconnectNode(e){try{await this.client.disconnectNode(e);}finally{this.onLifecycleMutation();}}async disconnectDevice(e){let t=this.backend;await t?.setAutoConnectExcluded?.(e,true).catch(()=>{});try{try{t&&typeof t.disconnectDevice=="function"&&await t.disconnectDevice(e);}finally{await this.client.forceDisconnectPeer(e);}}finally{this.onLifecycleMutation();}}async setAutoConnectExcluded(e,t){let n=this.backend;n&&typeof n.setAutoConnectExcluded=="function"&&await n.setAutoConnectExcluded(e,t),t||this.clearManualDisconnectProjection(e);}async disconnectPeer(e,t){try{await this.client.disconnectPeer(e,t);}finally{this.onLifecycleMutation();}}async forceDisconnectPeer(e){try{await this.client.forceDisconnectPeer(e);}finally{this.onLifecycleMutation();}}clearManualDisconnectProjection(e){let t=this.client.clearManualDisconnectProjection;typeof t=="function"&&t.call(this.client,e);}};var Go={classifyScope(r){return r.startsWith("drive-grant:")?{sessionKind:"drive-grant-guest",grantId:r.slice(12),scope:r}:r==="user-device"?{sessionKind:"app-user-device",scope:r}:{scope:r}}},Xs=[["sessionKind","session_kind"],["grantId","grant_id"],["scope","scope"],["peerNodeId","peer_node_id"],["connectionId","connection_id"],["transportEpoch","transport_epoch"],["channel","channel"],["tokenFp","token_fp"]];function Zs(r){let e=[];for(let[t,n]of Xs){let i=r[t];i==null||i===""||e.push(`${n}=${i}`);}return e.join(" ")}function ea(r,e,t=Go){let n=t.classifyScope(r);return {...{sessionKind:n.sessionKind,grantId:n.grantId,scope:n.scope??r},...e??{}}}function Je(r,e){return ea(r,e,Go)}function oe(r,e,t,...n){let i=Zs(e),o=ta(t,n);console.log(i&&o?`${r} ${i} ${o}`:i?`${r} ${i}`:o?`${r} ${o}`:r);}function ta(r,e){if(!r)return "";if(e.length===0)return r;if(/\{\}/.test(r)){let n=0;return r.replace(/\{\}/g,()=>{let i=n<e.length?e[n]:"";return n+=1,jo(i)})}return [r,...e.map(jo)].join(" ")}function jo(r){if(r==null)return String(r);if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);try{return JSON.stringify(r)}catch{return String(r)}}var ce=class extends Error{constructor(e,t){super(t),this.kind=e,this.name="DriveGrantActorError";}};function Si(r,e){return {scope:r,peerNodeId:e}}function bi(r){return `${r.scope}@${r.peerNodeId}`}var Xe=class{constructor(e){this.state="idle";this.inFlight=null;this.key=e.key,this.dial=e.dial,this.close=e.close??(async()=>{});}isReady(){return this.state==="base-ready"||this.state==="protocol-ready"}isClosed(){return this.state==="closed"}getState(){return this.state}getPreferredTransport(){return this.state==="closed"||this.state==="idle"||this.state==="dialing"?"none":"base"}markProtocolReady(){this.state!=="closed"&&(this.state="protocol-ready",oe("[drive-grant-actor][state]",this.correlation(),"state=protocol-ready"));}markDegraded(){this.state!=="closed"&&(this.state="degraded",oe("[drive-grant-actor][state]",this.correlation(),"state=degraded"));}correlation(e){return Je(this.key.scope,{peerNodeId:this.key.peerNodeId,...e??{}})}async ensureReady(){if(this.state==="closed")throw new ce("shutdown","drive-grant actor: already shut down");if(!this.isReady())return this.inFlight?this.inFlight:(this.state="dialing",oe("[drive-grant-actor][dial]",this.correlation(),"begin"),this.inFlight=this.dial(this.key).then(()=>{this.state!=="closed"&&(this.state="base-ready",this.inFlight=null,oe("[drive-grant-actor][dial]",this.correlation(),"ready_first"));},e=>{this.state!=="closed"&&(this.state="idle"),this.inFlight=null;let t=e instanceof Error?e.message:String(e);throw oe("[drive-grant-actor][dial]",this.correlation(),"failed error={}",t),e instanceof ce?e:new ce("dial-failed",`drive-grant actor: dial failed: ${t}`)}),this.inFlight)}async openLogicalChannel(e){if(this.state==="closed")throw new ce("shutdown","drive-grant actor: already shut down");if(!this.isReady())throw new ce("not-ready","drive-grant actor: ensureReady() must resolve before openLogicalChannel");return oe("[drive-grant-actor][channel]",this.correlation({channel:e}),"open"),{label:e}}async openLogicalChannelTestStub(e){if(this.state==="closed")throw new ce("shutdown","drive-grant actor: already shut down");if(!this.isReady())throw new ce("not-ready","drive-grant actor: ensureReady() must resolve before openLogicalChannel");return {label:e}}async shutdown(){if(this.state!=="closed"){this.state="closed",this.inFlight=null,oe("[drive-grant-actor][shutdown]",this.correlation(),"begin");try{await this.close(this.key);}catch{}oe("[drive-grant-actor][shutdown]",this.correlation(),"complete");}}},Ze=class{constructor(e){this.actors=new Map;this.factory=e;}getOrSpawn(e,t){let n=bi(e),i=this.actors.get(n);if(i&&!i.isClosed())return i;let o=(t??this.factory)(e);return this.actors.set(n,o),o}get(e){return this.actors.get(bi(e))??null}async shutdownAll(){let e=[...this.actors.values()];this.actors.clear(),await Promise.all(e.map(t=>t.shutdown()));}size(){return this.actors.size}};var na=new TextEncoder,ia=new TextDecoder;function Ii(r){let e=new Uint8Array(4+r.byteLength);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(0,r.byteLength,false),e.set(r,4),e}function oa(r){let e=new Uint8Array(0);return t=>{for(e=Ri(e,t);e.byteLength>=4;){let n=Pi(e,0);if(e.byteLength<4+n)break;r(e.slice(4,4+n)),e=e.slice(4+n);}}}function ra(r){return na.encode(JSON.stringify(r))}function sa(r){return JSON.parse(ia.decode(r))}function Zc(r){return Ii(ra(r))}function el(r,e={}){return oa(t=>{try{r(sa(t),t);}catch(n){if(e.onInvalidJson){e.onInvalidJson(n,t);return}throw n}})}function Ri(r,e){return w$1([r,e])}function Pi(r,e){return (r[e]<<24|r[e+1]<<16|r[e+2]<<8|r[e+3])>>>0}var Te=class{constructor(e,t){this.appTag=c$3(e),this.backend=t;}get tag(){return this.appTag}async waitForAuth(){return this.backend.waitForAuth()}get currentUser(){return this.backend.currentUser}getRtdbPresence(){let e=this.backend;return typeof e.getRtdbPresence=="function"?e.getRtdbPresence():e.rtdbPresence??null}onAuthChange(e){return this.backend.onAuthChange(e)}async signInAnonymously(){await this.backend.signInAnonymously();}async signInWithPluto(){if(typeof this.backend.signInWithPluto=="function"){await this.backend.signInWithPluto();return}await G().signInWithPluto();}async signOut(){await this.backend.signOut();}async stopAuthScopedActivity(){typeof this.backend.stopAuthScopedActivity=="function"&&await this.backend.stopAuthScopedActivity();}getRuntimeCapabilities(){return this.backend.getRuntimeCapabilities?.()}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n=true,i=300*1e3,o){await this.backend.updatePresence(e,t,n,i,o);}async setOffline(e){await this.backend.setOffline(e);}async cleanupStaleDevices(){await this.backend.cleanupStaleDevices();}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}async subscribeSessions(e,t){let i=(await this.backend.subscribeSessions(e)).getReader(),o=false;return (async()=>{try{for(;!o;){let{done:a,value:c}=await i.read();if(a)break;if(c)for(let l of c)"session"in l&&l.session&&await t(l.session);}}catch(a){o||console.error("[Signaling] Session stream error:",a);}})(),()=>{o=true,i.cancel();}}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async searchDevices(e){return this.backend.searchDevices(e)}async updateDevice(e,t){await this.backend.updateDevice(e,t);}async deleteDevice(e){await this.backend.deleteDevice(e);}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}notifyDisconnectRequested(e){typeof this.backend.notifyDisconnectRequested=="function"&&this.backend.notifyDisconnectRequested(e);}startPresenceLoop(e,t,n,i,o){this.backend.startPresenceLoop(e,t,n,i,o);}forceReconnectSnapshot(){this.backend.forceReconnectSnapshot();}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates=="function"?this.backend.getConnectionStates():[]}onConnectionStateChange(e){return typeof this.backend.onConnectionStateChange=="function"?this.backend.onConnectionStateChange(e):()=>{}}supportsRustPeerLifecycleProjection(){return typeof this.backend.listPeerSessions=="function"||typeof this.backend.getPeerSession=="function"||typeof this.backend.waitForSettledPeer=="function"||typeof this.backend.getConnectionStates=="function"}setWasmClient(e){let t=this.backend;t&&typeof t.setWasmClient=="function"&&t.setWasmClient(e);}};var ua=6e5,ga=250,ha=20,ma=100,kt=class{constructor(e){this.options=e;this.rtdbPresence=null;this.firestore=getFirestore(e.app);}setRtdbPresence(e){this.rtdbPresence=e;}watchMembers(e,t,n){let i=collection(this.firestore,`${this.getNamespaceRoot()}/rooms/${e}/members`);return this.rtdbPresence?this.watchMembersWithRtdb(e,t,i,n):this.watchMembersSnapshot(i,o=>{let s=Date.now(),a=o.docs.map(c=>this.toRoomMember(c)).filter(c=>!!c).filter(c=>c.nodeId!==t).filter(c=>!this.isExpired(c,s)).sort((c,l)=>c.joinedAt!==l.joinedAt?c.joinedAt-l.joinedAt:c.nodeId.localeCompare(l.nodeId));n(a);})}watchMembersWithRtdb(e,t,n,i){let o=this.rtdbPresence,s=this.getAppTag(),a=[],c={},l=()=>{let g=Date.now(),y=a.filter(m=>m.nodeId!==t).filter(m=>!this.isExpired(m,g)).filter(m=>{let v=c[m.nodeId];return !(v&&!v.online)}).sort((m,v)=>m.joinedAt!==v.joinedAt?m.joinedAt-v.joinedAt:m.nodeId.localeCompare(v.nodeId));i(y);},p=this.watchMembersSnapshot(n,g=>{a=g.docs.map(y=>this.toRoomMember(y)).filter(y=>!!y),l();}),u=o.onRoomPresenceChange(s,e,g=>{c=g,l();});return ()=>{p(),u();}}watchMembersSnapshot(e,t){let n=false,i=0,o=null,s=null,a=()=>{n||(s=onSnapshot(query(e,limit(ma)),c=>{i=0,t(c);},c=>{if(s=null,this.isTransientPermissionError(c)&&i<ha){i+=1,o=setTimeout(a,ga);return}console.warn("[BrowserFirestoreRooms] room watch failed:",c);}));};return a(),()=>{n=true,o&&(clearTimeout(o),o=null),s?.(),s=null;}}isTransientPermissionError(e){if(e?.code==="permission-denied")return true;let n=e instanceof Error?e.message:String(e);return /permission-denied|missing or insufficient permissions/i.test(n)}getNamespaceRoot(){let e=this.options.getRoomBackendTag().trim();if(!e)throw new Error("Room backend tag is required for browser room watches");return e.startsWith("space::")?`spaces/${e.slice(7)}`:`apps/${e}`}getAppTag(){return this.options.getRoomBackendTag().trim()}toRoomMember(e){let t=e.data(),n=typeof t.nodeId=="string"&&t.nodeId.trim().length>0?t.nodeId.trim():e.id,i=typeof t.ticket=="string"?t.ticket:"";return {nodeId:n,userId:typeof t.userId=="string"?t.userId:"",ticket:i,joinedAt:this.toMillis(t.joinedAt)??0,lastSeenAt:this.toMillis(t.lastSeenAt)??0,expiresAt:this.toMillis(t.expiresAt)}}isExpired(e,t){if(typeof e.expiresAt=="number")return e.expiresAt<=t;let n=e.lastSeenAt||e.joinedAt||0;return n>0&&n+ua<=t}toMillis(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Number(e);if(Number.isFinite(t))return t;let n=Date.parse(e);return Number.isNaN(n)?void 0:n}if(e instanceof Date)return e.getTime();if(e&&typeof e=="object"&&typeof e.toMillis=="function")try{return e.toMillis()}catch{return}}};function qo(r){return {get wasmClient(){return r.wasmClient},get roomCreationMode(){return r.roomCreationMode},get appLimits(){return r.appLimits},ensureAuthenticated:e=>r.ensureAuthenticated(e),getTicketWithToken:(e,t)=>r.getTicketWithToken(e,t),getNodeId:()=>r.getNodeId(),connect:(e,t)=>r.connect(e,t),refreshHostedAppSettings:e=>r.refreshHostedAppSettings(e),usesDirectRoomBackend:()=>r.usesDirectRoomBackend(),getRoomBackendTag:()=>r.getRoomBackendTag()}}var Le=class{constructor(e,t){this.heartbeatStops=new Map;this.browserRooms=null;this.rtdbPresence=null;this.client=e,this.signaling=t;}getBrowserRooms(){return this.browserRooms||(this.browserRooms=new kt({app:G().getApp(),getRoomBackendTag:()=>this.client.getRoomBackendTag()})),this.rtdbPresence&&this.browserRooms&&this.browserRooms.setRtdbPresence(this.rtdbPresence),this.browserRooms}setRtdbPresence(e){this.rtdbPresence=e,this.browserRooms&&this.browserRooms.setRtdbPresence(e);}syncRtdbPresenceFromSignaling(){if(this.rtdbPresence)return;let e=this.signaling.getRtdbPresence();if(e){this.setRtdbPresence(e);return}try{this.setRtdbPresence(new e$1(G().getApp()));}catch{}}usesDirectRoomBackend(){return this.client.usesDirectRoomBackend()}get roomBackendTag(){return this.client.getRoomBackendTag()}resolveRoomUserId(e){return G().getCurrentUser?.()?.uid??this.signaling.currentUser?.id??e??"anonymous"}get appTag(){return this.signaling.tag}async invokeRoomCallable(e,t){let{getFunctions:n,httpsCallable:i}=await import('firebase/functions'),o=n(G().getApp());return (await i(o,e)(t)).data}isAlreadyExistsError(e){if(!e||typeof e!="object")return false;let t="code"in e&&typeof e.code=="string"?e.code:"",n="message"in e&&typeof e.message=="string"?e.message:"";return t.includes("already-exists")||n.toLowerCase().includes("already exists")}normalizeRoomId(e){return e.trim().toUpperCase()}async getMembersInternal(e,t){if(!this.client.wasmClient)throw new Error("WASM Client not loaded");let n=t??await this.client.getNodeId(),i=await this.client.wasmClient.get_members(e,n,this.roomBackendTag);return this.parseMemberDocuments(i)}parseMemberDocuments(e){return JSON.parse(e).map(n=>this.parseRoomMemberDocument(n))}parseRoomMemberDocument(e){let t=e.fields;return {nodeId:t.nodeId?.stringValue||e.name.split("/").pop(),userId:t.userId?.stringValue,ticket:t.ticket?.stringValue,joinedAt:t.joinedAt?.integerValue?parseInt(t.joinedAt.integerValue):void 0,lastSeenAt:t.lastSeenAt?.integerValue?parseInt(t.lastSeenAt.integerValue):void 0,expiresAt:t.expiresAt?.integerValue?parseInt(t.expiresAt.integerValue):void 0}}async createRoom(e){if(await this.client.ensureAuthenticated("room-op"),!this.client.wasmClient)throw new Error("WASM Client not loaded");this.syncRtdbPresenceFromSignaling();let t=await this.client.getNodeId(),n=this.resolveRoomUserId(t);if(!this.usesDirectRoomBackend()){if(await this.client.refreshHostedAppSettings(),this.client.roomCreationMode==="server-only")throw new Error("This app uses server-only room creation. Create the room on your backend with your sk_live_... key, then call joinRoom(roomId) on the client.");let c="",l=false,p=typeof e=="string"&&e.trim().length>0?e.trim().toUpperCase():"",u=p?1:3;for(let g=0;g<u;g+=1){if(p)c=p;else {let m=new Uint8Array(6);crypto.getRandomValues(m),c=Array.from(m,v=>v.toString(36).padStart(2,"0")).join("").substring(0,6).toUpperCase();}let y=await this.client.getTicketWithToken(`room:${c}`,0);try{await this.invokeRoomCallable("createClientRoom",{appTag:this.appTag,roomId:c,nodeId:t,ticket:y}),l=!0;break}catch(m){if(this.isAlreadyExistsError(m)){if(p)throw m;continue}throw m}}if(!l)throw new Error(p?`Failed to create requested room "${p}".`:"Failed to create room after multiple attempts (ID collisions).");return await this.registerRtdbRoomMember(c,t),c}let i="",o=false,s=typeof e=="string"&&e.trim().length>0?e.trim().toUpperCase():"",a=s?1:3;for(let c=0;c<a;c++){if(s)i=s;else {let u=new Uint8Array(6);crypto.getRandomValues(u),i=Array.from(u,g=>g.toString(36).padStart(2,"0")).join("").substring(0,6).toUpperCase();}let l=await this.client.getTicketWithToken(`room:${i}`,0);await this.client.refreshHostedAppSettings();let p=this.client.appLimits.maxMembersPerRoom>=0?this.client.appLimits.maxMembersPerRoom:50;if(o=await this.client.wasmClient.create_room(i,n,l,t,this.roomBackendTag,p),o){console.log(`Room created: ${i}`);break}else {if(s)throw new Error(`Room "${i}" already exists.`);console.log(`Collision for roomId ${i}, retrying...`);}}if(!o)throw new Error(s?`Failed to create requested room "${s}".`:"Failed to create room after multiple attempts (ID collisions).");return await this.registerRtdbRoomMember(i,t),i}async joinRoom(e,t={}){if(await this.client.ensureAuthenticated("room-op"),!this.client.wasmClient)throw new Error("WASM Client not loaded");if(this.syncRtdbPresenceFromSignaling(),typeof e!="string"||e.length===0||e.length>64)throw new Error("roomId must be a non-empty string of at most 64 characters");if(e!=="demo"&&!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error("roomId must contain only alphanumeric characters, hyphens, or underscores");let n=await this.client.getNodeId(),i=this.resolveRoomUserId(n),o=this.normalizeRoomId(e),s=await this.client.getTicketWithToken(`room:${o}`,0);console.log("[RoomManager] joinRoom request",{roomId:e,normalizedId:o,targetRoomId:o,tag:this.roomBackendTag,userId:i,myNodeId:n,hasTicket:!!s,ticketLength:s?.length||0});try{this.usesDirectRoomBackend()?await this.client.wasmClient.join_room(o,i,s,n,this.roomBackendTag):(await this.client.refreshHostedAppSettings(),await this.invokeRoomCallable("joinClientRoom",{appTag:this.appTag,roomId:o,nodeId:n,ticket:s})),console.log(`Joined room: ${o}`);}catch(c){throw c$1("[RoomManager] joinRoom failed",c),c}let a=[];if(t.bootstrapPeers!==false){let l=(await this.getMembersInternal(o,n)).map(async u=>{let g=false,y=Date.now();if(u.expiresAt)u.expiresAt<y&&(g=true);else {let m=u.lastSeenAt||u.joinedAt||0;y-m>300*1e3&&(g=true);}if(g)return null;if(u.ticket)try{console.log(`Bootstrapping: Connecting to peer ${u.nodeId}...`);let m=await this.client.connect(u.ticket,5e3);return m.send({type:"chat",text:`Use ${i} joined the room.`}).catch(v=>{c$1("[RoomManager] join notification send skipped",{roomId:o,peerNodeId:u.nodeId,error:v});}),m}catch(m){return console.warn(`Failed to connect to peer ${u.nodeId}:`,m),null}return null});(await Promise.allSettled(l)).forEach(u=>{u.status==="fulfilled"&&u.value&&a.push(u.value);});}return await this.registerRtdbRoomMember(o,n),a}async leaveRoom(e){this.usesDirectRoomBackend()||await this.client.ensureAuthenticated("room-op");let t=await this.client.getNodeId();if(!t)return;console.log(`Leaving room ${e}...`),await this.markRtdbRoomMemberOffline(e,t),this.stopHeartbeat(e);let n=this.normalizeRoomId(e);try{this.usesDirectRoomBackend()?await this.client.wasmClient.leave_room(n,t,this.roomBackendTag):await this.invokeRoomCallable("leaveClientRoom",{appTag:this.appTag,roomId:n,nodeId:t}),console.log(`Left room: ${n}`);}catch(i){throw console.warn("Leave room failed:",i),i}}async getRoomMembers(e){await this.client.ensureAuthenticated("room-op");let t=this.normalizeRoomId(e);return this.getMembersInternal(t)}watchRoom(e,t){let n=false,i=null;return (async()=>{try{if(await this.client.ensureAuthenticated("room-op"),n)return;let o=this.normalizeRoomId(e),s=await this.client.getNodeId();if(n)return;i=this.getBrowserRooms().watchMembers(o,s,t),n&&(i(),i=null);}catch(o){n||console.warn("[RoomManager] watchRoom listener failed:",o);}})(),()=>{n=true,i?.(),i=null;}}async registerRtdbRoomMember(e,t){if(this.stopHeartbeat(e),this.rtdbPresence){let n=this.roomBackendTag;try{await this.rtdbPresence.registerRoomMember(n,e,t);}catch(i){throw new Error(`[RoomManager] RTDB room member register failed for ${e}: ${i instanceof Error?i.message:String(i)}`)}this.heartbeatStops.set(e,()=>{this.markRtdbRoomMemberOffline(e,t);});}else throw new Error(`[RoomManager] RTDB presence is required for room liveness (${e}); legacy Firestore heartbeat is disabled`)}async markRtdbRoomMemberOffline(e,t){if(!this.rtdbPresence)return;let n=this.roomBackendTag;try{await this.rtdbPresence.markRoomMemberOffline(n,e,t);}catch(i){console.warn("[RoomManager] RTDB markRoomMemberOffline failed:",i);}}stopHeartbeat(e){if(typeof e=="string"){let t=this.heartbeatStops.get(e);t&&(t(),this.heartbeatStops.delete(e),console.log(`Heartbeat stopped for room ${e}.`));return}for(let[t,n]of this.heartbeatStops.entries())n(),console.log(`Heartbeat stopped for room ${t}.`);this.heartbeatStops.clear();}};function fa(r,e){let t=r.trim();if(!t)throw new Error("Channel envelope requires a non-empty channel id.");let n=new TextEncoder,i=n.encode(t),o=e?n.encode(JSON.stringify(e)):new Uint8Array(0),s=new Uint8Array(6+i.byteLength+o.byteLength),a=new DataView(s.buffer);return s[0]=127,s[1]=1,a.setUint16(2,i.byteLength,false),a.setUint16(4,o.byteLength,false),s.set(i,6),s.set(o,6+i.byteLength),s}function Ko(r,e,t){let n=fa(e,t),i=r.getWriter(),o=false,s=async()=>{o||(o=true,await i.write(n));};return new WritableStream({write:async a=>{await s(),await i.write(a);},close:async()=>{await s();try{await i.close();}finally{i.releaseLock();}},abort:async a=>{try{await i.abort(a);}finally{i.releaseLock();}}})}var _i=[0,300,600,1e3,1500,2e3,2500,3e3,3500,3500,3500,3500,3500,3500,3500],zo=2e3,Nt=0,Dt="main",Mt=64,Qo=4*1024*1024,$o=1,Vo="openrtc:native-main-message",Yo=15e3,Jo=16,Xo=3e4,Zo=250,er=250,tr=2e3,nr=600,ir=2e3,or=120,rr=1e3,sr=6e4,wi="system/peer-default",ya="share/explicit-file",va="share/explicit-control",ar=[{id:wi,kind:"system",ownership:"shared",peerModel:"device-first",routing:"session-default",readiness:"settled-peer",promotionPolicy:"eligible",signalingPolicy:"hosted",description:"Default trusted device/runtime traffic"},{id:ya,kind:"share",ownership:"shared",peerModel:"anonymous-ticket",routing:"stream-envelope",readiness:"transport-only",promotionPolicy:"never",signalingPolicy:"ticket-only",description:"Explicit file transfer channel for share/ticket traffic"},{id:va,kind:"share",ownership:"shared",peerModel:"anonymous-ticket",routing:"stream-envelope",readiness:"transport-only",promotionPolicy:"never",signalingPolicy:"ticket-only",description:"Explicit control channel for share/ticket traffic"}];function cr(r){return {get registry(){return r.getRegistry()},get wasmClient(){return r.getWasmClient()},get node(){return r.getNode()},get discoveryMode(){return r.getDiscoveryMode()},get localNodeId(){return r.getLocalNodeId()},get deviceId(){return r.getDeviceId()},registerDisposer:e=>r.registerDisposer(e)}}var lr="openrtc:endpoint-ticket:v1";function se(r){let e=r.lastIndexOf(".");return {irohTicket:e>=0?r.slice(0,e):r,tokenSuffix:e>=0?r.slice(e+1):null}}function dr(){return pr(24)}function Et(r,e,t,n,i){return `${r}.${Ca(r,e,t,n,i)}`}function ue(r,e){let t=ba(e);return !t||!Sa(r,t)?null:t}function Ca(r,e,t,n,i){return btoa(JSON.stringify({t:e,s:t,m:n,h:ur(r),...typeof i=="number"?{e:i}:{},a:lr,n:Ia()})).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ba(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return JSON.parse(atob(e+"=".repeat(t)))}catch{return null}}function Sa(r,e){return !(typeof e.h=="string"&&e.h!==ur(r)||typeof e.e=="number"&&Number.isFinite(e.e)&&e.e<=Date.now()||typeof e.a=="string"&&e.a!==lr||typeof e.n=="string"&&!Ra(e.n))}function Ia(){return pr(16)}function pr(r){let e=new Uint8Array(r);return crypto.getRandomValues(e),btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ra(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return atob(e+"=".repeat(t)).length===16}catch{return false}}function le(r,e){return r>>>e|r<<32-e}var Pa=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function ur(r){let e=new TextEncoder().encode(r),t=e.length*8,n=e.length+1;for(;n%64!==56;)n+=1;let i=new Uint8Array(n+8);i.set(e),i[e.length]=128;let o=new DataView(i.buffer);o.setUint32(n,Math.floor(t/4294967296),false),o.setUint32(n+4,t>>>0,false);let s=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],a=new Array(64);for(let c=0;c<i.length;c+=64){for(let I=0;I<16;I+=1)a[I]=o.getUint32(c+I*4,false);for(let I=16;I<64;I+=1){let k=le(a[I-15],7)^le(a[I-15],18)^a[I-15]>>>3,T=le(a[I-2],17)^le(a[I-2],19)^a[I-2]>>>10;a[I]=a[I-16]+k+a[I-7]+T>>>0;}let[l,p,u,g,y,m,v,S]=s;for(let I=0;I<64;I+=1){let k=le(y,6)^le(y,11)^le(y,25),T=y&m^~y&v,D=S+k+T+Pa[I]+a[I]>>>0,_=le(l,2)^le(l,13)^le(l,22),E=l&p^l&u^p&u,A=_+E>>>0;S=v,v=m,m=y,y=g+D>>>0,g=u,u=p,p=l,l=D+A>>>0;}s[0]=s[0]+l>>>0,s[1]=s[1]+p>>>0,s[2]=s[2]+u>>>0,s[3]=s[3]+g>>>0,s[4]=s[4]+y>>>0,s[5]=s[5]+m>>>0,s[6]=s[6]+v>>>0,s[7]=s[7]+S>>>0;}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var xt=class{constructor(e,t,n){this.ctx=e;this.options=t;this.deps=n;this.appliedAuthSessionToken=null;this.authSyncUnsubscribe=null;this.authRefreshInterval=null;this.publicAuthChangeUnsubscribes=new Set;this.lastWasmAuthSyncUserId=null;this.lastWasmAuthSyncToken=null;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(this.disposed)return;this.disposed=true;let e=this.authSyncUnsubscribe;if(this.authSyncUnsubscribe=null,e)try{e();}catch(n){console.warn("[Client][WASM-AUTH] auth-change unsubscribe failed",n);}let t=this.authRefreshInterval;this.authRefreshInterval=null,t&&clearInterval(t);for(let n of Array.from(this.publicAuthChangeUnsubscribes))try{n();}catch(i){console.warn("[Client][AUTH] public auth-change unsubscribe failed",i);}this.publicAuthChangeUnsubscribes.clear();}assertActive(){if(this.disposed)throw new Error("[Client][AUTH] Auth coordinator is disposed")}isSpaceWithSpaceKey(){let e=this.options.spaceKey??this.options.space;return (this.options.discoveryMode===void 0||this.options.discoveryMode==="space")&&typeof e=="string"&&e.trim().length>0}async ensureAuthenticated(e){if(this.assertActive(),this.deps.usesTicketOnlySignalingMode())return;let t=this.options.authMode??"anonymous",n=e!=="discovery";if(this.isSpaceWithSpaceKey()){let l=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",p=this.options.spaceKey??this.options.space,u=typeof p=="string"?p.trim():"",g=l&&u?await b$3(l,u).catch(()=>null):null;if(this.assertActive(),G().getCurrentUser()){let k=await G().getIdToken({forceRefresh:false}).catch(()=>null);this.assertActive();let T=a$2(k);if(g&&c$4(T,g)){await E(this.deps.waitForAuth(),5e3),this.assertActive(),n&&d$2(`[Client][AUTH] Space scoped token already authenticated (${e})`);return}n&&d$2("[Client][AUTH] Existing Firebase user is not scoped to this space; minting scoped token",{reason:e,expectedNamespaceId:g?.slice(0,12)??null,actualNamespaceId:b$4(T,"namespaceId")?.slice(0,12)??null});}let m=this.options.spaceTokenProvider;if(!m)throw new Error("[Client][AUTH] space discovery requires spaceTokenProvider (use spaceToken for static sites)");let v=await m(),S=typeof v?.customToken=="string"?v.customToken.trim():"";if(!S)throw new Error("[Client][AUTH] spaceTokenProvider returned no customToken");this.assertActive(),await G().signInWithCustomTokenValue(S),this.assertActive(),await E(this.deps.waitForAuth(),5e3),this.assertActive();let I=await G().getIdToken({forceRefresh:true}).catch(()=>null);this.assertActive(),this.setWasmAuthToken(I??S,I?"space-id-token":"space-token"),this.assertActive(),n&&d$2(`[Client][AUTH] Space scoped token authenticated (${e})`);return}let o=typeof this.options.sessionToken=="string"?this.options.sessionToken.trim():"";if(o&&this.appliedAuthSessionToken!==o){this.assertActive(),await G().signInWithCustomTokenValue(o),this.assertActive(),this.appliedAuthSessionToken=o,await E(this.deps.waitForAuth(),5e3),this.assertActive(),n&&d$2(`[Client][AUTH] Session token authenticated (${e})`);return}try{await E(this.deps.waitForAuth(),5e3);}catch(l){this.assertActive(),n&&console.warn(`[Client][AUTH] waitForAuth timed out (${e})`,l);}this.assertActive();let s=this.deps.getCurrentUser(),a=s?.id??s?.uid??null,c=this.options.discoveryMode==="user-scoped"&&typeof a=="string"&&a.startsWith("space_");if(s&&!c){n&&d$2(`[Client][AUTH] Authenticated (${e}) as ${a??"current-user"}`);return}if(c&&n&&d$2("[Client][AUTH] Ignoring space-scoped user for anonymous user-scoped discovery"),t==="external"||t==="required")throw new Error(`[Client][AUTH] ${t} auth mode requires host-provided auth before ${e}`);n&&d$2(`[Client][AUTH] No user (${e}); attempting anonymous sign-in...`),await E(this.deps.signInAnonymously(),8e3),this.assertActive();try{await E(this.deps.waitForAuth(),5e3);}catch{}if(this.assertActive(),!this.deps.getCurrentUser())throw new Error("[Client][AUTH] Anonymous sign-in did not produce an authenticated user");n&&d$2(`[Client][AUTH] Anonymous sign-in success (${e})`);}setWasmAuthToken(e,t){let n=this.ctx.wasmClient;if(!n||typeof n.set_auth_token!="function"){console.warn("[Client][WASM-AUTH] WasmClient.set_auth_token is unavailable");return}let i=e?"token":null;this.lastWasmAuthSyncUserId===i&&this.lastWasmAuthSyncToken===e||(this.lastWasmAuthSyncUserId=i,this.lastWasmAuthSyncToken=e,d$2(`[Client][WASM-AUTH] Sync token (${t}) hasToken=${!!e} tokenLen=${e?.length??0}`),n.set_auth_token(e));}installAuthTokenSync(){if(this.disposed||this.isSpaceWithSpaceKey()||this.authSyncUnsubscribe)return;let e=this.deps.onAuthChange(()=>{this.disposed||this.syncAuthTokenToWasm("auth-change").catch(t=>{this.disposed||console.warn("[Client][WASM-AUTH] Failed syncing auth token on auth change:",t);});});this.authSyncUnsubscribe=e,this.authRefreshInterval||(this.authRefreshInterval=setInterval(()=>{this.disposed||this.syncAuthTokenToWasm("periodic-refresh",true).catch(t=>{this.disposed||console.warn("[Client][WASM-AUTH] Periodic auth refresh sync failed:",t);});},600*1e3));}async syncAuthTokenToWasm(e,t=false){if(this.disposed||this.isSpaceWithSpaceKey())return;let n=this.deps.getCurrentUser(),i=n&&n.getToken?await n.getToken(t):null;if(this.disposed)return;let o=!!i,s=i?.length||0,a=n?.id||null;this.lastWasmAuthSyncUserId===a&&this.lastWasmAuthSyncToken===i||(d$2(`[Client][WASM-AUTH] Sync token (${e}) hasToken=${o} tokenLen=${s} uid=${a||"none"} forceRefresh=${t}`),!this.disposed&&this.setWasmAuthToken(i,e));}async refreshRuntimeAuthToken(e="runtime-start"){this.disposed||this.deps.usesTicketOnlySignalingMode()||(await this.ensureAuthenticated("discovery"),!this.disposed&&(this.isSpaceWithSpaceKey()||await this.syncAuthTokenToWasm("auth-change",e==="managed-session")));}get currentUser(){return this.deps.getCurrentUser()}onAuthChange(e){if(this.disposed)return ()=>{};let t=true,n=this.deps.onAuthChange(o=>{!t||this.disposed||e(o);}),i=()=>{if(t){t=false;try{n();}finally{this.publicAuthChangeUnsubscribes.delete(i);}}};return this.publicAuthChangeUnsubscribes.add(i),i}async signInAnonymously(){return this.assertActive(),this.deps.signInAnonymously()}async signInWithPluto(){return this.assertActive(),this.deps.signInWithPluto()}async signOut(){if(!this.disposed&&(this.deps.beforeSignOut(),await this.deps.stopAuthScopedActivity(),!this.disposed))return this.deps.signOut()}};var Lt=class{constructor(e,t){this.ctx=e;this.deps=t;this.devicesById=new Map;this.deviceIdsByNodeId=new Map;this.activeScanningStops=new Set;this.activeSubscriptionStops=new Set;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(!this.disposed){this.disposed=true;for(let e of Array.from(this.activeScanningStops))try{e();}catch(t){console.warn("[Client] active device scanning unsubscribe failed",t);}this.activeScanningStops.clear();for(let e of Array.from(this.activeSubscriptionStops))try{e();}catch(t){console.warn("[Client] device directory subscription unsubscribe failed",t);}this.activeSubscriptionStops.clear();}}get byIdMap(){return this.devicesById}set byIdMap(e){this.devicesById=e instanceof Map?e:new Map;}get byNodeIdMap(){return this.deviceIdsByNodeId}set byNodeIdMap(e){this.deviceIdsByNodeId=e instanceof Map?e:new Map;}remember(e){if(!this.disposed&&e?.deviceId){if(this.devicesById.set(e.deviceId,e),typeof e.nodeId=="string"&&e.nodeId.trim()){let t=e.nodeId.trim();this.deviceIdsByNodeId.set(t,e.deviceId);}this.deps.onDeviceRemembered(e);}}getKnownDevice(e,t){let n=typeof e=="string"?e.trim():"";if(n){let o=this.devicesById.get(n);if(o)return o}let i=typeof t=="string"?t.trim():"";if(i){let o=this.deviceIdsByNodeId.get(i);if(o)return this.devicesById.get(o)??null}return null}getKnownDeviceIdForNode(e){let t=typeof e=="string"?e.trim():"";return t?this.deviceIdsByNodeId.get(t)??null:null}getKnownDeviceNodeId(e){let t=typeof e=="string"?e.trim():"";return t&&this.devicesById.get(t)?.nodeId?.trim()||null}rememberKnownDeviceForNode(e,t){if(this.disposed)return;let n=e.trim(),i=t.trim();!n||!i||this.deviceIdsByNodeId.set(n,i);}getKnownDevicePlatform(e,t){let n=this.getKnownDevice(e,t),i=typeof n?.platformType=="string"?n.platformType:typeof n?.platform_type=="string"?n.platform_type:null;return i?String(i).trim().toLowerCase():null}async refreshKnownDeviceCache(){if(this.disposed||!this.deps.requiresManagedTransportTrust())return;let e=await this.searchDevices().catch(()=>[]);this.disposed||e.forEach(t=>this.remember(t));}async searchDevices(){if(this.disposed)return [];if(await this.deps.ensureSignalingReadyForDiscovery("search"),this.disposed)return [];let e=await this.deps.searchDevices();return this.disposed?[]:(e.forEach(t=>{this.remember(t),this.deps.applyDiscoveredDevice(t);}),e)}async updateDevice(e,t){this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("search"),!this.disposed&&await this.deps.updateDevice(e,t));}async deleteDevice(e){this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("search"),!this.disposed&&await this.deps.deleteDevice(e));}async cleanupStaleDevices(){this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("search"),!this.disposed&&await this.deps.cleanupStaleDevices());}onDevicesChange(e){if(this.disposed)return ()=>{};let t=true,n=null,i=()=>{if(!(!t&&!n)){if(t=false,n)try{n();}finally{n=null;}this.activeSubscriptionStops.delete(i);}};return this.activeSubscriptionStops.add(i),(async()=>{await this.deps.ensureSignalingReadyForDiscovery("watch"),!(!t||this.disposed)&&(n=this.deps.onDevicesChange(o=>{!t||this.disposed||(o.forEach(s=>{this.remember(s),this.deps.applyDiscoveredDevice(s);}),e(o));}),(!t||this.disposed)&&i());})().catch(o=>{if(!(!t||this.disposed)){console.warn("[Client] Failed to initialize onDevicesChange listener:",o);try{e([]);}finally{i();}}}),i}async subscribeSessions(e,t){if(this.disposed)return ()=>{};if(await this.deps.ensureSignalingReadyForDiscovery("sessions"),this.disposed)return ()=>{};let n=true,i=await this.deps.subscribeSessions(e,s=>{if(n&&!this.disposed)return t(s)});if(this.disposed)return i(),()=>{};let o=()=>{if(n){n=false;try{i();}finally{this.activeSubscriptionStops.delete(o);}}};return this.activeSubscriptionStops.add(o),o}async startScanningLoop(e){if(this.disposed)return {stop:()=>{}};let t=new Set,n=false,i=null,o=null,s=e.localDeviceId;try{let c=await this.deps.getLocalDeviceId();if(this.disposed)return {stop:()=>{}};c&&(s=c);}catch{}i=this.onDevicesChange(c=>{n||this.disposed||e.onDevices?.(c);});let a=()=>{n=true,i&&(i(),i=null),o&&(o(),o=null),this.activeScanningStops.delete(a);};this.activeScanningStops.add(a);try{(e.onIncomingSession||e.acceptIncomingSession)&&(o=await this.subscribeSessions(s,async c=>{if(n||this.disposed)return;let l=c.sessionId||c.connectionId;if(!(!l||t.has(l))&&c.targetDeviceId===s&&c.initiatorDeviceId!==s&&!(c.state==="connected"||c.state==="closed"||c.state==="failed")){t.add(l);try{if(this.disposed)return;if(e.onIncomingSession){await e.onIncomingSession(c);return}(this.deps.getPeerStatus(c.initiatorDeviceId)==="connected"||e.isConnected?.(c.initiatorDeviceId))&&(this.deps.hasPeerScopes(c.initiatorDeviceId)||(e.hasProtectedConnectionIntent?.(c.initiatorDeviceId)??!1)||await this.deps.forceDisconnectPeer(c.initiatorDeviceId).catch(async()=>{await e.cleanupStaleConnection?.(c.initiatorDeviceId);})),c.initiatorNodeId&&await e.allowIncomingNodeId?.(c.initiatorNodeId);let u=await e.acceptIncomingSession?.(l,c.initiatorDeviceId);if(!u?.success)throw new Error(u?.error||"Failed to accept incoming signaling session");await e.onIncomingSessionAccepted?.(c);}catch(p){throw t.delete(l),p}}}));}catch(c){throw a(),c}return {stop:a}}};var Ft=class{constructor(e,t,n){this.ctx=e;this.options=t;this.deps=n;this.managedPresenceGrant=null;this.disposed=false;this.activePresenceDescriptor=null;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(this.disposed)return;this.disposed=true,this.managedPresenceGrant=null;let e=this.activePresenceDescriptor;this.activePresenceDescriptor=null,!(!e||!this.ctx.localNodeId)&&this.markOfflineDuringDispose(this.ctx.localNodeId);}markOfflineDuringDispose(e){let t=n=>{console.warn("[Client][PRESENCE] failed to mark offline during dispose",n);};try{Promise.resolve(this.deps.setOffline(e)).catch(t);}catch(n){t(n);}}assertActive(){if(this.disposed)throw new Error("[Client][PRESENCE] Presence controller is disposed")}resolvePresenceUserId(){let e=(this.options.discoveryMode===void 0||this.options.discoveryMode==="space")&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0;return this.deps.getCurrentUser()?.id??(e?this.ctx.localNodeId:null)}startSignalingPresenceLoop(e){if(this.disposed)return;let t=this.activePresenceDescriptor,n=(t?.metadata??"")===(e.metadata??"");t&&t.userId===e.userId&&t.nodeId===e.nodeId&&t.deviceName===e.deviceName&&t.ticket===e.ticket&&n||(this.deps.startPresenceLoop(e.userId,e.nodeId,e.deviceName,e.ticket,e.metadata),this.activePresenceDescriptor=e);}notifySignalingBackendChanged(){this.activePresenceDescriptor=null;}setManagedPresenceTicket(e){if(this.disposed)return;let t=e?.trim()||"";if(!t){this.managedPresenceGrant=null;return}let{irohTicket:n,tokenSuffix:i}=this.deps.splitCompoundTicket(t),o=i?this.deps.decodeCompoundTicketPayload(n,i):null;if(!o?.t||!o?.s)throw new Error("Managed presence ticket must be a compound ticket with an embedded token payload");this.managedPresenceGrant={scope:o.s,token:o.t,maxConnections:typeof o.m=="number"?o.m:0,compoundTicket:t,irohTicket:n};let s=this.ctx.wasmClient;s&&typeof s.register_session_token=="function"&&s.register_session_token(o.t,o.s,typeof o.m=="number"?o.m:0);}clearManagedPresenceTicket(){this.managedPresenceGrant=null;}async resolvePresenceTicket(e){this.assertActive();let t=e?.trim();if(t)return t;if(this.managedPresenceGrant)return this.refreshManagedPresenceTicketIfNeeded();let n=this.options.ticket?.trim();return n||this.deps.getTicket()}async refreshManagedPresenceTicketIfNeeded(){let e=this.managedPresenceGrant;if(!e)return this.deps.getTicket();let t=e.irohTicket;try{t=await this.deps.getTicket();}catch{return e.compoundTicket}if(t===e.irohTicket)return e.compoundTicket;let n=this.ctx.wasmClient;if(n&&typeof n.endpoint_ticket_with_token=="function"){let i=n.endpoint_ticket_with_token.bind(n),o=await d$3(()=>i(e.scope,e.maxConnections),{isActive:()=>!this.disposed}),{irohTicket:s,tokenSuffix:a}=this.deps.splitCompoundTicket(o),c=a?this.deps.decodeCompoundTicketPayload(s,a):null;return e.irohTicket=s,e.compoundTicket=o,c?.t&&c?.s&&(e.token=c.t,e.scope=c.s,e.maxConnections=typeof c.m=="number"?c.m:0),c$1("[Client][PRESENCE] reminted managed compound ticket through Rust",{grantScope:e.scope}),e.compoundTicket}if(e.scope==="user-device")throw new Error("Managed user-device presence refresh requires Rust/WASM endpoint_ticket_with_token support.");return e.irohTicket=t,e.compoundTicket=this.deps.buildCompoundTicketWithPayload(t,e.token,e.scope,e.maxConnections),c$1("[Client][PRESENCE] rebuilt managed compound ticket after endpoint change",{grantScope:e.scope}),e.compoundTicket}async startPresenceLoop(e){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let t=this.ctx.localNodeId;if(!t)throw new Error("startPresenceLoop requires an initialized node");let n=this.resolvePresenceUserId();if(!n)throw new Error("startPresenceLoop requires an authenticated user");let i=await this.resolvePresenceTicket(e?.ticket);if(this.assertActive(),!i||!i.trim())throw new Error("startPresenceLoop requires a valid endpoint ticket");this.startSignalingPresenceLoop({userId:n,nodeId:t,deviceName:e?.deviceName||this.options.deviceName||"Unknown Device",ticket:i,metadata:e?.metadata}),this.deps.syncRoomRtdbPresence();}async startPresenceLoopForListen(){if(this.disposed)return;let e=this.ctx.localNodeId,t=this.resolvePresenceUserId();if(!t||!e)return;let n=await this.resolvePresenceTicket();this.disposed||this.startSignalingPresenceLoop({userId:t,nodeId:e,deviceName:this.options.deviceName||"Unknown Device",ticket:n,metadata:""});}async setOffline(){this.disposed||(this.activePresenceDescriptor=null,this.ctx.localNodeId&&await this.deps.setOffline(this.ctx.localNodeId));}async updatePresence(e=true,t=3e5,n,i){if(this.disposed||!this.ctx.wasmClient)return;let o=(this.options.discoveryMode===void 0||this.options.discoveryMode==="space")&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0;if(o&&(await this.deps.ensureAuthenticated("discovery"),this.disposed)||!this.deps.getCurrentUser()?.id&&!o)return;let a=this.ctx.localNodeId;if(!a)return;let c=await this.resolvePresenceTicket(i);if(this.disposed)return;if(!c||!c.trim())throw new Error("updatePresence requires a valid endpoint ticket");let l=n,p=await this.deps.getLocalDeviceId()||this.ctx.deviceId;if(this.disposed)return;if(!p)throw new Error("updatePresence requires a stable local device ID");try{let g=n?JSON.parse(n):{};g.deviceId||(g.deviceId=p,l=JSON.stringify(g));}catch{l=JSON.stringify({deviceId:p,rawMetadata:n});}let u=await j$1(l);await this.deps.updatePresence(a,c,e,t,u);}};var Bt=class{constructor(e,t){this.ctx=e;this.deps=t;this.hostedAppSettingsLoaded=false;this.backendConnectionStateUnsubscribe=null;this.signalingBackend=null;this.subscriptionGeneration=0;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}async refreshHostedAppSettings(e=false){if(!(this.disposed||this.deps.usesTicketOnlySignalingMode())&&!(this.hostedAppSettingsLoaded&&!e))try{let{getFunctions:t,httpsCallable:n}=await import('firebase/functions');if(this.disposed)return;let i=t(G().getApp()),s=await n(i,"validateApiKey")({apiKey:this.deps.getApiKey()});if(this.disposed)return;let a=s.data;a.warning&&console.warn("[pluto-rtc]",a.warning),this.deps.setAppLimits(a.limits),a.discoveryMode&&this.deps.setDiscoveryMode(a.discoveryMode),this.deps.setRoomCreationMode(a.roomCreationMode??((this.deps.getOptions().discoveryMode??"space")==="space"?"client-open":"client-auth")),this.hostedAppSettingsLoaded=!0;}catch(t){if(this.disposed)return;console.warn("[pluto-rtc] Could not fetch hosted app settings, using local defaults.",t);}}setSignalingBackend(e){if(this.disposed)return;this.disposeBackendConnectionSubscription();let t=this.subscriptionGeneration,n=this.deps.getCurrentSignaling();this.deps.stopRoomLiveness(),this.stopAuthScopedActivityBestEffort(n);let i=this.deps.createSignaling(e);this.signalingBackend=e,this.deps.installBackend(i,e),this.deps.onSignalingBackendChanged(),this.syncRoomRtdbPresenceFromBackend();let o=e.setCoreClient;typeof o=="function"&&o.call(e,this.deps.getCoreClientHost());try{e.checkForSSOToken();}catch(a){console.warn("[Client] backend SSO token check failed:",a);}b$2("[Client] subscribing to backend connection state changes",{backendType:e?.constructor?.name??"unknown",hasGetConnectionStates:typeof e.getConnectionStates=="function",hasOnConnectionStateChange:typeof e.onConnectionStateChange=="function"});let s;try{s=i.onConnectionStateChange(a=>{this.disposed||t!==this.subscriptionGeneration||(this.deps.onBackendConnectionState(a),this.schedulePeerReconciliationBestEffort("backend-state"));});}catch(a){if(this.disposed||t!==this.subscriptionGeneration)return;console.warn("[Client] Failed to subscribe to backend connection state changes:",a);return}if(typeof s=="function"){let a=s;if(this.disposed||t!==this.subscriptionGeneration){this.callBackendConnectionStateUnsubscribe(a);return}this.backendConnectionStateUnsubscribe=a,b$2("[Client] backend connection state subscription established synchronously");}else s&&typeof s.then=="function"&&s.then(a=>{if(this.disposed||t!==this.subscriptionGeneration){this.callBackendConnectionStateUnsubscribe(a);return}this.backendConnectionStateUnsubscribe=a,b$2("[Client] backend connection state subscription established asynchronously");}).catch(a=>{this.disposed||t!==this.subscriptionGeneration||console.warn("[Client] Failed to subscribe to backend connection state changes:",a);});}syncRoomRtdbPresenceFromBackend(){if(this.disposed)return;let e=this.signalingBackend?.rtdbPresence;e&&this.deps.setRoomRtdbPresence(e);}async getLocalDeviceId(){return this.disposed?null:this.deps.getCurrentSignaling().getLocalDeviceId()}async getTurnCredentials(){return this.disposed?null:this.deps.getCurrentSignaling().getTurnCredentials()}setWasmClient(e){this.disposed||this.deps.getCurrentSignaling().setWasmClient(e);}getCurrentUser(){return this.disposed?null:this.deps.getCurrentSignaling().currentUser}async waitForAuth(){this.disposed||await this.deps.getCurrentSignaling().waitForAuth();}onAuthChange(e){return this.disposed?()=>{}:this.deps.getCurrentSignaling().onAuthChange(e)}async signInAnonymously(){if(!this.disposed)return this.deps.getCurrentSignaling().signInAnonymously()}async signInWithPluto(){if(!this.disposed)return this.deps.getCurrentSignaling().signInWithPluto()}async signOut(){if(!this.disposed)return this.deps.getCurrentSignaling().signOut()}getRuntimeCapabilities(){if(!this.disposed)return this.deps.getCurrentSignaling().getRuntimeCapabilities?.()}startAutoConnect(e,t){this.disposed||this.deps.getCurrentSignaling().startAutoConnect(e,t);}async isConnected(e){return this.disposed?false:this.deps.getCurrentSignaling().isConnected(e)}notifyDisconnectRequested(e){this.disposed||this.deps.getCurrentSignaling().notifyDisconnectRequested(e);}forceReconnectSnapshot(){this.disposed||this.deps.getCurrentSignaling().forceReconnectSnapshot();}startPresenceLoop(e,t,n,i,o){this.disposed||this.deps.getCurrentSignaling().startPresenceLoop(e,t,n,i,o);}async setOffline(e){this.disposed||await this.deps.getCurrentSignaling().setOffline(e);}async updatePresence(e,t,n,i,o){this.disposed||await this.deps.getCurrentSignaling().updatePresence(e,t,n,i,o);}async searchDevices(){return this.disposed?[]:this.deps.getCurrentSignaling().searchDevices()}async updateDevice(e,t){this.disposed||await this.deps.getCurrentSignaling().updateDevice(e,t);}async deleteDevice(e){this.disposed||await this.deps.getCurrentSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.disposed||await this.deps.getCurrentSignaling().cleanupStaleDevices();}onDevicesChange(e){return this.disposed?()=>{}:this.deps.getCurrentSignaling().onDevicesChange(e)}async subscribeSessions(e,t){return this.disposed?()=>{}:this.deps.getCurrentSignaling().subscribeSessions(e,t)}async stopAuthScopedActivity(){this.disposed||(this.deps.stopRoomLiveness(),await this.stopAuthScopedActivityFor(this.deps.getCurrentSignaling()));}dispose(){if(this.disposed)return;this.disposed=true,this.disposeBackendConnectionSubscription(),this.deps.stopRoomLiveness();let e=this.deps.getCurrentSignaling();this.stopAuthScopedActivityBestEffort(e);}async stopAuthScopedActivityFor(e){if(e&&typeof e.stopAuthScopedActivity=="function")try{await e.stopAuthScopedActivity();}catch(t){if(this.disposed)return;console.warn("[Client] signaling auth-scoped teardown failed",t);}}stopAuthScopedActivityBestEffort(e){try{this.stopAuthScopedActivityFor(e);}catch{}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}disposeBackendConnectionSubscription(){this.subscriptionGeneration+=1,this.callBackendConnectionStateUnsubscribe(this.backendConnectionStateUnsubscribe),this.backendConnectionStateUnsubscribe=null;}callBackendConnectionStateUnsubscribe(e){if(e)try{e();}catch(t){console.warn("[Client] backend connection-state unsubscribe failed",t);}}};function gr(r$1){return new Ti({getContext:()=>r$1.getClientContext(),getOptions:()=>r$1.options,getApiKey:()=>r$1.options.apiKey,getCurrentSignaling:()=>r$1.signaling,createSignaling:e=>new Te(r(r$1.options),e),stopRoomLiveness:()=>r$1.rooms.stopHeartbeat(),installBackend:e=>{r$1.setSignaling(e),r$1.setRooms(new Le(r$1.roomClientHost,e));},setRoomRtdbPresence:e=>{r$1.rooms.setRtdbPresence(e);},setAppLimits:e=>{r$1.setAppLimits(e);},setDiscoveryMode:e=>{r$1.options.discoveryMode=e;},setRoomCreationMode:e=>{r$1.setRoomCreationMode(e);},getCoreClientHost:()=>({connect:(e,t,n,i,o)=>r$1.connectionDialer.connect(e,t,n,i,o),ensureManagedApplicationRoute:e=>r$1.ensureManagedApplicationRoute(e),waitForApplicationCryptoForPeer:(e,t)=>r$1.waitForApplicationCryptoForPeer(e,t),hasApplicationRouteForPeer:(e,t)=>r$1.hasApplicationRouteForPeer(e,t),rememberRouteRepairTokenFromTicket:e=>r$1.sessionTokens.rememberRouteRepairTokenFromTicket(e)}),schedulePeerReconciliation:e=>r$1.peerProjection.schedule(e),onBackendConnectionState:e=>{if(e.transportState!=="connected"||e.replacementInProgress===true)return;let t=r$1.registry.get(e.connectionId);if(!t||t.isClosed||e.remoteNodeId&&e.remoteNodeId.trim()!==t.remoteNodeId)return;let n=e.activeTransportStableId,i=()=>{t.handleBaseTransportAvailable("rust-backend-state",{transportState:e.transportState??e.state,transportGeneration:e.transportGeneration,transportStableId:n});};if(!Number.isSafeInteger(n)||Number(n)<=0){i();return}r$1.managedTransportDialer.repairAdmissionForTransportGeneration(t.remoteNodeId,Number(n)).catch(o=>{c$1("[Client][AUTH] current-generation admission repair deferred",{connectionId:t.id,remoteNodeId:t.remoteNodeId,transportStableId:n,error:o instanceof Error?o.message:String(o)});}).finally(i);},beforeSignOut:()=>r$1.prepareStreamListenForSignOutIfExists(),usesTicketOnlySignalingMode:()=>r$1.runtimeStatus.usesTicketOnlySignalingMode(),ensureWasmRuntimeForP2P:()=>r$1.runtimeReadiness.ensureWasmRuntimeForP2P(),getTicket:()=>r$1.runtimeIdentity.getTicket(),ensureSignalingReadyForDiscovery:e=>r$1.runtimeReadiness.ensureSignalingReadyForDiscovery(e),requiresManagedTransportTrust:()=>r$1.runtimeStatus.requiresManagedTransportTrust(r$1.discoveryMode),onDeviceRemembered:e=>{r$1.applicationCrypto.reindexDevice(e);},applyDiscoveredDevice:e=>{r$1.peerServices.applyDiscoveredDevice(e);},getPeerStatus:e=>r$1.peerServices.getPeerStatus(e),hasPeerScopes:e=>r$1.peerServices.hasPeerScopes(e),forceDisconnectPeer:e=>r$1.peerServices.forceDisconnectPeer(e)})}var Ti=class{constructor(e){this.host=e;}get auth(){return this._auth||(this._auth=new xt(this.host.getContext(),this.host.getOptions(),{usesTicketOnlySignalingMode:()=>this.host.usesTicketOnlySignalingMode(),getCurrentUser:()=>this.backend.getCurrentUser(),waitForAuth:()=>this.backend.waitForAuth(),onAuthChange:e=>this.backend.onAuthChange(e),signInAnonymously:()=>this.backend.signInAnonymously(),signInWithPluto:()=>this.backend.signInWithPluto(),signOut:()=>this.backend.signOut(),beforeSignOut:()=>this.host.beforeSignOut(),stopAuthScopedActivity:()=>this.backend.stopAuthScopedActivity()})),this._auth}get backend(){return this._backend||(this._backend=new Bt(this.host.getContext(),{getOptions:()=>this.host.getOptions(),getApiKey:()=>this.host.getApiKey(),usesTicketOnlySignalingMode:()=>this.host.usesTicketOnlySignalingMode(),getCurrentSignaling:()=>this.host.getCurrentSignaling(),createSignaling:e=>this.host.createSignaling(e),stopRoomLiveness:()=>this.host.stopRoomLiveness(),installBackend:(e,t)=>this.host.installBackend(e,t),setRoomRtdbPresence:e=>this.host.setRoomRtdbPresence(e),setAppLimits:e=>this.host.setAppLimits(e),setDiscoveryMode:e=>this.host.setDiscoveryMode(e),setRoomCreationMode:e=>this.host.setRoomCreationMode(e),getCoreClientHost:()=>this.host.getCoreClientHost(),onBackendConnectionState:e=>this.host.onBackendConnectionState(e),schedulePeerReconciliation:e=>this.host.schedulePeerReconciliation(e),onSignalingBackendChanged:()=>{this._presence?.notifySignalingBackendChanged();}})),this._backend}get presence(){return this._presence||(this._presence=new Ft(this.host.getContext(),this.host.getOptions(),{ensureWasmRuntimeForP2P:()=>this.host.ensureWasmRuntimeForP2P(),ensureAuthenticated:e=>this.auth.ensureAuthenticated(e),getTicket:()=>this.host.getTicket(),getLocalDeviceId:()=>this.backend.getLocalDeviceId(),getCurrentUser:()=>this.backend.getCurrentUser(),startPresenceLoop:(e,t,n,i,o)=>this.backend.startPresenceLoop(e,t,n,i,o),setOffline:e=>this.backend.setOffline(e),updatePresence:(e,t,n,i,o)=>this.backend.updatePresence(e,t,n,i,o),syncRoomRtdbPresence:()=>this.backend.syncRoomRtdbPresenceFromBackend(),splitCompoundTicket:e=>se(e),decodeCompoundTicketPayload:(e,t)=>ue(e,t),buildCompoundTicketWithPayload:(e,t,n,i)=>Et(e,t,n,i)})),this._presence}get devices(){return this._devices||(this._devices=new Lt(this.host.getContext(),{ensureSignalingReadyForDiscovery:e=>this.host.ensureSignalingReadyForDiscovery(e),searchDevices:()=>this.backend.searchDevices(),updateDevice:(e,t)=>this.backend.updateDevice(e,t),deleteDevice:e=>this.backend.deleteDevice(e),cleanupStaleDevices:()=>this.backend.cleanupStaleDevices(),onDevicesChange:e=>this.backend.onDevicesChange(e),subscribeSessions:(e,t)=>this.backend.subscribeSessions(e,t),requiresManagedTransportTrust:()=>this.host.requiresManagedTransportTrust(),onDeviceRemembered:e=>this.host.onDeviceRemembered(e),applyDiscoveredDevice:e=>this.host.applyDiscoveredDevice(e),getPeerStatus:e=>this.host.getPeerStatus(e),hasPeerScopes:e=>this.host.hasPeerScopes(e),forceDisconnectPeer:e=>this.host.forceDisconnectPeer(e),getLocalDeviceId:()=>this.backend.getLocalDeviceId()})),this._devices}clearManagedPresenceTicketIfExists(){this._presence?.clearManagedPresenceTicket();}};var Wt=class{constructor(e){this.localTerminalConnectionIds=new Set;this.connections=e??new Map;}get(e){return this.connections.get(e)}has(e){return this.connections.has(e)}set(e,t){this.connections.set(e,t);}delete(e){return this.connections.delete(e)}values(){return this.connections.values()}forEach(e){this.connections.forEach(e);}[Symbol.iterator](){return this.connections[Symbol.iterator]()}get size(){return this.connections.size}all(){return Array.from(this.connections.values())}applicationReady(e={}){return this.all().filter(t=>typeof t.isReadyForApplicationPayload=="function"?t.isReadyForApplicationPayload(e):!t.isClosed)}get backingMap(){return this.connections}set backingMap(e){this.connections=e instanceof Map?e:new Map;}getForPeer(e,t){for(let n of this.connections.values())if(e&&n.id===e||t&&(n.remoteNodeId===t||n.deviceId===t))return n;return null}markLocalTerminalClose(e){this.localTerminalConnectionIds.add(e);}clearLocalTerminalClose(e){this.localTerminalConnectionIds.delete(e);}hasLocalTerminalClose(e){return !!e&&this.localTerminalConnectionIds.has(e)&&!this.connections.has(e)}};function et(){return BigInt(Date.now())}function Ot(r,e){let t=new ArrayBuffer(17),n=new DataView(t);return n.setUint8(0,3),n.setBigUint64(1,r,false),n.setBigInt64(9,e,false),new Uint8Array(t)}function hr(r,e){let t=new ArrayBuffer(25),n=new DataView(t);return n.setUint8(0,4),n.setBigUint64(1,r.seq,false),n.setBigInt64(9,r.senderUnixMs,false),n.setBigInt64(17,e,false),new Uint8Array(t)}function mr(r){if(r.byteLength<17||r[0]!==3)return null;let e=new DataView(r.buffer,r.byteOffset,r.byteLength);return {seq:e.getBigUint64(1,false),senderUnixMs:e.getBigInt64(9,false)}}function fr(r){if(r.byteLength<25||r[0]!==4)return null;let e=new DataView(r.buffer,r.byteOffset,r.byteLength);return {seq:e.getBigUint64(1,false),senderUnixMs:e.getBigInt64(9,false),recvUnixMs:e.getBigInt64(17,false)}}function Ai(r,e){let t=import.meta.env??{};if(!(String(t.VITE_E2E??"").toLowerCase()==="true"))return e;let i=r==="VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_TICK_MS"?t.VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_TICK_MS:r==="VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_SUSPECT_MS"?t.VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_SUSPECT_MS:r==="VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_STALE_MS"?t.VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_STALE_MS:void 0,o=Number(i);return Number.isFinite(o)&&o>0?o:e}var tt={tickIntervalMs:Ai("VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_TICK_MS",5e3),suspectAfterMs:Ai("VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_SUSPECT_MS",1e4),staleAfterMs:Ai("VITE_OPENRTC_E2E_WEBRTC_HEARTBEAT_STALE_MS",3e4)},Ht=class{constructor(e,t,n=tt){this.seq=0n;this.pendingPings=new Map;this.lastPongAtMs=null;this.firstPingSentAtMs=null;this.currentHealth="unknown";this.lastLatencyMs=null;this.tickTimer=null;this.stopped=false;this.probeWaiters=new Map;this.probeLatencyWaiters=new Map;this.probeTimers=new Map;this.probeLatencyTimers=new Map;this.sendFn=e,this.onHealthChange=t,this.config=n;}start(){this.tickTimer!==null||this.stopped||(this.tickTimer=setInterval(()=>{this.tick();},this.config.tickIntervalMs),this.tick());}stop(){this.stopped=true,this.tickTimer!==null&&(clearInterval(this.tickTimer),this.tickTimer=null);for(let e of this.probeWaiters.values())e(false);this.probeWaiters.clear();for(let e of this.probeTimers.values())clearTimeout(e);this.probeTimers.clear();for(let e of this.probeLatencyWaiters.values())e(null);this.probeLatencyWaiters.clear();for(let e of this.probeLatencyTimers.values())clearTimeout(e);this.probeLatencyTimers.clear(),this.pendingPings.clear();}handleIncoming(e){if(!e||e.byteLength===0)return false;let t=e[0];if(t===3){let n=mr(e);if(n){c$1("[TransportHeartbeat] ping received from peer, sending pong",{seq:n.seq.toString()});let i=hr(n,et());this.sendFn(i).catch(o=>console.warn("[TransportHeartbeat] pong send failed",o));}else console.warn("[TransportHeartbeat] ping decode failed",{byteLength:e.byteLength});return true}if(t===4){let n=fr(e);if(n){let i=this.pendingPings.get(n.seq),o=i!==void 0;c$1("[TransportHeartbeat] pong received",{seq:n.seq.toString(),wasPending:o,pendingCount:this.pendingPings.size}),o&&(this.pendingPings.delete(n.seq),this.lastPongAtMs=Date.now(),this.lastLatencyMs=i!==void 0?Math.max(0,this.lastPongAtMs-i):null,this.evaluateHealth());let s=this.probeWaiters.get(n.seq);s&&(this.probeWaiters.delete(n.seq),s(true));let a=this.probeLatencyWaiters.get(n.seq);a&&(this.probeLatencyWaiters.delete(n.seq),a(o&&i!==void 0?Math.max(0,Date.now()-i):null));}else console.warn("[TransportHeartbeat] pong decode failed",{byteLength:e.byteLength});return true}return false}async tick(){if(this.stopped)return;let e=Date.now(),t=e-this.config.staleAfterMs;for(let[o,s]of this.pendingPings)s<=t&&this.pendingPings.delete(o);this.seq++;let n=this.seq,i=Ot(n,et());try{await this.sendFn(i),this.firstPingSentAtMs===null&&(this.firstPingSentAtMs=e),this.pendingPings.set(n,e),c$1("[TransportHeartbeat] ping sent",{seq:n.toString(),pendingCount:this.pendingPings.size,lastPongAtMs:this.lastPongAtMs,silenceSinceLastPongMs:this.lastPongAtMs?e-this.lastPongAtMs:null});}catch(o){console.warn("[TransportHeartbeat] ping send failed",{seq:n.toString(),error:o});}this.evaluateHealth();}evaluateHealth(){let e=this.computeHealth();if(e!==this.currentHealth){c$1("[TransportHeartbeat] health transition",{from:this.currentHealth,to:e,lastPongAtMs:this.lastPongAtMs,firstPingSentAtMs:this.firstPingSentAtMs,silenceMs:this.lastPongAtMs?Date.now()-this.lastPongAtMs:this.firstPingSentAtMs?Date.now()-this.firstPingSentAtMs:null,pendingCount:this.pendingPings.size}),this.currentHealth=e;try{this.onHealthChange(e);}catch{}}}computeHealth(){let e=Date.now();if(this.firstPingSentAtMs===null)return "unknown";if(this.lastPongAtMs!==null){let n=e-this.lastPongAtMs;return n>=this.config.staleAfterMs?"stale":n>=this.config.suspectAfterMs?"suspect":"healthy"}let t=e-this.firstPingSentAtMs;return t>=this.config.staleAfterMs?"stale":t>=this.config.suspectAfterMs?"suspect":"unknown"}get health(){return this.currentHealth}get latencyMs(){return this.lastLatencyMs}async probe(e){if(this.stopped)return false;this.seq++;let t=this.seq,n=Ot(t,et()),i=Date.now();return this.pendingPings.set(t,i),this.firstPingSentAtMs===null&&(this.firstPingSentAtMs=i),await new Promise(o=>{let s=setTimeout(()=>{this.probeTimers.delete(t),this.probeWaiters.delete(t)&&(this.pendingPings.delete(t),o(false));},e);this.probeTimers.set(t,s),this.probeWaiters.set(t,a=>{let c=this.probeTimers.get(t);c&&(clearTimeout(c),this.probeTimers.delete(t)),o(a);}),this.sendFn(n).catch(()=>{let a=this.probeTimers.get(t);a&&(clearTimeout(a),this.probeTimers.delete(t)),this.pendingPings.delete(t),this.probeWaiters.delete(t)&&o(false);});})}async probeLatency(e){if(this.stopped)return null;this.seq++;let t=this.seq,n=Ot(t,et()),i=Date.now();return this.pendingPings.set(t,i),this.firstPingSentAtMs===null&&(this.firstPingSentAtMs=i),await new Promise(o=>{let s=setTimeout(()=>{this.probeLatencyTimers.delete(t),this.probeLatencyWaiters.delete(t)&&(this.pendingPings.delete(t),o(null));},e);this.probeLatencyTimers.set(t,s),this.probeLatencyWaiters.set(t,a=>{let c=this.probeLatencyTimers.get(t);c&&(clearTimeout(c),this.probeLatencyTimers.delete(t)),o(a);}),this.sendFn(n).catch(()=>{let a=this.probeLatencyTimers.get(t);a&&(clearTimeout(a),this.probeLatencyTimers.delete(t)),this.pendingPings.delete(t),this.probeLatencyWaiters.delete(t)&&o(null);});})}};var B=class B{constructor(e,t,n,i,o,s={}){this.listeners=[];this.pendingMessages=[];this.pendingEncryptedApplicationPayloads=[];this.lastApplicationPayloadTransport=null;this.webrtcBinaryHandlers=[];this.closeListeners=[];this.upgradeStateListeners=[];this.writer=null;this.reader=null;this._isClosed=false;this.receiveBuffer=new Uint8Array(0);this.writeMutex=Promise.resolve();this.applicationCryptoWaiters=[];this.applicationKeyAgreementObservationEpoch=0;this.nativeSignalSender=null;this.webrtcTransport=null;this.webRtcApplicationRouteReadyTransport=null;this.webRtcApplicationRouteReadyNegotiationId=null;this.upgradeState="none";this.upgradeRequested=false;this.negotiationSwitchCount=0;this.upgradeAttemptActive=false;this.upgradeRetryCount=0;this.lastBaseTransportGeneration=null;this.lastBaseTransportStableId=null;this.upgradeReDriveCount=0;this.upgradeReDriveTimer=null;this.upgradeRetryTimer=null;this.upgradeAttemptTimeoutTimer=null;this.lastReportedTransportStatus=null;this.pendingTransportStatusReport=null;this.transportStatusReportInFlight=false;this.applicationRouteMissingNotified=false;this.upgradeTerminalFailure=false;this.pendingSignals=[];this.activeNegotiationId=null;this.pendingAvailabilityHint=null;this.webrtcHeartbeat=null;this.webRtcHeartbeatProbeInFlight=false;this.webRtcApplicationRouteProbeInFlight=false;this.pendingWebRtcApplicationRouteProof=null;this.webRtcHeartbeatConsecutiveProbeFailures=0;this.irohHealthListeners=[];this.webrtcHealthListeners=[];this.lastWebRtcHeartbeatOkAt=null;this.lastWebRtcDataChannelOpenAt=null;this.lastApplicationRouteReadyReportAt=null;this.lastForegroundAt=null;this.webRtcDisconnectedGraceTimer=null;this.preferredWebRtcRole=null;this.lastWebRtcLocalCandidateType=null;this.lastWebRtcRemoteCandidateType=null;this._peerMoQReady=false;this._remoteSupportsWebRTC=false;this.mediaListeners=[];this.trackListeners=[];this.warnedSrtpApplicationCryptoBoundary=false;this.id=e,this.localNodeId=t,this.remoteNodeId=n,this.deviceId=n,this.writer=i,this.reader=o,this.options=s,this.readLoop(),this.options.rtcConfig?.lanMode&&this.options.rtcConfig&&queueMicrotask(()=>this.requestWebRTCUpgrade("lan-mode"));}get isClosed(){return this._isClosed}setApplicationCrypto(e){this.options={...this.options,applicationCrypto:e},e?(this.applicationRouteMissingNotified=false,this.resolveApplicationCryptoWaiters(),this.flushPendingEncryptedApplicationPayloads(),!this.isCurrentWebRtcTransportApplicationRouteReady()&&this.webrtcTransport&&this.upgradeState==="upgraded"&&this.startWebRtcApplicationRouteProbe(this.webrtcTransport,"application-crypto-ready"),this.options.transportContext?.requestMoQApplicationRouteProof?.()):this.options.transportContext?.clearMoQApplicationRouteProof?.();}markApplicationKeyAgreementObserved(){return this.applicationKeyAgreementObservationEpoch+=1,this.applicationKeyAgreementObservationEpoch}getApplicationKeyAgreementObservationEpoch(){return this.applicationKeyAgreementObservationEpoch}requireApplicationCrypto(){this.options={...this.options,requireApplicationCrypto:true};}isApplicationCryptoRequired(){return this.options.requireApplicationCrypto===true}isReadyForApplicationPayload(e={}){if(this.isClosed||!this.hasRequiredApplicationCrypto())return false;let t=e.preferredTransports??[],n=this.getTransportStatus().activeTransport;return t.length===0?this.isTransportAvailableForApplicationPayload(n):t.includes(n)||f$1(n)&&t.includes("webrtc")?this.isTransportAvailableForApplicationPayload(n):e.allowFallbackAfterPreferredTransportFailure===true&&this.upgradeState==="failed"&&this.isTransportAvailableForApplicationPayload(n)}getApplicationPayloadTransports(e={}){if(!this.isReadyForApplicationPayload(e))return [];let t=this.getTransportStatus(),n=[t.activeTransport];return e.includeFallbackTransports===true&&t.parallelTransport&&t.parallelTransport!==t.activeTransport&&this.isTransportAvailableForApplicationPayload(t.parallelTransport)&&n.push(t.parallelTransport),n}isTransportAvailableForApplicationPayload(e){return this._isClosed||!this.hasRequiredApplicationCrypto()?false:f$1(e)?this.isWebRtcApplicationRouteReady():e==="moq"?this.isMoQApplicationRouteReady():e==="iroh"||e==="iroh-relay"||e==="iroh-quic"||e==="iroh-lan"||e==="ble"?this.hasBaseApplicationRoute():false}resolveApplicationCryptoWaiters(){let e=this.applicationCryptoWaiters.splice(0);for(let t of e)t.timer&&clearTimeout(t.timer),t.resolve();}rejectApplicationCryptoWaiters(e){let t=this.applicationCryptoWaiters.splice(0);for(let n of t)n.timer&&clearTimeout(n.timer),n.reject(e);}async waitForRequiredApplicationCrypto(){if(!this.options.requireApplicationCrypto||this.options.applicationCrypto)return;if(this.isClosed)throw new Error("[Connection] Application crypto is required but the connection is closed.");let e=this.options.applicationCryptoWaitMs??B.DEFAULT_APPLICATION_CRYPTO_WAIT_MS;if(e<=0)throw new Error("[Connection] Application crypto is required before sending app payloads.");await new Promise((t,n)=>{let i={resolve:t,reject:n,timer:null};i.timer=setTimeout(()=>{this.applicationCryptoWaiters=this.applicationCryptoWaiters.filter(o=>o!==i),n(new Error("[Connection] Application crypto negotiation timed out before sending app payloads."));},e),this.applicationCryptoWaiters.push(i);});}requestWebRTCUpgrade(e="peer-capable"){if(!this.options.rtcConfig){this.traceLifecycle("webrtc-request-skipped",{reason:e,skipReason:"missing-rtc-config"});return}let t=this.getDeterministicWebRtcRole();this.upgradeState==="upgrading"&&this.preferredWebRtcRole==="responder"||(this.preferredWebRtcRole=t);let n=this.getControlFrameMode()==="native-main"&&!this.isWebRtcApplicationRouteReady();this.traceLifecycle("webrtc-requested",{reason:e,requestedRole:t,forceRenegotiate:n}),this.beginWebRtcRecovery(e,{forceRenegotiate:n,replaceExisting:n&&!!this.webrtcTransport,resetRetryBudget:true,skipIfAlreadyUpgrading:true});}isWebRtcRouteHeartbeatLive(){if(!this.isWebRtcDataChannelOpen())return false;let e=this.lastWebRtcHeartbeatOkAt===null?null:Date.now()-this.lastWebRtcHeartbeatOkAt;if(e!==null&&e<=B.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS)return true;let t=this.lastWebRtcDataChannelOpenAt===null?null:Date.now()-this.lastWebRtcDataChannelOpenAt;return t!==null&&t<=B.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS}requestTransportRecovery(e,t={}){!this.options.rtcConfig||this._isClosed||this.beginWebRtcRecovery(e,{forceRenegotiate:!!t.forceRenegotiate,replaceExisting:!!t.replaceExisting,resetRetryBudget:false,skipIfAlreadyUpgrading:false});}handleAppForeground(){if(this.lastForegroundAt=Date.now(),this._isClosed||!this.options.rtcConfig||!this.upgradeRequested||!this.hasRecoverableBasePath())return;if(this.upgradeState==="upgrading"&&this.upgradeAttemptActive&&this.activeNegotiationId){this.pendingAvailabilityHint={negotiationId:this.activeNegotiationId,source:"app-foreground"},this.traceLifecycle("webrtc-availability-hint-deferred",{negotiationId:this.activeNegotiationId});return}let e=this.webrtcTransport,t=e?.getNativeTransport?.(),n=e?.getDataChannelReadyState?.()??null,i=typeof t?.connectionState=="string"?t.connectionState:null,o=typeof t?.iceConnectionState=="string"?t.iceConnectionState:null;if(this.upgradeState!=="upgraded"||n!=="open"||i==="failed"||i==="disconnected"||o==="failed"||o==="disconnected"){this.requestTransportRecovery("app-foreground",{forceRenegotiate:true,replaceExisting:!!e||this.upgradeState==="failed"||this.upgradeState==="upgraded"});return}let a=this.webrtcHeartbeat,c=this.lastWebRtcHeartbeatOkAt===null?null:Date.now()-this.lastWebRtcHeartbeatOkAt;!(c!==null&&c>=tt.suspectAfterMs)||!a||a.probe(B.FOREGROUND_PROBE_TIMEOUT_MS).then(p=>{p||this._isClosed||this.webrtcTransport===e&&this.requestTransportRecovery("app-foreground-probe-failed",{forceRenegotiate:true,replaceExisting:true});});}handleBaseTransportAvailable(e,t){if(t?.transportState&&t.transportState!=="connected")return;let n=Number.isSafeInteger(t?.transportGeneration)?Number(t?.transportGeneration):null,i=Number.isSafeInteger(t?.transportStableId)?Number(t?.transportStableId):null,o=false;if(n!==null){if(this.lastBaseTransportGeneration!==null&&n<this.lastBaseTransportGeneration||n===this.lastBaseTransportGeneration)return;o=this.lastBaseTransportGeneration!==null,this.lastBaseTransportGeneration=n,this.lastBaseTransportStableId=i;}this._isClosed||!this.options.rtcConfig||!this.upgradeRequested||this.upgradeState==="upgrading"&&!o||(this.traceLifecycle("base-transport-available",{source:e,transportGeneration:n,transportStableId:i,replacedBaseTransport:o}),this.beginWebRtcRecovery(`base-transport-available:${e}`,{forceRenegotiate:true,replaceExisting:!!this.webrtcTransport,resetRetryBudget:true,skipIfAlreadyUpgrading:!o}));}beginWebRtcRecovery(e,t){if(!this.options.rtcConfig||this._isClosed)return;let n=t.forceRenegotiate,i=t.replaceExisting,o=t.resetRetryBudget;if(t.skipIfAlreadyUpgrading&&(this.upgradeState==="upgrading"||this.upgradeState==="upgraded")){let s=this.isWebRtcApplicationRouteReady();if(!(this.upgradeState==="upgraded"&&!s&&!this.isWebRtcRouteHeartbeatLive()&&this.getDeterministicWebRtcRole()==="initiator")){c$1("[Connection] WebRTC recovery request ignored: attempt already active",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,currentState:this.upgradeState,routeAlreadyProven:s});return}c$1("[Connection] WebRTC recovery replacing a stale upgraded route (heartbeat not live)",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e}),this.stopWebRtcHeartbeat(),this.pendingSignals=[],this.teardownWebRTCTransport(`recovery-replace-stale:${e}`),this.setUpgradeState("none");}c$1("[Connection] beginWebRtcRecovery called",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,replaceExisting:i,forceRenegotiate:n,resetRetryBudget:o,currentState:this.upgradeState,caller:new Error().stack?.split(`
2
+ `).slice(1,4).join(" | ")}),this.upgradeRequested=true,this.upgradeAttemptActive=false,this.upgradeTerminalFailure=false,this.clearUpgradeRetryTimer(),this.clearUpgradeReDriveTimer(),this.clearUpgradeAttemptTimeoutTimer(),o&&(this.upgradeRetryCount=0,this.upgradeReDriveCount=0),i&&(this.stopWebRtcHeartbeat(),this.pendingSignals=[],this.teardownWebRTCTransport(`recovery-replace-existing:${e}`)),this.attemptUpgrade({forceRenegotiate:n,replaceExisting:i});}getUpgradeState(){return this.upgradeState}updateRTCConfig(e){this.options.rtcConfig=e;}onUpgradeStateChange(e){this.upgradeStateListeners.push(e);}async getTransportDiagnostics(){return this.collectTransportDiagnostics(false)}async collectTransportDiagnostics(e){let{activeTransport:t,parallelTransport:n}=this.getTransportStatus(),i={activeTransport:t,parallelTransport:n,usesRelay:null,relaySource:null,webrtc:null},o=this.webrtcTransport,s=o?.getNativeTransport?.();if(!o||!s)return i;try{let a=typeof s.getStats=="function"?await s.getStats():null,c=null;typeof a?.forEach=="function"&&(a.forEach(j=>{if(c||j?.type!=="transport")return;let q=j?.selectedCandidatePairId;!q||typeof a.get!="function"||(c=a.get(q)??null);}),c||a.forEach(j=>{c||j?.type==="candidate-pair"&&j?.selected===!0&&(c=j);}));let l=c?.localCandidateId&&typeof a?.get=="function"?a.get(c.localCandidateId):null,p=c?.remoteCandidateId&&typeof a?.get=="function"?a.get(c.remoteCandidateId):null,u=s?.sctp?.transport?.iceTransport,g=null;try{g=typeof u?.getSelectedCandidatePair=="function"?u.getSelectedCandidatePair():null;}catch{}let y=g?.local??l??null,m=g?.remote??p??null,v=typeof y?.candidateType=="string"?y.candidateType:typeof y?.type=="string"?y.type:null,S=typeof m?.candidateType=="string"?m.candidateType:typeof m?.type=="string"?m.type:null,I=typeof y?.protocol=="string"?y.protocol:null,k=typeof m?.protocol=="string"?m.protocol:null,T=!!(v&&S),D=T?v==="relay"||S==="relay":null,_=T?`${v??"unknown"}<->${S??"unknown"}`:null;if(this._isClosed||this.webrtcTransport!==o||this.upgradeState!=="upgraded")return {...i,relaySource:"webrtc-stats-stale"};let E=this.webRtcTransportLabel();e&&T&&(this.lastWebRtcLocalCandidateType=v,this.lastWebRtcRemoteCandidateType=S);let A=this.getTransportStatus();return e&&E!==this.webRtcTransportLabel()&&this.isWebRtcApplicationRouteReadyForTransport(o)&&this.reportTransportStatusIfChanged(),{...i,...A,usesRelay:D,relaySource:D==null?null:D?"webrtc-candidate-relay":"webrtc-candidate-direct",webrtc:{iceConnectionState:typeof s.iceConnectionState=="string"?s.iceConnectionState:null,iceGatheringState:typeof s.iceGatheringState=="string"?s.iceGatheringState:null,localCandidateType:v,remoteCandidateType:S,localProtocol:I,remoteProtocol:k,candidateTypeSummary:_}}}catch{return {...i,relaySource:"webrtc-stats-unavailable"}}}refreshWebRtcCandidatePairObservation(e){this._isClosed||this.webrtcTransport!==e||this.collectTransportDiagnostics(true).catch(t=>{c$1("[Connection] WebRTC selected candidate-pair observation failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:e.getNegotiationId?.()??null,error:t});});}clearWebRtcCandidatePairObservation(){this.lastWebRtcLocalCandidateType=null,this.lastWebRtcRemoteCandidateType=null;}webRtcTransportLabel(){let e=this.options.rtcConfig,t=e?.lanMode===true&&e.useDefaultIceServers===false&&Array.isArray(e.iceServers)&&e.iceServers.length===0;return g$2(this.lastWebRtcLocalCandidateType,this.lastWebRtcRemoteCandidateType,t)}get transportType(){return this.isWebRtcApplicationRouteReady()?this.webRtcTransportLabel():this.isMoQApplicationRouteReady()?"moq":"iroh-relay"}get peerMoQReady(){return this._peerMoQReady}set peerMoQReady(e){this._peerMoQReady!==e&&(this._peerMoQReady=e,e?this.options.transportContext?.requestMoQApplicationRouteProof?.():this.options.transportContext?.clearMoQApplicationRouteProof?.(),this.reportTransportStatusIfChanged());}get remoteSupportsWebRTC(){return this._remoteSupportsWebRTC}set remoteSupportsWebRTC(e){this._remoteSupportsWebRTC=e;}async send(e,t={}){return this.sendTyped(0,e,{requireApplicationCrypto:true,useApplicationPayloadRoute:true,routeOptions:t})}async sendMedia(e,t){let n=e==="video"?1:2;return this.sendTyped(n,t,{requireApplicationCrypto:true})}async sendOnTransport(e,t){return this.sendTypedOnTransport(e,0,t,{requireApplicationCrypto:true})}getLastApplicationPayloadTransport(){return this.lastApplicationPayloadTransport}async sendControl(e){return this.sendTyped(0,e,{requireApplicationCrypto:false,protectApplicationPayload:false})}async sendRawIrohFrame(e){if(this.isClosed||!this.writer)throw new Error("[Connection] Requested transport unavailable: iroh");let t=this.writeMutex,n;this.writeMutex=new Promise(i=>{n=i;});try{if(await t,!this.writer)throw new Error("[Connection] Requested transport unavailable: iroh");await this.writer.write(e);}catch(i){throw this.preserveWebRtcConnectionAfterBaseTransportLoss(`Iroh Send Error: ${i}`)||(console.error("[Connection] Iroh Send error:",i),this.close(`Send Error: ${i}`)),i}finally{n();}}getAvailableTransports(){let e=[],{activeTransport:t,parallelTransport:n}=this.getTransportStatus();this.isWebRtcApplicationRouteReady()&&e.push(this.webRtcTransportLabel());this.options.transportContext;if(this.isMoQApplicationRouteReady()&&e.push("moq"),this.hasBaseApplicationRoute()){let o=t==="iroh-lan"||t==="iroh-quic"||t==="iroh-relay"||t==="ble"?t:n;e.push(o??"iroh-relay");}return e}onWebRTCBinaryMessage(e){this.webrtcBinaryHandlers.push(e);}dispatchWebRtcBinaryHandlers(e){for(let t of this.webrtcBinaryHandlers)if(t(e))return true;return false}getWebRTCTransport(){return this.isWebRtcApplicationRouteReady()?this.webrtcTransport:null}async sendOnWebRTC(e){if(!this.webrtcTransport||!this.isWebRtcApplicationRouteReady())throw new Error("[Connection] WebRTC transport unavailable");await this.waitForRequiredApplicationCrypto(),await this.webrtcTransport.send(this.protectApplicationPayload(0,e));}encodePayload(e){return typeof e=="string"?new TextEncoder().encode(e):e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new TextEncoder().encode(JSON.stringify(e))}protectApplicationPayload(e,t){return this.options.applicationCrypto?.protectPayload(e,t)??t}protectRequiredApplicationPayload(e,t){let n=this.options.applicationCrypto;return n?n.protectPayload(e,t):null}openApplicationPayload(e,t){let n=this.options.applicationCrypto;return n?n.openPayload(e,t):l$1(t)?(this.queueEncryptedApplicationPayload(e,t),null):this.options.requireApplicationCrypto===true&&!this.isPlaintextBootstrapPayload(t)?null:t}openUntypedApplicationPayload(e){if(!l$1(e))return this.options.requireApplicationCrypto===true?null:e;let t=this.options.applicationCrypto;return t?t.openPayload(0,e)??t.openPayload(3,e):(this.queueEncryptedApplicationPayload("untyped",e),null)}isPlaintextBootstrapPayload(e){try{return JSON.parse(B.textDecoder.decode(e))?.type==="handshake"}catch{return false}}queueEncryptedApplicationPayload(e,t){this._isClosed||(this.pendingEncryptedApplicationPayloads.push({typeId:e,payload:new Uint8Array(t)}),this.pendingEncryptedApplicationPayloads.length>B.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS&&this.pendingEncryptedApplicationPayloads.splice(0,this.pendingEncryptedApplicationPayloads.length-B.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS));}flushPendingEncryptedApplicationPayloads(){let e=this.options.applicationCrypto;if(!e||this.pendingEncryptedApplicationPayloads.length===0)return;let t=this.pendingEncryptedApplicationPayloads.splice(0),n=[];for(let i of t){let o=i.typeId==="untyped"?e.openPayload(0,i.payload)??e.openPayload(3,i.payload):e.openPayload(i.typeId,i.payload);if(o){i.typeId===1?this.emitMedia("video",o):i.typeId===2?this.emitMedia("audio",o):this.processDataPayload(o);continue}l$1(i.payload)&&n.push(i);}n.length>B.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS&&n.splice(0,n.length-B.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS),this.pendingEncryptedApplicationPayloads=n;}buildFrame(e,t){let n=5+t.length,i=new Uint8Array(n);return new DataView(i.buffer).setUint32(0,1+t.length,false),i[4]=e,i.set(t,5),i}async sendOverIroh(e,t,n){let i=this.options.transportContext;if(i?.disableIrohFallback&&e!==0)return console.warn(`[Connection] Iroh disabled for ${n}; dropping packet.`),false;if(this.isClosed)return false;if(!this.writer&&i?.sendIrohApplicationFrame)return await i.sendIrohApplicationFrame(t),true;if(!this.writer)return false;let o=this.writeMutex,s;this.writeMutex=new Promise(a=>{s=a;});try{return await o,this.writer?(await this.writer.write(t),!0):!1}catch(a){if(this.preserveWebRtcConnectionAfterBaseTransportLoss(`Iroh Send Error: ${a}`))return false;throw console.error("[Connection] Iroh Send error:",a),this.close(`Send Error: ${a}`),a}finally{s();}}async sendUsingTransport(e,t,n,i,o,s){let a=this.options.transportContext;return e==="webrtc-lan"||e==="webrtc-turn"?this.transportType!==e||!this.webrtcTransport||!this.isWebRtcApplicationRouteReady()||t!==0?false:(await this.webrtcTransport.send(o),this.reportApplicationRouteReady("webrtc-application-send"),true):e==="webrtc"?!this.webrtcTransport||!this.isWebRtcApplicationRouteReady()||t!==0?false:(await this.webrtcTransport.send(o),this.reportApplicationRouteReady("webrtc-application-send"),true):e==="moq"?a&&a.isMoQReady()&&this.peerMoQReady&&this.isMoQDataRouteReady(a)?(await a.sendMoQ(s,{alreadyProtected:true}),true):false:e==="iroh-lan"||e==="ble"?this.transportType!==e?false:this.sendOverIroh(t,s,"explicit transport send"):e==="iroh"||e==="iroh-relay"||e==="iroh-quic"?this.sendOverIroh(t,s,"explicit transport send"):false}async sendTypedOnTransport(e,t,n,i={}){i.requireApplicationCrypto&&await this.waitForRequiredApplicationCrypto();let o=this.encodePayload(n),s=i.protectApplicationPayload===false?o:this.protectApplicationPayload(t,o),a=this.buildFrame(t,o),c=this.buildFrame(t,s);if(!await this.sendUsingTransport(e,t,n,a,s,c))throw new Error(`[Connection] Requested transport unavailable: ${e}`);this.lastApplicationPayloadTransport=e;}async sendTyped(e,t,n={}){this.options.transportContext;n.requireApplicationCrypto&&await this.waitForRequiredApplicationCrypto();let o=this.encodePayload(t),s=n.protectApplicationPayload===false?o:this.protectApplicationPayload(e,o),a=this.buildFrame(e,o),c=this.buildFrame(e,s),l=n.useApplicationPayloadRoute&&e===0?this.getApplicationPayloadTransports(n.routeOptions??{}):this.getSendTransportPriorities(n);if(l.length===0)throw new Error("[Connection] Application payload route is not ready.");let p=null;for(let g of l)try{if(await this.sendUsingTransport(g,e,t,a,s,c)){this.lastApplicationPayloadTransport=g;return}}catch(y){p=y,console.warn(`[Connection] ${g} Send Failed:`,y);}let u=l.join(", ");throw p instanceof Error?new Error(`[Connection] Failed to send app payload on route(s): ${u}. Last error: ${p.message}`):new Error(`[Connection] Failed to send app payload on route(s): ${u}.`)}getSendTransportPriorities(e){let t=["webrtc","moq","iroh"],n=this.options.transportContext?.priorities??t,i=n.length>0?n:t,o=this.options.transportContext?.rankRoutes?.(i)??i;return e.requireApplicationCrypto===false||e.protectApplicationPayload===false?["iroh",...o.filter(a=>a!=="iroh"&&a!=="iroh-relay"&&a!=="iroh-quic"&&a!=="iroh-lan")]:o}async disconnect(){this.close("Explicit Disconnect");}onMessage(e){if(this.listeners.push(e),this.pendingMessages.length!==0)for(let t of this.pendingMessages)e(t);}onMedia(e){this.mediaListeners.push(e);}onDisconnect(e){this.closeListeners.push(e);}close(e){if(this._isClosed)return;if(this._isClosed=true,this.upgradeRequested=false,this.upgradeAttemptActive=false,this.activeNegotiationId=null,this.pendingAvailabilityHint=null,this.pendingSignals=[],this.clearUpgradeRetryTimer(),this.clearUpgradeReDriveTimer(),this.clearUpgradeAttemptTimeoutTimer(),this.clearWebRtcDisconnectedGraceTimer(),this.teardownWebRTCTransport(`connection-close:${e??"unspecified"}`),this.setUpgradeState("none"),this.rejectApplicationCryptoWaiters(new Error("[Connection] Application crypto negotiation stopped because the connection closed.")),this.pendingEncryptedApplicationPayloads=[],this.writer?.close().catch(()=>{}),(this.options.transportContext?.readerCloseStrategy??"cancel")==="release-lock")try{this.reader?.releaseLock();}catch{}else this.reader?.cancel().catch(()=>{});this.writer=null,this.reader=null,this.closeListeners.forEach(n=>n());}preserveWebRtcConnectionAfterBaseTransportLoss(e){let t=this.getControlFrameMode()==="native-main"&&!!this.nativeSignalSender,n=!!this.webrtcTransport&&(this.upgradeState==="upgraded"||this.upgradeState==="upgrading"&&!!this.nativeSignalSender);if(!t&&!n)return false;c$1("[Connection] Base transport closed while a control/WebRTC route remains usable; preserving connection",{connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,transportStatus:this.getTransportStatus(),upgradeState:this.upgradeState}),this.clearUpgradeRetryTimer();try{this.reader?.releaseLock();}catch{}try{this.writer?.releaseLock();}catch{}return this.reader=null,this.writer=null,this.reportApplicationRouteReady("base-transport-loss-preserved"),this.reportTransportStatusIfChanged(),true}async readLoop(){if(this.reader)try{for(;!this.isClosed;){let{done:e,value:t}=await this.reader.read();if(e){if(this.preserveWebRtcConnectionAfterBaseTransportLoss("Read Done (Remote Closed)"))break;this.close("Read Done (Remote Closed)");break}t&&this.handleData(t);}}catch(e){let t=`Read Error: ${e}`;if(this.preserveWebRtcConnectionAfterBaseTransportLoss(t))return;console.error("[Connection] Read loop error:",e),this.close(t);}}injectData(e){this.handleData(e);}handleData(e){let t=new Uint8Array(this.receiveBuffer.length+e.length);for(t.set(this.receiveBuffer),t.set(e,this.receiveBuffer.length),this.receiveBuffer=t;!(this.receiveBuffer.length<4);){let i=new DataView(this.receiveBuffer.buffer,this.receiveBuffer.byteOffset,this.receiveBuffer.byteLength).getUint32(0,false);if(this.receiveBuffer.length<4+i)break;let o=this.receiveBuffer.slice(4,4+i);this.receiveFrameBody(o),this.receiveBuffer=this.receiveBuffer.slice(4+i);}}receiveFrameBody(e){if(e.length===0)return;let t=e[0],n=e.slice(1);if(B.isUntypedDataFrame(e)){let i=this.openUntypedApplicationPayload(e);i&&this.processDataPayload(i);}else if(t===3)this.sendIrohHeartbeatPong(n);else if(t===4)this.irohHealthListeners.forEach(i=>i("healthy"));else if(t===1){let i=this.openApplicationPayload(t,n);i&&this.emitMedia("video",i);}else if(t===2){let i=this.openApplicationPayload(t,n);i&&this.emitMedia("audio",i);}else {if(t===0&&this.tryHandlePlaintextNativeSignal(n))return;let i=this.openApplicationPayload(t,n);i&&this.processDataPayload(i);}}tryHandlePlaintextNativeSignal(e){let t;try{t=JSON.parse(B.textDecoder.decode(e));}catch{return false}return !t||typeof t!="object"||t.type!=="#pluto-signal"?false:(this.handleInternalSignal(t),true)}static isUntypedDataFrame(e){let t=e[0];return t===123||t===91||l$1(e)?true:e.length>=4&&e[0]===68&&e[1]===86&&e[2]===67&&e[3]===72}processDataPayload(e){if(l$1(e)){let t=this.openUntypedApplicationPayload(e);t&&t!==e&&this.processDataPayload(t);return}try{let t=B.textDecoder.decode(e);if(!this.isLikelyTextPayload(e,t)){this.emitMessage(e);return}let n=JSON.parse(t);if(this.tryHandleWebRtcApplicationRouteProofPayload(n,null))return;if(n&&typeof n=="object"&&n.type==="#pluto-signal"){this.handleInternalSignal(n);return}typeof n=="object"&&n!==null?this.emitMessage(n):this.emitMessage(t);}catch{try{let t=B.textDecoder.decode(e);if(this.isLikelyTextPayload(e,t)){this.emitMessage(t);return}}catch{}this.emitMessage(e);}}isLikelyTextPayload(e,t){try{for(let i=0;i<t.length;i+=1){let o=t.charCodeAt(i);if(o<32&&o!==9&&o!==10&&o!==13)return !1}let n=B.textEncoder.encode(t);if(n.byteLength!==e.byteLength)return !1;for(let i=0;i<n.byteLength;i+=1)if(n[i]!==e[i])return !1;return !0}catch{return false}}emitMedia(e,t){this.mediaListeners.forEach(n=>n(e,t));}emitMessage(e){this.pendingMessages.push(e),this.pendingMessages.length>B.MAX_PENDING_MESSAGES&&this.pendingMessages.splice(0,this.pendingMessages.length-B.MAX_PENDING_MESSAGES),this.listeners.length!==0&&this.listeners.forEach(t=>t(e));}receiveMessage(e){this.emitMessage(e);}receiveDataPayload(e){this.processDataPayload(e);}warnSrtpApplicationCryptoBoundary(e){!this.options.applicationCrypto||this.warnedSrtpApplicationCryptoBoundary||(this.warnedSrtpApplicationCryptoBoundary=true,console.warn(`[Connection] ${e} uses WebRTC DTLS-SRTP media encryption, not the ORTCE1 applicationCrypto envelope. Use sendMedia() for ORTCE1-protected app-encoded media chunks.`));}addTrack(e){let t=this.webrtcTransport?.getNativeTransport?.();return t&&typeof t.addTrack=="function"?(this.warnSrtpApplicationCryptoBoundary("addTrack"),t.addTrack(e)):null}addTransceiver(e,t){let n=this.webrtcTransport?.getNativeTransport?.();return n&&typeof n.addTransceiver=="function"?(this.warnSrtpApplicationCryptoBoundary("addTransceiver"),n.addTransceiver(e,t)):null}onTrack(e){this.trackListeners.push(e);}hasRecoverableBasePath(){return !!this.nativeSignalSender||this.hasBaseApplicationRoute()}hasBaseApplicationRoute(){return this.options.hasBaseApplicationStream===false?false:!!this.writer||this.getControlFrameMode()==="native-main"&&!!this.nativeSignalSender&&typeof this.options.transportContext?.sendIrohApplicationFrame=="function"}isWebRtcDataChannelOpen(){return this.upgradeState==="upgraded"&&!!this.webrtcTransport&&this.webrtcTransport.getDataChannelReadyState?.()==="open"}clearWebRtcDisconnectedGraceTimer(){this.webRtcDisconnectedGraceTimer&&(clearTimeout(this.webRtcDisconnectedGraceTimer),this.webRtcDisconnectedGraceTimer=null);}transportStillLikelyAlive(e){let t=e.getDataChannelReadyState?.()??null,n=e.getNativeTransport?.()??null,i=typeof n?.connectionState=="string"?n.connectionState:null,o=typeof n?.iceConnectionState=="string"?n.iceConnectionState:null;return t==="closed"||t==="closing"?false:t==="open"?true:i==="connected"||i==="connecting"||o==="connected"||o==="completed"||o==="checking"}handleUnhealthyWebRtcTransportStateWithGrace(e,t){let n=e.getDataChannelReadyState?.()??null;if(n==="closed"||n==="closing"){if(c$1("[Connection] WebRTC unhealthy with closed DataChannel; failing upgraded transport immediately",{connectionId:this.id,remoteNodeId:this.remoteNodeId,state:t,dcReadyState:n}),!this.hasBaseApplicationRoute()&&!this.isMoQApplicationRouteReady()){this.close(`all-application-routes-closed:${t}`);return}this.stopWebRtcHeartbeat(),this.handleUpgradeFailure(`transport-state-${t}-dc-closed`);return}this.webRtcDisconnectedGraceTimer||(c$1("[Connection] WebRTC transport reported unhealthy; applying grace window before fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,state:t}),this.webRtcDisconnectedGraceTimer=setTimeout(()=>{if(this.webRtcDisconnectedGraceTimer=null,!(this._isClosed||this.webrtcTransport!==e)){if(this.transportStillLikelyAlive(e)){c$1("[Connection] WebRTC unhealthy grace expired but transport appears alive; suppressing fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,state:t});return}this.stopWebRtcHeartbeat(),this.handleUpgradeFailure(`transport-state-${t}-grace-expired`);}},B.WEBRTC_DISCONNECTED_GRACE_MS));}async attemptUpgrade(e){if(this._isClosed||!this.upgradeRequested||!this.options.rtcConfig)return;let t=typeof e=="object"&&e!==null?e:{preferredNegotiationId:e??null},n=t.preferredNegotiationId,i=!!t.forceRenegotiate;if(!!!t.replaceExisting&&(this.upgradeAttemptActive||this.upgradeState==="upgraded"))return;this.upgradeAttemptActive=true,this.teardownWebRTCTransport("upgrade-attempt-replacement"),this.clearWebRtcCandidatePairObservation(),this.applicationRouteMissingNotified=false;let s=this.normalizeNegotiationId(n)??this.createNegotiationId();this.activeNegotiationId=s,this.setUpgradeState("upgrading"),this.startUpgradeAttemptTimeout(s),(i||this.upgradeRetryCount>0)&&this.sendInternalSignal({transport:"webrtc",type:"renegotiate",negotiationId:s}).catch(()=>{});try{this.webrtcTransport=Ce.createTransport("webrtc");}catch(p){this.upgradeAttemptActive=false,c$1("[Connection] WebRTC upgrade unavailable",p),this.handleUpgradeFailure("transport-create-error");return}let a=this.webrtcTransport;typeof a.setSignalSender=="function"&&a.setSignalSender(p=>this.sendInternalSignal(p)),a.onMessage(p=>{if(p instanceof Uint8Array&&p.byteLength>0){if(this.webrtcHeartbeat?.handleIncoming(p)){p[0]===4&&this.refreshWebRtcCandidatePairObservation(a);return}let g=l$1(p),y=this.openApplicationPayload(0,p);if(!y||g&&this.tryHandleWebRtcApplicationRouteProofBytes(a,y)||this.dispatchWebRtcBinaryHandlers(y))return;this.processDataPayload(y);return}let u=this.openApplicationPayload(0,p);u&&this.processDataPayload(u);}),a.onStateChange(p=>{if(!(this._isClosed||this.webrtcTransport!==a)){if(d$2(`[Connection] WebRTC transport state changed: ${p}`),p==="connected"){this.pendingAvailabilityHint=null,this.clearWebRtcDisconnectedGraceTimer(),this.clearUpgradeAttemptTimeoutTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.clearUpgradeRetryTimer(),this.lastWebRtcDataChannelOpenAt=Date.now(),this.setUpgradeState("upgraded"),this.startWebRtcHeartbeat(a),this.startWebRtcApplicationRouteProbe(a,"transport-connected");return}if(p==="failed"||p==="disconnected"){if(this.clearUpgradeAttemptTimeoutTimer(),this.upgradeAttemptActive=false,this.upgradeState==="upgraded"&&(p==="disconnected"||this.isWebRtcApplicationRouteReadyForTransport(a))){this.handleUnhealthyWebRtcTransportStateWithGrace(a,p);return}if(this.clearWebRtcDisconnectedGraceTimer(),a.isTerminalFailure?.()){let u=this.pendingAvailabilityHint,g=!!u&&u.negotiationId===this.activeNegotiationId;this.pendingAvailabilityHint=null,this.upgradeTerminalFailure=!g,g&&this.traceLifecycle("webrtc-terminal-failure-retry-after-availability",{negotiationId:this.activeNegotiationId,source:u?.source??null});}this.stopWebRtcHeartbeat(),this.handleUpgradeFailure(`transport-state-${p}`);}}});try{await a.init(this.localNodeId,this.deviceId,{rtcConfig:this.options.rtcConfig,negotiationId:s,forceRole:this.preferredWebRtcRole??void 0});}catch(p){this.upgradeAttemptActive=false,this.clearUpgradeAttemptTimeoutTimer(),c$1("[Connection] WebRTC init failed",p),this.handleUpgradeFailure("init-error");return}if(this.webrtcTransport!==a){this.upgradeAttemptActive=false;return}let c=a.getNegotiationId?.();if(c&&(this.activeNegotiationId=this.normalizeNegotiationId(c)??s),this.pendingSignals.length>0){let p=this.pendingSignals.splice(0);for(let u of p)a.handleSignalingMessage?.(u);}let l=a.getNativeTransport?.();l&&l.ontrack!==void 0&&(l.ontrack=p=>{d$2(`[Connection] Peer track received: ${p.track.kind}`),this.trackListeners.forEach(u=>u(p));});}setUpgradeState(e){this.upgradeState!==e&&(this.upgradeState=e,this.reportTransportStatusIfChanged(),this.upgradeStateListeners.forEach(t=>{try{t(e);}catch(n){c$1("[Connection] Upgrade state listener failed",n);}}));}handleUpgradeFailure(e){if(this._isClosed||!this.upgradeRequested)return;this.clearUpgradeAttemptTimeoutTimer();let t=this.upgradeTerminalFailure,n=!t&&this.shouldRetryUpgrade();this.upgradeAttemptActive=false,this.setUpgradeState("failed");let i={connectionId:this.id,remoteNodeId:this.remoteNodeId,retryCount:this.upgradeRetryCount,maxRetries:B.MAX_UPGRADE_RETRIES,terminal:t,willRetry:n};if(n?c$1(`[Connection] WebRTC upgrade retry scheduled after failure: ${e}`,i):console.warn(`[Connection] WebRTC upgrade failed: ${e}`,i),t&&console.warn("[Connection] WebRTC upgrade is terminal \u2014 not retrying. Both peers may be on the same page (same-context loopback)."),c$1(`[Connection] WebRTC upgrade fallback: ${e}`),n){this.scheduleUpgradeRetry();return}this.clearUpgradeRetryTimer(),this.teardownWebRTCTransport(`upgrade-failed:${e}`),!t&&this.upgradeRequested&&!this._isClosed&&this.upgradeRetryCount>=B.MAX_UPGRADE_RETRIES&&this.hasRecoverableBasePath()&&this.scheduleUpgradeReDrive();}scheduleUpgradeReDrive(){this.clearUpgradeReDriveTimer(),this.upgradeReDriveCount=Math.min(this.upgradeReDriveCount+1,Number.MAX_SAFE_INTEGER);let e=this.upgradeReDriveCount,t=Math.min(e-1,B.UPGRADE_REDRIVE_DELAYS_MS.length-1),n=B.UPGRADE_REDRIVE_DELAYS_MS[t];this.upgradeReDriveTimer=setTimeout(()=>{this.upgradeReDriveTimer=null,!(this._isClosed||!this.upgradeRequested||this.upgradeAttemptActive)&&(this.isWebRtcApplicationRouteReady()||!this.hasRecoverableBasePath()||(this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,d$2(`[Connection] Re-driving WebRTC upgrade round ${e} after ${n}ms because the retry budget was exhausted on a healthy base route`),this.attemptUpgrade({forceRenegotiate:true})));},n);}clearUpgradeReDriveTimer(){this.upgradeReDriveTimer&&(clearTimeout(this.upgradeReDriveTimer),this.upgradeReDriveTimer=null);}shouldRetryUpgrade(){return !(this._isClosed||!this.upgradeRequested||this.upgradeTerminalFailure||!this.options.rtcConfig||!this.hasRecoverableBasePath()||this.upgradeRetryCount>=B.MAX_UPGRADE_RETRIES)}scheduleUpgradeRetry(){this.clearUpgradeRetryTimer(),this.upgradeRetryCount+=1;let e=this.upgradeRetryCount;this.upgradeRetryTimer=setTimeout(()=>{this.upgradeRetryTimer=null,!(this._isClosed||!this.upgradeRequested||this.upgradeAttemptActive)&&(d$2(`[Connection] Retrying WebRTC upgrade ${e}/${B.MAX_UPGRADE_RETRIES}`),this.attemptUpgrade());},B.UPGRADE_RETRY_DELAY_MS);}clearUpgradeRetryTimer(){this.upgradeRetryTimer&&(clearTimeout(this.upgradeRetryTimer),this.upgradeRetryTimer=null);}startUpgradeAttemptTimeout(e){this.clearUpgradeAttemptTimeoutTimer(),this.upgradeAttemptTimeoutTimer=setTimeout(()=>{this.upgradeAttemptTimeoutTimer=null,!(this._isClosed||!this.upgradeRequested)&&this.upgradeState==="upgrading"&&this.activeNegotiationId===e&&(this.upgradeAttemptActive=false,c$1("[Connection] WebRTC upgrade attempt timed out",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:e}),this.handleUpgradeFailure("upgrade-attempt-timeout"));},B.WEBRTC_UPGRADE_ATTEMPT_TIMEOUT_MS);}clearUpgradeAttemptTimeoutTimer(){this.upgradeAttemptTimeoutTimer&&(clearTimeout(this.upgradeAttemptTimeoutTimer),this.upgradeAttemptTimeoutTimer=null);}teardownWebRTCTransport(e){this.pendingAvailabilityHint=null,this.clearWebRtcDisconnectedGraceTimer(),this.clearUpgradeAttemptTimeoutTimer(),this.clearWebRtcCandidatePairObservation();let t=this.webrtcTransport;if(!t)return;let n=t.getNativeTransport?.();this.traceLifecycle("webrtc-transport-teardown",{reason:e,negotiationId:this.activeNegotiationId,dataChannelReadyState:t.getDataChannelReadyState?.()??null,peerConnectionState:n?.connectionState??null,iceConnectionState:n?.iceConnectionState??null}),this.webrtcTransport=null,this.clearWebRtcApplicationRouteReady(),this.cancelWebRtcApplicationRouteProofForTransport(t,`teardown:${e}`),this.applicationRouteMissingNotified=false,this.stopWebRtcHeartbeat();try{t.close();}catch(i){c$1("[Connection] WebRTC transport close failed",i);}this.reportTransportStatusIfChanged();}startWebRtcHeartbeat(e){this.stopWebRtcHeartbeat();let t=Date.now();c$1("[Connection] WebRTC heartbeat starting",{connectionId:this.id,startedAt:t,config:tt});let n=new Ht(async i=>{c$1("[Connection] WebRTC heartbeat send",{connectionId:this.id,byteLength:i.byteLength,typeId:i[0]}),await e.send(i);},i=>{let o=Date.now()-t;if(c$1("[Connection] WebRTC heartbeat health callback",{connectionId:this.id,health:i,elapsedSinceStartMs:o}),i==="healthy"&&(this.lastWebRtcHeartbeatOkAt=Date.now(),this.webRtcHeartbeatConsecutiveProbeFailures=0,this.isWebRtcApplicationRouteReadyForTransport(e)?this.reportApplicationRouteReady("webrtc-heartbeat-healthy"):this.hasRequiredApplicationCrypto()?this.webrtcTransport===e?this.startWebRtcApplicationRouteProbe(e,"webrtc-heartbeat-healthy"):this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-transport",negotiationId:e.getNegotiationId?.()??null,activeNegotiationId:this.activeNegotiationId}):this.notifyWebRtcApplicationRouteMissing("webrtc-heartbeat-before-crypto")),this.webrtcHealthListeners.forEach(s=>s(i)),i==="stale"){if(this.webRtcHeartbeatProbeInFlight)return;this.webRtcHeartbeatProbeInFlight=true,d$2("[Connection] WebRTC heartbeat stale \u2014 probing transport before fallback"),n.probe(4e3).then(s=>{if(this._isClosed||this.webrtcTransport!==e)return;if(s){this.lastWebRtcHeartbeatOkAt=Date.now(),this.webRtcHeartbeatConsecutiveProbeFailures=0,d$2("[Connection] WebRTC heartbeat probe succeeded \u2014 keeping upgraded transport");return}if(this.webRtcHeartbeatConsecutiveProbeFailures+=1,this.transportStillLikelyAlive(e)){this.lastWebRtcHeartbeatOkAt=Date.now(),d$2("[Connection] WebRTC heartbeat probe failed but transport appears alive \u2014 suppressing fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,consecutiveFailures:this.webRtcHeartbeatConsecutiveProbeFailures});return}if(this.webRtcHeartbeatConsecutiveProbeFailures<2){d$2("[Connection] WebRTC heartbeat probe failed \u2014 awaiting one more failure before fallback",{connectionId:this.id,remoteNodeId:this.remoteNodeId,consecutiveFailures:this.webRtcHeartbeatConsecutiveProbeFailures});return}if(!this.hasRecoverableBasePath()){this.lastWebRtcHeartbeatOkAt=Date.now(),d$2("[Connection] WebRTC heartbeat probe failed but no base recovery path exists \u2014 keeping transport",{connectionId:this.id,remoteNodeId:this.remoteNodeId});return}d$2("[Connection] WebRTC heartbeat probe failed consecutively \u2014 triggering upgrade fallback"),this.stopWebRtcHeartbeat(),this.handleUpgradeFailure("heartbeat-stale-probe-failed");}).finally(()=>{this.webRtcHeartbeatProbeInFlight=false;});}},tt);this.webrtcHeartbeat=n,n.start();}stopWebRtcHeartbeat(){this.webRtcHeartbeatProbeInFlight=false,this.webRtcHeartbeatConsecutiveProbeFailures=0,this.webrtcHeartbeat&&(this.webrtcHeartbeat.stop(),this.webrtcHeartbeat=null);}notifyWebRtcApplicationRouteMissing(e){this.applicationRouteMissingNotified||(this.applicationRouteMissingNotified=true,this.traceLifecycle("webrtc-route-proved-application-crypto-missing",{negotiationId:this.activeNegotiationId,reason:e}),this.options.onApplicationRouteMissing?.({connectionId:this.id,remoteNodeId:this.remoteNodeId,reason:e,negotiationId:this.activeNegotiationId}));}currentWebRtcNegotiationId(e){return this.normalizeNegotiationId(e.getNegotiationId?.())??this.normalizeNegotiationId(this.activeNegotiationId)}createWebRtcApplicationRouteProofId(){let e=new Uint8Array(8);try{globalThis.crypto?.getRandomValues?.(e);}catch{for(let n=0;n<e.byteLength;n+=1)e[n]=Math.floor(Math.random()*256);}let t=Array.from(e).map(n=>n.toString(16).padStart(2,"0")).join("");return `${Date.now().toString(36)}-${t}`}isCurrentWebRtcApplicationRouteProof(e){return !e.cancelled&&this.pendingWebRtcApplicationRouteProof===e&&!this._isClosed&&this.webrtcTransport===e.transport&&this.upgradeState==="upgraded"&&this.currentWebRtcNegotiationId(e.transport)===e.negotiationId}cancelWebRtcApplicationRouteProofForTransport(e,t){let n=this.pendingWebRtcApplicationRouteProof;n?.transport===e&&this.cancelWebRtcApplicationRouteProof(n,t);}cancelWebRtcApplicationRouteProof(e,t){!e||e.cancelled||(e.cancelled=true,e.timer&&(clearTimeout(e.timer),e.timer=null),this.pendingWebRtcApplicationRouteProof===e&&(this.pendingWebRtcApplicationRouteProof=null,this.webRtcApplicationRouteProbeInFlight=false),this.traceLifecycle("webrtc-application-route-proof-cancelled",{reason:t,negotiationId:e.negotiationId,probeId:e.probeId}));}completeWebRtcApplicationRouteProofAck(e){if(!this.isCurrentWebRtcApplicationRouteProof(e)){this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-proof",negotiationId:e.negotiationId,probeId:e.probeId,activeNegotiationId:this.activeNegotiationId});return}this.cancelWebRtcApplicationRouteProof(e,"ack-received"),this.markWebRtcApplicationRouteReady(e.transport);}async sendWebRtcApplicationRouteProofFrame(e,t,n={}){if(this._isClosed||this.webrtcTransport!==e||this.upgradeState!=="upgraded"||n.requireLocalNegotiation===true&&this.currentWebRtcNegotiationId(e)!==t.negotiationId)throw new Error("[Connection] WebRTC route proof cannot be sent on a stale transport");let i=B.textEncoder.encode(JSON.stringify(t)),o=this.protectRequiredApplicationPayload(0,i);if(!o)throw new Error("[Connection] WebRTC route proof requires application crypto");await e.send(o);}tryHandleWebRtcApplicationRouteProofBytes(e,t){try{let n=JSON.parse(B.textDecoder.decode(t));return this.tryHandleWebRtcApplicationRouteProofPayload(n,e)}catch{return false}}tryHandleWebRtcApplicationRouteProofPayload(e,t){if(!this.isWebRtcApplicationRouteProofFrame(e))return false;if(!t)return this.traceLifecycle("webrtc-route-proof-ignored",{reason:"missing-webrtc-transport-context",negotiationId:e.negotiationId,probeId:e.probeId,role:e.role}),true;if(this._isClosed||this.webrtcTransport!==t||this.upgradeState!=="upgraded")return this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-transport",negotiationId:e.negotiationId,probeId:e.probeId,role:e.role,activeNegotiationId:this.activeNegotiationId}),true;if(e.role==="probe")return this.sendWebRtcApplicationRouteProofFrame(t,{type:"#openrtc-webrtc-route-proof",version:1,role:"ack",negotiationId:e.negotiationId,probeId:e.probeId}).catch(i=>{c$1("[Connection] WebRTC application route proof ACK failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:e.negotiationId,probeId:e.probeId,error:i});}),true;if(this.currentWebRtcNegotiationId(t)!==e.negotiationId)return this.traceLifecycle("webrtc-route-proof-ignored",{reason:"stale-negotiation",negotiationId:e.negotiationId,probeId:e.probeId,role:e.role,activeNegotiationId:this.activeNegotiationId}),true;let n=this.pendingWebRtcApplicationRouteProof;return n&&n.transport===t&&n.negotiationId===e.negotiationId&&n.probeId===e.probeId?(this.completeWebRtcApplicationRouteProofAck(n),true):(this.traceLifecycle("webrtc-route-proof-ignored",{reason:"unexpected-ack",negotiationId:e.negotiationId,probeId:e.probeId,activeNegotiationId:this.activeNegotiationId,expectedProbeId:n?.probeId??null}),true)}isWebRtcApplicationRouteProofFrame(e){if(!e||typeof e!="object")return false;let t=e;return t.type==="#openrtc-webrtc-route-proof"&&t.version===1&&(t.role==="probe"||t.role==="ack")&&typeof t.probeId=="string"&&t.probeId.length>0&&t.probeId.length<=B.WEBRTC_APPLICATION_ROUTE_PROOF_MAX_ID_LENGTH&&typeof t.negotiationId=="string"&&t.negotiationId.length>0&&t.negotiationId.length<=B.WEBRTC_APPLICATION_ROUTE_PROOF_MAX_ID_LENGTH}startWebRtcApplicationRouteProbe(e,t){if(this.webRtcApplicationRouteProbeInFlight||this._isClosed||this.webrtcTransport!==e||this.upgradeState!=="upgraded"||this.isWebRtcApplicationRouteReadyForTransport(e))return;let n=this.currentWebRtcNegotiationId(e);if(!n){this.traceLifecycle("webrtc-application-route-probe-deferred",{reason:t,skipReason:"missing-negotiation-id"});return}if(!this.options.applicationCrypto){this.notifyWebRtcApplicationRouteMissing("webrtc-heartbeat-before-crypto");return}let i=this.createWebRtcApplicationRouteProofId(),o={transport:e,negotiationId:n,probeId:i,reason:t,timer:null,cancelled:false};o.timer=setTimeout(()=>{this.cancelWebRtcApplicationRouteProof(o,"timeout"),this.traceLifecycle("webrtc-application-route-probe-deferred",{reason:t,negotiationId:n,probeId:i,skipReason:"ack-timeout"});},B.WEBRTC_APPLICATION_ROUTE_PROOF_TIMEOUT_MS),this.pendingWebRtcApplicationRouteProof=o,this.webRtcApplicationRouteProbeInFlight=true,this.traceLifecycle("webrtc-application-route-probe-start",{reason:t,negotiationId:n,probeId:i}),(async()=>{for(let s of B.WEBRTC_APPLICATION_ROUTE_PROOF_DELAYS_MS){if(!this.isCurrentWebRtcApplicationRouteProof(o)||this.isWebRtcApplicationRouteReadyForTransport(e)||s>0&&(await u(s),!this.isCurrentWebRtcApplicationRouteProof(o)||this.isWebRtcApplicationRouteReadyForTransport(e)))return;try{await this.sendWebRtcApplicationRouteProofFrame(e,{type:"#openrtc-webrtc-route-proof",version:1,role:"probe",negotiationId:n,probeId:i},{requireLocalNegotiation:!0});}catch(a){if(!this.isCurrentWebRtcApplicationRouteProof(o))return;c$1("[Connection] WebRTC application route proof send failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:n,probeId:i,error:a});}}})().finally(()=>{this.pendingWebRtcApplicationRouteProof===o&&(this.webRtcApplicationRouteProbeInFlight=false);});}async sendIrohHeartbeatPong(e){if(e.byteLength<16||!this.writer)return;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getBigUint64(0,false),i=t.getBigInt64(8,false),o=BigInt(Date.now()),s=new ArrayBuffer(29),a=new DataView(s);a.setUint32(0,25,false),a.setUint8(4,4),a.setBigUint64(5,n,false),a.setBigInt64(13,i,false),a.setBigInt64(21,o,false);let c=this.writeMutex,l;this.writeMutex=new Promise(p=>{l=p;});try{await c,this.writer&&await this.writer.write(new Uint8Array(s));}catch{}finally{l();}}onWebRtcHeartbeatHealth(e){this.webrtcHealthListeners.push(e);}onIrohHeartbeatHealth(e){this.irohHealthListeners.push(e);}reportTransportStatusIfChanged(){if(this._isClosed)return;let{activeTransport:e,parallelTransport:t}=this.getTransportStatus(),n=`${e}:${t??""}`;this.lastReportedTransportStatus!==n&&this.pendingTransportStatusReport?.fingerprint!==n&&(this.pendingTransportStatusReport={fingerprint:n,status:{activeTransport:e,parallelTransport:t??null},retryCount:0},this.drainTransportStatusReports());}drainTransportStatusReports(){this.transportStatusReportInFlight||this._isClosed||(this.transportStatusReportInFlight=true,(async()=>{for(;!this._isClosed&&this.pendingTransportStatusReport;){let e=this.pendingTransportStatusReport;if(this.pendingTransportStatusReport=null,this.lastReportedTransportStatus===e.fingerprint)continue;let t=true;try{t=await this.options.onTransportStatusChange?.(e.status)!==!1;}catch(o){t=false,c$1("[Connection] Transport status projection failed",{connectionId:this.id,remoteNodeId:this.remoteNodeId,...e.status,error:o});}if(this._isClosed)return;if(t){this.lastReportedTransportStatus=e.fingerprint;continue}let n=this.getTransportStatus(),i=`${n.activeTransport}:${n.parallelTransport??""}`;i===e.fingerprint&&!this.pendingTransportStatusReport&&e.retryCount<1&&(this.pendingTransportStatusReport={fingerprint:i,status:{activeTransport:n.activeTransport,parallelTransport:n.parallelTransport??null},retryCount:e.retryCount+1},await Promise.resolve());}})().finally(()=>{this.transportStatusReportInFlight=false,!this._isClosed&&this.pendingTransportStatusReport&&this.drainTransportStatusReports();}));}reportApplicationRouteReady(e){if(this._isClosed||!this.isWebRtcApplicationRouteReady())return;let t=Date.now();if(e!=="webrtc-route-ready"&&this.lastApplicationRouteReadyReportAt!==null&&t-this.lastApplicationRouteReadyReportAt<1e3)return;this.lastApplicationRouteReadyReportAt=t;let{activeTransport:n,parallelTransport:i}=this.getTransportStatus();this.options.onApplicationRouteReady?.({connectionId:this.id,remoteNodeId:this.remoteNodeId,activeTransport:n,parallelTransport:i,reason:e});}getTransportStatus(){let e=this.transportType;return {activeTransport:e,parallelTransport:this.resolveParallelTransport(e)}}getTransportLatencySnapshot(){let e=this.webrtcHeartbeat?.latencyMs??null;if(e===null)return {};let t={},{activeTransport:n,parallelTransport:i}=this.getTransportStatus();for(let o of [n,i])o==="webrtc-lan"?t.webrtcLan=e:o==="webrtc-turn"?t.webrtcTurn=e:o==="webrtc"&&(t.webrtc=e);return t}resolveParallelTransport(e){if(this._isClosed)return null;let t=c$2(e);return !t&&this.writer||!t&&f$1(e)&&this.hasRecoverableBasePath()?"iroh-relay":t&&this.isWebRtcDataChannelOpen()?this.webRtcTransportLabel():null}setNativeSignalSender(e){this.nativeSignalSender=e;}traceLifecycle(e,t={}){let n={event:e,connectionId:this.id,localNodeId:this.localNodeId,remoteNodeId:this.remoteNodeId,upgradeState:this.upgradeState,upgradeRequested:this.upgradeRequested,upgradeAttemptActive:this.upgradeAttemptActive,upgradeRetryCount:this.upgradeRetryCount,activeNegotiationId:this.activeNegotiationId,preferredWebRtcRole:this.preferredWebRtcRole,hasWriter:!!this.writer,hasNativeSignalSender:!!this.nativeSignalSender,isClosed:this._isClosed,...t};c$1("[OpenRTC][lifecycle]",n);try{c$1(`[OpenRTC][lifecycle-json] ${JSON.stringify(n)}`);}catch{}}getControlFrameMode(){return this.options.controlFrameMode??"typed"}async sendNativeControlEnvelope(e){return this.getControlFrameMode()!=="native-main"||!this.nativeSignalSender?false:(await this.nativeSignalSender(e),true)}promoteToNativeMainControlRoute(e){this.options={...this.options,controlFrameMode:"native-main"},this.nativeSignalSender=e,this.traceLifecycle("native-main-control-route-promoted");}hasRequiredApplicationCrypto(){return this.options.requireApplicationCrypto!==true||!!this.options.applicationCrypto}clearWebRtcApplicationRouteReady(){this.webRtcApplicationRouteReadyTransport=null,this.webRtcApplicationRouteReadyNegotiationId=null;}isCurrentWebRtcTransportApplicationRouteReady(){return !!this.webrtcTransport&&this.isWebRtcApplicationRouteReadyForTransport(this.webrtcTransport)}isWebRtcApplicationRouteReadyForTransport(e){return this.webRtcApplicationRouteReadyTransport===e&&this.webRtcApplicationRouteReadyNegotiationId===(e.getNegotiationId?.()??this.activeNegotiationId)}markWebRtcApplicationRouteReady(e){if(this.isWebRtcApplicationRouteReadyForTransport(e)||!this.hasRequiredApplicationCrypto()){this.hasRequiredApplicationCrypto()||this.traceLifecycle("webrtc-route-promotion-skipped",{reason:"missing-application-crypto",negotiationId:e.getNegotiationId?.()??this.activeNegotiationId});return}if(this.webrtcTransport!==e){this.traceLifecycle("webrtc-route-promotion-skipped",{reason:"stale-transport",negotiationId:e.getNegotiationId?.()??null,activeNegotiationId:this.activeNegotiationId});return}this.webRtcApplicationRouteReadyTransport=e,this.webRtcApplicationRouteReadyNegotiationId=e.getNegotiationId?.()??this.activeNegotiationId,this.negotiationSwitchCount=0,this.upgradeReDriveCount=0,this.clearUpgradeReDriveTimer(),this.traceLifecycle("webrtc-application-route-ready",{negotiationId:this.webRtcApplicationRouteReadyNegotiationId}),this.reportTransportStatusIfChanged(),this.refreshWebRtcCandidatePairObservation(e),this.reportApplicationRouteReady("webrtc-route-ready");}isWebRtcApplicationRouteReady(){return this.isCurrentWebRtcTransportApplicationRouteReady()&&this.upgradeState==="upgraded"&&!!this.webrtcTransport&&this.hasRequiredApplicationCrypto()}isMoQApplicationRouteReady(){let e=this.options.transportContext;return !this._isClosed&&!!e&&e.isMoQReady()&&this.peerMoQReady&&this.isMoQDataRouteReady(e)&&e.isMoQApplicationRouteProven?.()===true&&this.hasRequiredApplicationCrypto()}isMoQDataRouteReady(e){return typeof e.isMoQDataReady=="function"?e.isMoQDataReady():true}async sendInternalSignal(e){let t=e&&(e.transport==="webrtc"||!e.transport)?{...e,transport:"webrtc",negotiationId:this.normalizeNegotiationId(e.negotiationId)??this.activeNegotiationId??void 0}:e,n={type:"#pluto-signal",content:t};if(this.getControlFrameMode()==="native-main"){if(this.nativeSignalSender)try{await this.nativeSignalSender(n),d$2("[Connection] Sent internal signal via native sender",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});return}catch(i){console.warn("[Connection] Native signal sender failed, falling back to own native-main stream",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null,error:i});}if(this.writer&&typeof this.sendRawIrohFrame=="function")try{let i=new TextEncoder().encode(JSON.stringify(n)),o=new Uint8Array(1+i.byteLength);o[0]=0,o.set(i,1);let s=new ArrayBuffer(4+o.byteLength),a=new DataView(s),c=new Uint8Array(s);a.setUint32(0,o.byteLength,!1),c.set(o,4),await this.sendRawIrohFrame(c),d$2("[Connection] Sent internal signal over own native-main stream",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});return}catch(i){console.warn("[Connection] Own native-main stream signal send failed; falling back to typed iroh",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null,error:i});}}try{if((t?.type==="sdp"||t?.type==="candidate"||t?.type==="renegotiate")&&c$1("[Connection][WebRTC][signal][send]",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:t?.negotiationId??null,signalType:t?.type??null,sdpType:t?.sdp?.type??null,hasSdp:!!t?.sdp?.sdp,hasCandidate:!!t?.candidate}),this.writer&&typeof this.sendRawIrohFrame=="function"){let i=new TextEncoder().encode(JSON.stringify(n)),o=new Uint8Array(1+i.byteLength);o[0]=0,o.set(i,1);let s=new ArrayBuffer(4+o.byteLength),a=new DataView(s),c=new Uint8Array(s);a.setUint32(0,o.byteLength,!1),c.set(o,4),await this.sendRawIrohFrame(c),d$2("[Connection] Sent internal signal over native-main iroh frame",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});return}await this.sendTypedOnTransport("iroh",0,n,{requireApplicationCrypto:!1}),d$2("[Connection] Sent internal signal over iroh (typed-frame fallback)",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null});}catch(i){throw console.warn("[Connection] Failed to send internal signal over iroh",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:t?.type??null,error:i}),i}}receiveInternalSignal(e){this._isClosed||!e||typeof e!="object"||this.handleInternalSignal({type:"#pluto-signal",content:e});}handleInternalSignal(e){if(!(e.content&&(e.content.transport==="webrtc"||!e.content.transport)))return;let n=e.content,i=typeof n?.type=="string"?n.type:null,o=n?.sdp&&typeof n.sdp=="object"&&typeof n.sdp.type=="string"?n.sdp.type:null,s=i==="sdp"&&o==="offer",a=this.normalizeNegotiationId(n?.negotiationId);if((i==="sdp"||i==="candidate"||i==="renegotiate")&&c$1("[Connection][WebRTC][signal][recv]",{connectionId:this.id,remoteNodeId:this.remoteNodeId,negotiationId:a??null,signalType:i,sdpType:o,hasSdp:!!n?.sdp?.sdp,hasCandidate:!!n?.candidate,upgradeState:this.upgradeState}),i==="renegotiate"){let S=this.lastWebRtcHeartbeatOkAt===null?null:Date.now()-this.lastWebRtcHeartbeatOkAt,I=this.lastWebRtcDataChannelOpenAt===null?null:Date.now()-this.lastWebRtcDataChannelOpenAt,k=S!==null&&S<=B.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS||this.isWebRtcDataChannelOpen()&&I!==null&&I<=B.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS;if(this.isWebRtcDataChannelOpen()||this.upgradeState==="upgraded"){let _=!!a&&a!==this.activeNegotiationId&&a.startsWith("conn-")&&!a.startsWith(`conn-${this.id}-`)&&this.getDeterministicWebRtcRole()==="responder";if(k&&!_){c$1("[Connection] Ignoring WebRTC renegotiate request; route is provably live",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,heartbeatSilenceMs:S,dataChannelOpenForMs:I});return}c$1("[Connection] Honoring WebRTC renegotiate by tearing down the current route",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,priorState:this.upgradeState,heartbeatSilenceMs:S,dataChannelOpenForMs:I,reason:_?"fresh-remote-generation":"stale-route"}),this.clearUpgradeRetryTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,this.pendingSignals=[],this.stopWebRtcHeartbeat(),this.teardownWebRTCTransport(_?"inbound-renegotiate-fresh-generation":"inbound-renegotiate-stale-route"),this.setUpgradeState("none");}else if(this.upgradeState==="upgrading"&&this.webrtcTransport)if(!!a&&a!==this.activeNegotiationId&&a.startsWith("native-"))c$1("[Connection] Honoring fresh native WebRTC renegotiate during in-flight upgrade",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId}),this.clearUpgradeRetryTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,this.pendingSignals=[],this.stopWebRtcHeartbeat(),this.teardownWebRTCTransport("inbound-native-renegotiate-while-upgrading"),this.setUpgradeState("none"),this.preferredWebRtcRole=this.getDeterministicWebRtcRole();else {c$1("[Connection] Ignoring WebRTC renegotiate request while an upgrade is already in flight",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}}let c=!!a&&!!this.activeNegotiationId&&a!==this.activeNegotiationId;if(c&&(i==="sdp"||i==="candidate")&&(this.isWebRtcDataChannelOpen()||this.upgradeState==="upgraded")){c$1("[Connection] Ignoring delayed WebRTC signal for a non-active generation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:i,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let l=i==="sdp"&&s||i==="renegotiate"&&this.upgradeState!=="upgrading"&&this.upgradeState!=="upgraded";if(c&&!l){c$1("[Connection] Ignoring stale WebRTC signal from a previous negotiation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalType:i,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let p=!!this.activeNegotiationId?.startsWith("native-"),u=!!a?.startsWith("native-"),g=s&&!!a?.startsWith(`conn-${this.id}-`);if(c&&l&&this.upgradeState==="upgrading"&&this.preferredWebRtcRole==="responder"&&p&&g){c$1("[Connection] Ignoring reflected WebRTC offer during active native negotiation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let y=s&&!!a?.startsWith(`conn-${this.id}-`);if(c&&l&&y&&!p&&this.getDeterministicWebRtcRole()==="initiator"&&(this.upgradeState==="upgrading"||this.upgradeAttemptActive)){c$1("[Connection] Ignoring competing inbound WebRTC offer as glare-impolite initiator",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId});return}let m=y&&!u;if(c&&l&&m&&this.negotiationSwitchCount>=B.MAX_NEGOTIATION_SWITCHES){console.warn("[Connection] Ignoring competing inbound WebRTC offer: negotiation switch budget exhausted",{connectionId:this.id,remoteNodeId:this.remoteNodeId,signalNegotiationId:a,activeNegotiationId:this.activeNegotiationId,switchBudget:B.MAX_NEGOTIATION_SWITCHES});return}c&&l&&(m&&(this.negotiationSwitchCount+=1),c$1("[Connection] Switching to a fresh inbound WebRTC negotiation",{connectionId:this.id,remoteNodeId:this.remoteNodeId,priorNegotiationId:this.activeNegotiationId,nextNegotiationId:a,priorState:this.upgradeState,signalType:i,switchCount:this.negotiationSwitchCount,budgetedNegotiationSwitch:m}),this.clearUpgradeRetryTimer(),this.upgradeAttemptActive=false,this.upgradeRetryCount=0,this.upgradeTerminalFailure=false,this.pendingSignals=[],this.stopWebRtcHeartbeat(),this.teardownWebRTCTransport("inbound-negotiation-switch")),a&&(!this.activeNegotiationId||c)&&(this.activeNegotiationId=a);let v=!this.webrtcTransport||this.upgradeState==="failed"||c&&this.upgradeState!=="upgrading";if(l&&v&&this.options.rtcConfig&&!this._isClosed){c$1("[Connection] Auto-requesting WebRTC upgrade from incoming signal",{connectionId:this.id,remoteNodeId:this.remoteNodeId,currentState:this.upgradeState,signalType:i,sdpType:o,signalNegotiationId:a,preferredRole:s?"responder":this.preferredWebRtcRole}),s?this.preferredWebRtcRole="responder":i==="renegotiate"&&a?.startsWith("native-")&&(this.preferredWebRtcRole=this.getDeterministicWebRtcRole()),this.upgradeRequested=true,this.upgradeTerminalFailure=false,this.pendingSignals=[n],this.attemptUpgrade(a);return}n.transport||(n.transport="webrtc"),this.webrtcTransport?.handleSignalingMessage?this.webrtcTransport.handleSignalingMessage(n):(!a||!this.activeNegotiationId||a===this.activeNegotiationId)&&this.pendingSignals.push(n);}createNegotiationId(){return `conn-${this.id}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}getDeterministicWebRtcRole(){return this.localNodeId>this.remoteNodeId?"initiator":"responder"}normalizeNegotiationId(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}};B.textDecoder=new TextDecoder("utf-8",{fatal:true}),B.textEncoder=new TextEncoder,B.UPGRADE_RETRY_DELAY_MS=1e3,B.MAX_UPGRADE_RETRIES=5,B.UPGRADE_REDRIVE_DELAYS_MS=[5e3,1e4,15e3],B.WEBRTC_DISCONNECTED_GRACE_MS=4e3,B.MAX_PENDING_MESSAGES=256,B.DEFAULT_APPLICATION_CRYPTO_WAIT_MS=1e4,B.WEBRTC_UPGRADE_ATTEMPT_TIMEOUT_MS=vi+3e3,B.MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS=256,B.WEBRTC_APPLICATION_ROUTE_PROOF_TIMEOUT_MS=6500,B.WEBRTC_APPLICATION_ROUTE_PROOF_DELAYS_MS=[0,250,750,1500,3e3],B.WEBRTC_APPLICATION_ROUTE_PROOF_MAX_ID_LENGTH=256,B.WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS=12e3,B.MAX_NEGOTIATION_SWITCHES=6,B.FOREGROUND_PROBE_TIMEOUT_MS=2e3;var de=B;async function ge(r,e,t){await B$2(r,e)&&c$1("[Client][CONNECT] Closed unused bi stream after adopting existing connection",{remoteNodeId:t??null,reason:e});}async function vr(r){try{await r.refreshApplicationRouteHandshake(r.connection,r.reason,{forceReciprocal:!0});return}catch(e){let t=r.wasmClient.remote_session_admission_ready_for_ticket;if(!r.hasCompoundTicketToken||typeof t!="function")throw e;let n;try{n=await t.call(r.wasmClient,r.ticket),r.assertActive();}catch{throw e}if(n)throw e;c$1("[Client][AUTH] repairing admission after physical replacement",{nodeId:r.nodeId,connectionId:r.connection.id,reason:r.reason}),await r.representTicket(`${r.reason}:current-generation-admission-repair`),r.assertActive(),await r.refreshApplicationRouteHandshake(r.connection,`${r.reason}:after-current-generation-admission-repair`,{forceReciprocal:true});}}function Fe(){return new Error("Transport-only ticket-only channels do not expose a main message stream.")}var ki=class extends de{constructor(t){let n=new WritableStream({write(){throw Fe()}}).getWriter(),i=new ReadableStream().getReader();super(t.connectionId,t.localNodeId,t.remoteNodeId,n,i,{...t.options,controlFrameMode:"native-main",hasBaseApplicationStream:false});this.input=t;this.transportDisconnectStarted=false;}async send(){throw Fe()}async sendMedia(){throw Fe()}async sendControl(){throw Fe()}async sendOnTransport(t,n){throw Fe()}async sendRawIrohFrame(){throw Fe()}async disconnect(){await super.disconnect(),!this.transportDisconnectStarted&&(this.transportDisconnectStarted=true,await this.disconnectNodeTransportBestEffort());}async disconnectNodeTransportBestEffort(){try{await this.input.disconnectNodeTransport(this.remoteNodeId);}catch{}}};function Cr(r){return new ki(r)}var jt=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}async connect(e,t=2e4,n,i,o){if(this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive(),!e||!e.trim())throw new Error("connect requires a non-empty endpoint ticket");let s=e.trim(),{irohTicket:a,tokenSuffix:c}=se(s),l=this.deps.getWasmClient(),p;try{p=await l.endpoint_id_from_ticket(a);}catch(F){throw new Error(`connect requires a valid endpoint ticket: ${F?.message||F}`)}this.assertActive();let u=null;if(c){let F=ue(a,c);typeof F?.t=="string"&&(u=F.t,this.deps.rememberRouteRepairTokenForNode(p,F.t,c));}let g=this.deps.getDeterministicConnectionId(p),y=this.deps.getRegisteredChannel(i??null),m=this.deps.isTransportOnlyChannel(i);c$1("[Client][CONNECT] resolved ticket target",{nodeId:p,connectionId:g,channelId:i??null,registeredChannel:y?{id:y.id,readiness:y.readiness,promotionPolicy:y.promotionPolicy,signalingPolicy:y.signalingPolicy}:null,transportOnlyChannel:m,hasCompoundTicketToken:!!u});let v=this.ctx.registry.get(g);if(v&&!u){let F=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,o?.approvedScope??null,u,v);return F&&this.deps.initializeConnectionTrust(v,F),await this.deps.refreshApplicationRouteHandshake(v,"connect-existing"),this.assertActive(),v}let S=c?ue(a,c):null,I=o?.approvedScope??null;!I&&typeof S?.s=="string"&&S.s.trim()&&(I=S.s.trim());let k=async F=>{d$2(`Initiating managed transport dial to ${p} (${F})...`);let W=await this.deps.ensureWasmManagedTransport(s,n??null,{skipIfConnected:o?.admissionAlreadyPresented===true,admissionAlreadyPresented:o?.admissionAlreadyPresented===true,timeoutMs:t});if(this.assertActive(),W.approvedScope)I=W.approvedScope,this.deps.setSessionTokenApprovedScope(g,W.approvedScope);else if(u&&!I){await this.schedulePeerReconciliationBestEffort("managed-dial-scope-lookup"),this.assertActive();let U=this.deps.getSessionTokenApprovedScope(g);if(typeof U=="string"&&U.trim())I=U.trim();else {let ne=this.deps.getPeerState(n??p)?.scopes?.[0];typeof ne=="string"&&ne.trim()&&(I=ne.trim());}}},T=async(F,W)=>vr({connection:F,reason:W,nodeId:p,ticket:s,hasCompoundTicketToken:!!u,wasmClient:l,assertActive:()=>this.assertActive(),refreshApplicationRouteHandshake:(U,Z,ne)=>this.deps.refreshApplicationRouteHandshake(U,Z,ne),representTicket:k});try{await k("initial");}catch(F){if(this.deps.isLocalIrohRuntimeNotInitializedError(F)){let W=await this.deps.recoverLocalIrohRuntime("connect-managed-dial");if(this.assertActive(),!W)throw new Error(`Failed to initiate managed transport dial to ${p}: ${F?.message||F}`);try{await k("after-local-runtime-recovery");}catch(U){throw new Error(`Failed to initiate managed transport dial to ${p} after local Iroh runtime recovery: ${U?.message||U}`)}}else throw F}if(this.assertActive(),u){let F=I??o?.approvedScope??null,W=this.ctx.registry.get(g);if(W&&!W.isClosed){let U=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,F,u,W);return this.deps.assignConnectionChannel(W,i),this.deps.initializeConnectionTrust(W,U),U&&this.deps.bindConnectionDeviceIdInRust(W,U),this.deps.approveSessionTokenNode(p),this.deps.approveSessionTokenConnection(W.id),this.deps.applySessionTokenTrustApproval(W,F,"dialer-compound-ticket-existing-connection"),this.deps.announceConnectionWhenStable(W),c$1("[Client][AUTH] adopted token-approved existing connection",{nodeId:p,connectionId:W.id,localNodeId:W.localNodeId,remoteNodeId:W.remoteNodeId,approvalScope:I||null}),await T(W,"dialer-compound-ticket-existing-connection"),this.assertActive(),W}}if(m){let F;F=Cr({connectionId:g,localNodeId:this.ctx.localNodeId,remoteNodeId:p,options:{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(p),applicationCrypto:this.deps.getOptions()?.applicationCrypto,requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),onTransportStatusChange:Z=>this.deps.handleConnectionTransportStatus(F,Z.activeTransport,Z.parallelTransport),onApplicationRouteReady:Z=>{this.deps.handleConnectionApplicationRouteReady(F,Z);},onApplicationRouteMissing:Z=>{this.deps.handleConnectionApplicationRouteMissing(g,Z);}},disconnectNodeTransport:Z=>this.deps.disconnectNodeTransport(Z)});let W=I??o?.approvedScope??null,U=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,W,u,F);return this.deps.assignConnectionChannel(F,i),this.deps.initializeConnectionTrust(F,U),this.deps.registerConnection(F),U&&this.deps.bindConnectionDeviceIdInRust(F,U),u&&(this.deps.approveSessionTokenNode(p),this.deps.approveSessionTokenConnection(F.id),this.deps.applySessionTokenTrustApproval(F,W,"dialer-compound-ticket-transport-only")),this.deps.announceConnectionWhenStable(F),c$1("[Client][AUTH] using transport-only channel connection",{nodeId:p,connectionId:F.id,channelId:i??null,signalingMode:this.deps.getOptions().signalingMode??"hosted",hasCompoundTicketToken:!!u}),F}let D=await this.openMainBiStream(p,t);this.disposed&&(await ge(D,"dial-coordinator-disposed-after-open",p),this.assertActive());let _=this.ctx.registry.get(g);if(_&&!_.isClosed){let F=I??o?.approvedScope??null,W=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,F,u,_);return await ge(D,"late-dial-adopted-existing-connection",p),this.deps.assignConnectionChannel(_,i),this.deps.initializeConnectionTrust(_,W),W&&this.deps.bindConnectionDeviceIdInRust(_,W),u&&(this.deps.approveSessionTokenNode(p),this.deps.approveSessionTokenConnection(_.id),this.deps.applySessionTokenTrustApproval(_,F,"dialer-compound-ticket-late-existing-connection")),this.deps.announceConnectionWhenStable(_),c$1("[Client][CONNECT] adopted existing connection after async dial completed",{nodeId:p,connectionId:_.id,channelId:i??null,approvalScope:I||null,upgradeState:typeof _.getUpgradeState=="function"?_.getUpgradeState():null}),await T(_,"late-dial-adopted-existing-connection"),this.assertActive(),_}let E$1=this.deps.shouldUseNativeMainFramingForPeer(p,this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,I??o?.approvedScope??null,u,null),!!u);E$1&&(await E(this.deps.writeNativeMainLabelHeaderOnBiStream(D,p),4e3,"writeNativeMainLabelHeaderOnBiStream"),this.disposed&&(await ge(D,"dial-coordinator-disposed-after-native-label",p),this.assertActive()));let A=this.createConnection({connId:g,nodeId:p,biStream:D,useNativeMainFraming:E$1});this.deps.assignConnectionChannel(A,i);let j=I??o?.approvedScope??null,q=this.deps.resolveExpectedDeviceIdForSessionTokenScope(n,j,u,A);if(this.deps.initializeConnectionTrust(A,q),this.disposed&&(await this.disconnectConnectionBestEffort(A),this.assertActive()),this.deps.registerConnection(A),q&&this.deps.bindConnectionDeviceIdInRust(A,q),u){await this.schedulePeerReconciliationBestEffort("compound-ticket-connect"),this.assertActive();let F=this.deps.getPeerState(A.id)??this.deps.getPeerState(p),W=this.deps.consumePendingSessionTokenTrustApproval(A.id);W.approved?this.deps.applySessionTokenTrustApproval(A,W.scope??j,"dialer-compound-ticket-pending"):F?.admissionState==="admitted"&&this.deps.applySessionTokenTrustApproval(A,j,"dialer-compound-ticket-rust-admitted"),c$1("[Client][AUTH] token-approved connection registered locally",{nodeId:p,connectionId:A.id,localNodeId:A.localNodeId,remoteNodeId:A.remoteNodeId,rustAdmissionState:F?.admissionState??null,pendingApproval:W.approved});}return this.deps.announceConnectionWhenStable(A),c$1("[Client][HANDSHAKE] sending hello (dial path)",{connectionId:A.id,remoteNodeId:A.remoteNodeId}),this.sendDialHelloInBackground(A),A}async connectPeer(e){this.assertActive();let t=e.scope??"persistent";if(!e.ticket)throw new Error("connectPeer requires a ticket.");c$1("[Client][connectPeer] starting",{scope:t,channelId:e.channelId??null,hasDeviceId:!!e.deviceId,ticketLength:e.ticket.length});let n=se(e.ticket).tokenSuffix!==null;if(!n&&!this.deps.sessionTokenScopeAllowsDeviceBinding(t))throw new Error(`connectPeer requires a compound ticket with a session token for restricted scope '${t}'.`);if(e.respectManualDisconnect&&this.hasManualDisconnectProjection(e.deviceId))throw new Error(`connectPeer suppressed by manual disconnect for device ${e.deviceId}`);e.deviceId&&!n&&!e.respectManualDisconnect&&this.deps.clearManualDisconnectProjection(e.deviceId);let i=await this.connect(e.ticket,Math.max(1,e.timeoutMs??2e4),e.deviceId,e.channelId);this.assertActive();let o=this.deps.getSessionTokenApprovedScope(i.id),s=[...o?[o]:[],...this.deps.getPeerScopes(i.id)].filter((g,y,m)=>m.indexOf(g)===y),a=s.length>0?s:[t],l=s.length===0||a.some(g=>this.deps.sessionTokenScopeAllowsDeviceBinding(g))?e.deviceId:void 0,p=this.deps.resolvePromotionEligibility({connectionId:i.id,nodeId:i.remoteNodeId,deviceId:l??void 0}),u=l||i.remoteNodeId||i.deviceId||i.id;l&&n&&this.deps.clearManualDisconnectProjection(l),this.deps.hasRustPeerLifecycleProjection()?this.schedulePeerReconciliationInBackground("connect-peer"):this.deps.dispatchLiveConnectionProjection(i,{trustProjection:null,promotionEligible:p,peerId:u,deviceId:l,ticket:e.ticket,scopes:a,applicationRouteReady:this.deps.hasApplicationRouteForConnection(i),webRtcApplicationRouteReady:this.deps.isWebRtcApplicationRouteReadyForConnection(i)});for(let g of a)this.deps.addPeerScope(u,g);return i}hasManualDisconnectProjection(e){let t=typeof e=="string"?e.trim():"";if(!t)return false;let n=this.deps.getWasmClient();if(n&&typeof n.is_auto_connect_excluded=="function"&&n.is_auto_connect_excluded(t)===true)return true;let i=this.deps.getPeerState(t);if(!i)return false;if(i.manualDisconnect===true)return true;let o=i,s=[i.error,o.lastDisconnectReason].filter(a=>typeof a=="string"&&a.length>0).join(" ");return /manual disconnect/i.test(s)}async openMainBiStream(e,t){this.assertActive();let n=null,i=0,o=500,s=Math.ceil(t/o),a=this.deps.getWasmClient(),c=a.open_native_main_control_bi;if(typeof c!="function")throw new Error("[Client][NATIVE-MAIN] open_native_main_control_bi is unavailable on this WASM build; the admission and key-agreement control plane cannot use a protected application stream. Rebuild the OpenRTC WASM runtime.");for(;i<s;){this.assertActive();try{n=await E(c.call(a,e),2500,"wasmClient.open_native_main_control_bi"),this.disposed&&(await ge(n,"dial-coordinator-disposed-during-open",e),this.assertActive());break}catch(l){if(this.disposed)throw l;i++,await u(o);}}if(!n)throw new Error(`Failed to establish connection to ${e} after ${t} ms`);return n}assertActive(){if(this.disposed)throw new Error("Connection dial cancelled because the client was disposed.")}createConnection(e){let{connId:t,nodeId:n,biStream:i,useNativeMainFraming:o}=e,s;if(s=new de(t,this.deps.getLocalNodeId(),n,i.send.getWriter(),i.recv.getReader(),{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(n),applicationCrypto:this.deps.getOptions()?.applicationCrypto,requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),controlFrameMode:o?"native-main":"typed",onTransportStatusChange:a=>this.deps.handleConnectionTransportStatus(s,a.activeTransport,a.parallelTransport),onApplicationRouteReady:a=>{this.deps.handleConnectionApplicationRouteReady(s,a);},onApplicationRouteMissing:a=>{this.deps.handleConnectionApplicationRouteMissing(t,a);}}),o&&this.deps.getWasmClient()){let a=this.deps.getWasmClient();s.setNativeSignalSender(async c=>{await this.deps.sendNativeSignalEnvelope(s,n,c,a);}),c$1("[Client][NATIVE-MAIN] Attached native signal sender to dial-path connection",{connectionId:s.id,remoteNodeId:n});}return s}sendDialHelloInBackground(e){let t=n=>{this.disposed||console.warn("[Client][TRUST] Failed to send outgoing handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:n});};try{Promise.resolve(this.deps.sendTransportHandshake(e,"hello")).then(()=>{this.disposed||this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,"protected-hello:dial");}).catch(t);}catch(n){t(n);}}schedulePeerReconciliationBestEffort(e){try{return Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>[])}catch{return Promise.resolve([])}}schedulePeerReconciliationInBackground(e){if(!this.disposed)try{this.schedulePeerReconciliationBestEffort(e);}catch{}}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}};var Gt=class{constructor(e){this.deps=e;this.connectionListeners=[];this.disconnectionListeners=[];this.announcedConnections=new Set;this.stabilityWaitEpochs=new Map;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.connectionListeners=[],this.disconnectionListeners=[],this.announcedConnections.clear(),this.stabilityWaitEpochs.clear());}findLiveConnectionForRemoteNode(e,t){let n=this.deps.registry.get(t);if(n&&!n.isClosed)return n;for(let i of this.deps.registry.values())if(i.remoteNodeId===e&&!i.isClosed)return i;return null}cleanupReplacedConnection(e){this.disposed||(this.deps.registry.delete(e),this.forgetAnnouncedConnection(e));}healOrphanTsConnection(e){if(this.disposed)return;let t=this.deps.registry.get(e);!t||t.isClosed||c$1("[Client][PEER-RECONCILE] observed orphan TS connection",{connectionId:e});}registerConnection(e){if(this.disposed)return;let t=this.deps.registry;t.clearLocalTerminalClose(e.id);let n=t.get(e.id);if(t.set(e.id,e),n&&n!==e&&!n.isClosed&&this.disconnectBestEffort(n),typeof e.setApplicationCrypto=="function"){let s=this.deps.resolveApplicationCryptoForPeer(e.remoteNodeId,e);s&&e.setApplicationCrypto(s);}this.flushPendingNativeMainHandshakesBestEffort(e.remoteNodeId,"connection-registered"),this.flushPendingNativeMainSignalsBestEffort(e.remoteNodeId,"connection-registered");let i=this.deps.getConnectionTrustState(e.id),o=i?.verifiedDeviceId??i?.expectedDeviceId??this.deps.getKnownDeviceIdByNodeId(e.remoteNodeId)??null;o?this.deps.bindConnectionDeviceIdInRust(e,o):this.lookupConnectionDeviceBindingInBackground(e),i?.verified&&o&&this.deps.retireSupersededConnections(e,o,"registered-trusted-replacement"),typeof e.onUpgradeStateChange=="function"&&e.onUpgradeStateChange(()=>{this.disposed||!t.has(e.id)||e.isClosed||this.deps.hasRustPeerLifecycleProjection()||this.deps.applyConnectionTrustProjection(e);}),this.deps.hasRustPeerLifecycleProjection()?this.schedulePeerReconciliationBestEffort("register-connection"):this.deps.applyConnectionTrustProjection(e),typeof e.reportTransportStatusIfChanged=="function"&&e.reportTransportStatusIfChanged(),typeof e.onWebRTCBinaryMessage=="function"&&e.onWebRTCBinaryMessage(s=>this.disposed?false:this.deps.maybeHandleWebRTCExplicitFileEnvelope(e,s)),e.onMessage(s=>{if(!this.disposed)try{Promise.resolve(this.deps.handleMessage(e,s)).catch(a=>{this.disposed||console.warn("[Client] connection message handler failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:a});});}catch(a){this.disposed||console.warn("[Client] connection message handler failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:a});}}),e.onDisconnect(()=>{if(this.disposed||(e.peerMoQReady=false,t.get(e.id)!==e))return;let s=this.deps.hasRustPeerLifecycleProjection();s||t.markLocalTerminalClose(e.id);let a=this.deps.getExistingPeerProjectionForDisconnect(e);t.delete(e.id),this.deps.cleanupConnectionState(e.id,s?"physical-route":"logical-terminal"),s?this.schedulePeerReconciliationBestEffort("connection-disconnect"):this.deps.dispatchLiveConnectionProjection(e,{trustProjection:null,promotionEligible:this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId}),existingProjection:a,terminalTransportClose:true,applicationRouteReady:false,webRtcApplicationRouteReady:false}),this.announcedConnections.delete(e.id)&&this.emitDisconnection(e);});}announceConnectionWhenStable(e){let t=(this.stabilityWaitEpochs.get(e.id)??0)+1;this.stabilityWaitEpochs.set(e.id,t),(async()=>{if(this.disposed)return;let n=await this.waitForStableConnection(e);if(!this.disposed&&this.deps.registry.get(e.id)===e&&this.stabilityWaitEpochs.get(e.id)===t){if(!n){if(!e.isClosed){let i=this.deps.getConnectionTrustState(e.id);console.warn(`[Client] Suppressing unstable connection ${e.id}`,{deviceId:e.deviceId,upgradeState:e.getUpgradeState?.()??null,transportStatus:typeof e.getTransportStatus=="function"?e.getTransportStatus():null,trustRequired:i?.required??null,trustVerified:i?.verified??null,trustFailed:i?.failed??null,trustFailureReason:i?.failureReason??null});}return}this.announcedConnections.has(e.id)||(this.announcedConnections.add(e.id),this.emitConnection(e));}})();}async waitForStableConnection(e){if(this.disposed)return false;let t=this.deps.initializeConnectionTrust(e),n=false,i=false,o=this.deps.hasApplicationRouteForConnection(e),s=this.deps.allowsTransportOnlyStability(e),a=null,c=this.deps.getWasmClient(),l=c&&typeof c.wait_for_settled_peer=="function"?c.wait_for_settled_peer:null;if(l)try{let g=await l.call(c,e.deviceId,this.deps.stableTimeoutMs),y=e.getUpgradeState;if(a=typeof y=="function"?y.call(e):null,o=this.deps.hasApplicationRouteForConnection(e),g?.settledReady&&(!t.required||t.verified)&&(o||s))return !0;if(t.required&&t.failed)return console.warn("[Client][STABILITY] trust failed during settled-peer gate",{connectionId:e.id,deviceId:e.deviceId,settledReady:g?.settledReady??null,trustRequired:t.required,trustVerified:t.verified,trustFailed:t.failed,trustFailureReason:t.failureReason??null,upgradeState:a}),!1}catch{}let p=Date.now(),u$1=null;for(;Date.now()-p<this.deps.stableTimeoutMs;){if(this.disposed||e.isClosed||t.required&&t.failed)return false;let g=await this.deps.isCoreConnectionHealthy(e.deviceId);if(this.disposed)return false;let y=e.getUpgradeState;a=typeof y=="function"?y.call(e):null;let m=a==="upgraded";if(n=g,i=m,o=this.deps.hasApplicationRouteForConnection(e),g||m){if(u$1===null&&(u$1=Date.now()),Date.now()-u$1>=this.deps.stableWindowMs&&(!t.required||t.verified)&&(o||s))return true}else u$1=null;await u(this.deps.stablePollMs);}return console.warn("[Client][STABILITY] connection did not become stable before timeout",{connectionId:e.id,deviceId:e.deviceId,trustRequired:t.required,trustVerified:t.verified,trustFailed:t.failed,trustFailureReason:t.failureReason??null,lastCoreHealthy:n,lastUpgradedTransportHealthy:i,lastApplicationRouteReady:o,lastUpgradeState:a,transportStatus:typeof e.getTransportStatus=="function"?e.getTransportStatus():null}),false}onConnection(e){return this.disposed?()=>{}:(this.connectionListeners.push(e),()=>{this.connectionListeners=this.connectionListeners.filter(t=>t!==e);})}onDisconnection(e){return this.disposed?()=>{}:(this.disconnectionListeners.push(e),()=>{this.disconnectionListeners=this.disconnectionListeners.filter(t=>t!==e);})}isConnectionAnnounced(e){return this.announcedConnections.has(e)}forgetAnnouncedConnection(e){this.announcedConnections.delete(e);}emitConnection(e){for(let t of [...this.connectionListeners])try{t(e);}catch(n){console.warn("[Client] connection listener failed",n);}}emitDisconnection(e){for(let t of [...this.disconnectionListeners])try{t(e);}catch(n){console.warn("[Client] disconnection listener failed",n);}}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}flushPendingNativeMainHandshakesBestEffort(e,t){if(!this.disposed)try{Promise.resolve(this.deps.flushPendingNativeMainHandshakesForNode(e,t)).catch(()=>{});}catch{}}flushPendingNativeMainSignalsBestEffort(e,t){if(!this.disposed)try{Promise.resolve(this.deps.flushPendingNativeMainSignalsForNode(e,t)).catch(()=>{});}catch{}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}lookupConnectionDeviceBindingInBackground(e){try{Promise.resolve(this.deps.searchDevices()).then(()=>{if(this.disposed)return;let t=this.deps.getKnownDeviceIdByNodeId(e.remoteNodeId);t&&this.deps.bindConnectionDeviceIdInRust(e,t);}).catch(()=>{});}catch{}}};var qt=class{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}async handleMessage(e,t){if(this.disposed)return;if(!!t&&typeof t=="object"&&t.type==="handshake"){if(!await this.handleHandshake(e,t)||this.disposed)return}else if((this.deps.requiresManagedTransportTrust()||this.deps.usesTicketOnlySignalingMode())&&!this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)){console.warn("[Client][SESSION-TOKEN] Dropping application message before admission",{connectionId:e.id,remoteNodeId:e.remoteNodeId}),this.disconnectBestEffort(e);return}this.deps.dispatchMessage(e,t);}async handleHandshake(e,t){if(this.disposed)return false;let n=t.action??"hello",i=await this.deps.handleApplicationKeyAgreement(e,t).catch(v=>this.disposed?{remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null}:(console.warn("[Client][KEY-AGREEMENT] Handshake key agreement failed; closing connection",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:v}),this.disconnectBestEffort(e),{remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null}));if(this.disposed)return false;let o=t.capabilities&&typeof t.capabilities=="object"?t.capabilities:void 0,s=!!o&&Object.prototype.hasOwnProperty.call(o,"webrtc"),a=!!o&&Object.prototype.hasOwnProperty.call(o,"moq"),c=typeof t.moq=="boolean",l=s&&o.webrtc===true,p=a?o.moq===true:!!t.moq,u=this.deps.isWebRTCTransportEnabled(),g=this.deps.requiresManagedTransportTrust(),y=v=>{if(this.disposed||e.isClosed||!l||!u)return;let S=this.deps.getLocalNodeId();this.deps.usesTicketOnlySignalingMode()&&S&&e.remoteNodeId&&S.localeCompare(e.remoteNodeId)<0||(c$1("[Client][HANDSHAKE] requesting WebRTC upgrade from handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:n,reason:v}),e.requestWebRTCUpgrade(v));};if(n==="hello"){let v=await this.deps.validateIncomingSessionTokenWithRetry(t.sessionToken??"",e.id,{remoteNodeId:e.remoteNodeId,source:"handshake-hello",tokenPayload:typeof t.sessionTokenPayload=="string"?t.sessionTokenPayload:void 0});if(this.disposed)return false;if(!v.ok)return console.warn("[Client][SESSION-TOKEN] Rejecting connection \u2014 invalid session token",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:v.reason,hasToken:!!t.sessionToken}),this.disconnectBestEffort(e),false;t.sessionToken&&this.deps.applySessionTokenTrustApproval(e,v.scope??null,"handshake-hello");}c$1("[Client][HANDSHAKE] received",{action:n,connectionId:e.id,remoteNodeId:e.remoteNodeId,channelId:t.channelId??this.deps.getConnectionChannelId(e.id)??null,remoteSupportsWebRTC:l,remoteSupportsMoQ:p,localWebRTCEnabled:u,hasSessionToken:!!t.sessionToken,hasTransportTrust:!!t.transportTrust});let m=t.capabilities?.applicationKeyAgreement===true&&i.cryptoReady?i.replyAction:null;return m&&this.sendHandshakeWithRecoveryInBackground(e,m,null,"application-key-agreement-confirmation","[Client][KEY-AGREEMENT] Failed to advance reciprocal key agreement",i.replyClaimId?()=>this.deps.releaseApplicationKeyAgreementReply(e.id,m,i.replyClaimId):void 0),s&&(e.remoteSupportsWebRTC=l),!g&&u&&l&&(n==="hello"||n==="capability-update"||n==="response"&&!t.transportTrust)&&y(`handshake:${n}`),(a||c)&&(p&&this.deps.getMoQState()==="ready"?(d$2(`[Client] Peer ${e.deviceId.substring(0,6)} supports MoQ. Upgrading...`),this.deps.enableMoQForConnection(e)):p||(e.peerMoQReady=false,this.deps.forgetMoQPeerSubscription(e.id))),this.deps.assignConnectionChannel(e,t.channelId??null),t.transportTrust||g?this.handleTransportTrustHandshakeInBackground(e,t,n,g,y):(t.action==="hello"||!t.action)&&t.sessionToken&&m!=="response"&&this.sendHandshakeWithRecoveryInBackground(e,"response",null,"session-token-response","[Client][SESSION-TOKEN] Failed to send response handshake"),true}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}sendHandshakeInBackground(e,t,n){let i=o=>{this.disposed||console.warn(n,{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:o});};try{Promise.resolve(this.deps.sendTransportHandshake(e,t)).catch(i);}catch(o){i(o);}}sendHandshakeWithRecoveryInBackground(e,t,n,i,o,s){let a=c=>{s?.(),!this.disposed&&console.warn(o,{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:c});};try{Promise.resolve(this.deps.sendTransportHandshakeWithRecovery(e,t,n,i)).catch(a);}catch(c){a(c);}}handleTransportTrustHandshakeInBackground(e,t,n,i,o){let s=a=>{this.disposed||console.warn("[Client][TRUST] Handshake processing failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:a});};try{Promise.resolve(this.handleTransportTrustHandshake(e,t,n,i,o)).catch(s);}catch(a){s(a);}}async handleTransportTrustHandshake(e,t,n,i,o){try{if(this.disposed)return;let s=n,a=t.transportTrust??null,c=this.deps.initializeConnectionTrust(e);if(a?.deviceId&&!c.expectedDeviceId&&this.deps.getKnownDevice(a.deviceId,e.remoteNodeId)&&(c.expectedDeviceId=a.deviceId),s==="hello"){let l=typeof a?.challenge=="string"?a.challenge:null;if(!l&&c.required)if(this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)){let p=this.deps.getSessionTokenApprovedScope(e.id);c.required=!1,c.verified=!0,c.failed=!1,c.failureReason=void 0,c.issuedChallenge=null,this.deps.applyConnectionTrustProjection(e);let u=typeof a?.deviceId=="string"&&a.deviceId.trim()?a.deviceId.trim():c.expectedDeviceId??this.deps.getKnownDeviceIdForNode(e.remoteNodeId)??null;u&&this.deps.sessionTokenScopeAllowsDeviceBinding(p)&&this.deps.bindConnectionDeviceIdInRust(e,u),c$1("[Client][TRUST] Skipping challenge enforcement for session-token-approved connection",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s});}else c.failureReason="missing-transport-trust-challenge",this.deps.applyConnectionTrustProjection(e),c$1("[Client][TRUST] Deferring missing hello challenge enforcement pending response/ack or session-token approval",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s});if(await this.deps.sendTransportHandshakeWithRecovery(e,"response",l,`trust-${s}-response`),this.disposed)return}else if(s==="response"||s==="ack"){let l=await this.deps.verifyRemoteTransportTrust(e,a);if(this.disposed)return;if(!l.verified){if(l.stale){c$1("[Client][TRUST] Ignoring stale transport proof and requesting current challenge",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s,reason:l.reason??"stale-transport-trust-response"}),await this.deps.sendTransportHandshakeWithRecovery(e,"hello",null,"stale-trust-response-rechallenge");return}if(this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)){this.deps.applySessionTokenTrustApproval(e,null,"handshake-proof-bypass-after-session-token");return}if(l.reason==="missing-transport-trust-payload"){c.failureReason=l.reason,this.deps.applyConnectionTrustProjection(e),c$1("[Client][TRUST] Deferring absent optional transport proof pending session-token admission",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:s});return}c.required&&await this.deps.enforceConnectionTrustFailure(e,l.reason??"remote-transport-proof-invalid");return}if(this.deps.markConnectionTrustVerified(e,l.deviceId),s==="response"&&o(`handshake:${s}:trust-verified`),s==="response"&&typeof a?.challenge=="string"&&(await this.deps.sendTransportHandshakeWithRecovery(e,"ack",a.challenge,"trust-response-ack"),this.disposed))return}else s==="capability-update"&&(this.deps.isSessionTokenApproved(e.id,e.remoteNodeId)||this.deps.getConnectionTrustState(e.id)?.verified)&&o("capability-update:trust-reused");}catch(s){console.warn("[Client][TRUST] Handshake processing failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:s});}}};var zt=class zt{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}async handleUnhandledIncomingStreamEvent(e){if(await this.closeIfDisposed(e,"incoming-acceptor-disposed"))return;let{type:t,stream:n,remoteNodeId:i,traceId:o}=e,s=e.protocolHint;if(t==="bi"&&s==="native-main"&&(s=this.deps.normalizeAuthoritativeIncomingProtocolHint("native-main",i,o)??"native-main",e={...e,protocolHint:s}),!e.invalid){if(t==="bi"&&e.channel?.channelId===wi){await this.receiveDefaultPeerStream(e);return}if(t==="uni"){if(!this.deps.shouldSkipIncomingStreamProbe()&&await this.deps.tryHandleNativeMainUniStream(n,i,o))return;await this.deps.cancelUnhandledIncomingUniStream(n,i);return}if(t==="bi"&&s==="native-main"){c$1("[Client][INCOMING] Handling native desktop main stream",{remoteNodeId:i,traceId:o||null}),this.handleNativeMainStreamInBackground(n,i,e.transportStableId,o,"[Client][NATIVE-MAIN] Background handler crashed");return}if(this.deps.shouldTreatIncomingStreamAsTransportOnly(e)){this.deps.logIncomingDiagnostic("bi:drop-unhandled-ticket-flow",{remoteNodeId:i||"unknown",traceId:o||null,protocolHint:s,channelId:e.channel?.channelId??null});return}t==="bi"&&s!=="explicit"&&await this.acceptIncomingBiStream(e);}}async receiveDefaultPeerStream(e){let t=e.stream,n=e.remoteNodeId,i=this.deps.getDeterministicConnectionId(n),o=this.deps.getConnection(i);if(!o||o.isClosed||!y(t)){await ge(t,"peer-default-without-live-connection",n);return}let s=t.recv.getReader(),a=t.send.getWriter(),c=new Uint8Array(0);try{for(;;){let{done:l,value:p}=await s.read();if(l)break;if(!p||p.byteLength===0)continue;let u=new Uint8Array(c.byteLength+p.byteLength);for(u.set(c),u.set(p,c.byteLength),c=u;c.byteLength>=4;){let g=new DataView(c.buffer,c.byteOffset,c.byteLength).getUint32(0,!1);if(g===0||g>zt.MAX_PEER_MESSAGE_FRAME_BYTES)throw new Error(`invalid peer-default frame length ${g}`);if(c.byteLength<4+g)break;o.receiveFrameBody(c.slice(4,4+g)),c=c.slice(4+g);}}if(c.byteLength!==0)throw new Error(`truncated peer-default frame (${c.byteLength} bytes)`)}catch(l){this.deps.logIncomingDiagnostic("peer-default:receive-failed",{connectionId:i,remoteNodeId:n,traceId:e.traceId??null,error:l});}finally{try{await a.close();}catch{}try{s.releaseLock();}catch{}try{a.releaseLock();}catch{}}}async acceptIncomingBiStream(e){if(await this.closeIfDisposed(e,"incoming-acceptor-disposed-before-accept"))return;let{stream:t,remoteNodeId:n,traceId:i}=e,o=e.protocolHint,s=this.deps.getDeterministicConnectionId(n),a=this.deps.getKnownDevice(null,n),c=typeof a?.platformType=="string"?String(a.platformType).toLowerCase():typeof a?.platform_type=="string"?String(a.platform_type).toLowerCase():null;if(!this.deps.usesTicketOnlySignalingMode()&&(c==="desktop"||c==="mobile")){c$1("[Client][INCOMING] Routing unhinted native peer stream through native-main handler",{connectionId:s,remoteNodeId:n,traceId:i||null,protocolHint:o,knownRemotePlatform:c}),this.handleNativeMainStreamInBackground(t,n,e.transportStableId,i,"[Client][NATIVE-MAIN] Unhinted native peer stream handler crashed");return}let l=this.deps.getConnection(s);if(l&&!l.isClosed){let v=l.getUpgradeState(),S=await this.deps.isCoreConnectionHealthy(n).catch(()=>false);if(await this.closeIfDisposed(e,"incoming-acceptor-disposed-after-core-health"))return;let I=typeof l.getControlFrameMode=="function"&&l.getControlFrameMode()==="native-main";if(S){if(!I){c$1("[Client][INCOMING] Closing auxiliary bi stream while typed connection is upgrading/upgraded",{connectionId:s,remoteNodeId:n,traceId:i||null,existingUpgradeState:v,protocolHint:o}),await ge(t,"typed-connection-auxiliary-stream",n);return}c$1("[Client][INCOMING] Routing auxiliary bi stream to native-main handler while connection is upgrading/upgraded",{connectionId:s,remoteNodeId:n,traceId:i||null,existingUpgradeState:v,protocolHint:o}),this.handleNativeMainStreamInBackground(t,n,e.transportStableId,i,"[Client][NATIVE-MAIN] Auxiliary stream handler crashed");return}if((v==="upgrading"||v==="upgraded")&&c$1("[Client][INCOMING] Replacing upgraded connection due to stale core transport",{connectionId:s,remoteNodeId:n,traceId:i||null,existingUpgradeState:v,coreTransportConnected:S}),c$1("[Client][INCOMING] Replacing existing connection main stream",{connectionId:s,remoteNodeId:n,traceId:i||null}),this.deps.cleanupReplacedConnection(s),await this.disconnectConnection(l),await this.closeIfDisposed(e,"incoming-acceptor-disposed-after-existing-disconnect"))return}let p=t;if(!y(p)){console.error("[Client][INCOMING] Unable to construct connection from invalid bi stream",{remoteNodeId:n});return}let u,g;try{u=p.send.getWriter(),g=p.recv.getReader();}catch(v){console.error("[Client][INCOMING] Failed to acquire incoming stream reader/writer",{remoteNodeId:n,error:v});return}let y$1;y$1=new de(s,this.deps.getLocalNodeId(),n,u,g,{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(n),applicationCrypto:this.deps.getOptions()?.applicationCrypto,requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),controlFrameMode:"typed",onTransportStatusChange:v=>this.deps.handleConnectionTransportStatus(y$1,v.activeTransport,v.parallelTransport),onApplicationRouteReady:v=>{this.deps.handleConnectionApplicationRouteReady(y$1,v);},onApplicationRouteMissing:v=>{this.deps.handleConnectionApplicationRouteMissing(s,v);}});let m=this.deps.getKnownDeviceIdForNode(n);if(this.deps.initializeConnectionTrust(y$1,m),this.disposed){await this.disconnectConnection(y$1);return}this.deps.registerConnection(y$1),m?this.deps.bindConnectionDeviceIdInRust(y$1,m):this.lookupAcceptedDeviceBindingInBackground(y$1,n),this.deps.announceConnectionWhenStable(y$1),c$1("[Client][HANDSHAKE] sending hello (incoming connection path)",{connectionId:y$1.id,remoteNodeId:y$1.remoteNodeId}),this.sendIncomingHelloInBackground(y$1);}handleNativeMainStreamInBackground(e,t,n,i,o){let s=a=>{this.disposed||console.error(o,{remoteNodeId:t,traceId:i||null,error:a});};try{let a=Number.isSafeInteger(n)&&Number(n)>0?this.deps.handleNativeMainStream(e,t,n):this.deps.handleNativeMainStream(e,t);Promise.resolve(a).catch(s);}catch(a){s(a);}}lookupAcceptedDeviceBindingInBackground(e,t){let n=i=>{this.disposed||console.warn("[Client][BIND] Accept-side searchDevices fallback failed",{connectionId:e.id,remoteNodeId:t,error:i});};try{Promise.resolve(this.deps.searchDevices()).then(()=>{if(this.disposed)return;let i=this.deps.getKnownDeviceIdForNode(t);i?this.deps.bindConnectionDeviceIdInRust(e,i):console.warn("[Client][BIND] Accept-side directory lookup found no deviceId for remote node",{connectionId:e.id,remoteNodeId:t});}).catch(n);}catch(i){n(i);}}sendIncomingHelloInBackground(e){let t=n=>{this.disposed||console.warn("[Client][TRUST] Failed to send incoming handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:n});};try{Promise.resolve(this.deps.sendTransportHandshake(e,"hello")).then(()=>{this.disposed||this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,"protected-hello:incoming");}).catch(t);}catch(n){t(n);}}async disconnectConnection(e){try{await Promise.resolve(e.disconnect());}catch{}}async closeIfDisposed(e,t){return this.disposed?(e.type==="bi"?await ge(e.stream,t,e.remoteNodeId):e.type==="uni"&&await this.deps.cancelUnhandledIncomingUniStream(e.stream,e.remoteNodeId),true):false}};zt.MAX_PEER_MESSAGE_FRAME_BYTES=4*1024*1024;var Kt=zt;function br(r){return r==="desktop"||r==="mobile"||r==="native"}function Sr(r,e,t=false){return true}function Ir(r){return !r}function Qt(r,e,t){return r}var Ni={ready:false,phase:"frame-start",expectedFrameLength:0,consumedBytes:0,payloadBytes:new Uint8Array};function Rr(r,e){let t=new TextEncoder().encode(JSON.stringify(r)),n=new TextEncoder().encode(e.label),i=new Uint8Array(5+n.byteLength+4+t.byteLength),o=new DataView(i.buffer),s=0;return i[s]=e.protocolByte,s+=1,o.setUint32(s,n.byteLength,false),s+=4,i.set(n,s),s+=n.byteLength,o.setUint32(s,t.byteLength,false),s+=4,i.set(t,s),i}async function Pr(r,e,t,n,i=8e3){if(typeof window>"u"||typeof window.dispatchEvent!="function")return null;let o=[],s=c=>{o.push(Promise.resolve(c));};if(window.dispatchEvent(new CustomEvent(r,{detail:{remoteNodeId:e,remoteDeviceId:t,message:n,respondWith:s}})),o.length===0)return null;let a;try{let c=await Promise.race([Promise.allSettled(o),new Promise(l=>{a=setTimeout(()=>l([]),i);})]);for(let l of c)if(l.status==="fulfilled"&&l.value!==void 0&&l.value!==null)return l.value}finally{a&&clearTimeout(a);}return null}function _r(r,e){if(r.byteLength===0)return Ni;if(r[0]===e.protocolByte){if(r.byteLength<5)return Ni;let i=new DataView(r.buffer,r.byteOffset,r.byteLength),o=i.getUint32(1,false);if(o>0&&o<=e.maxLabelBytes&&r.byteLength>=5+o&&new TextDecoder().decode(r.slice(5,5+o))===e.label){let a=5+o+4;if(r.byteLength<a)return {ready:false,phase:"frame-body",expectedFrameLength:0,consumedBytes:0,payloadBytes:new Uint8Array};let c=i.getUint32(5+o,false);if(c>e.maxFrameBytes)throw new Error(`native-main frame too large: ${c}`);return r.byteLength<a+c?{ready:false,phase:"frame-body",expectedFrameLength:c,consumedBytes:0,payloadBytes:new Uint8Array}:{ready:true,phase:"frame-body",expectedFrameLength:c,consumedBytes:a+c,payloadBytes:r.slice(a,a+c)}}}if(r.byteLength<4)return Ni;let n=new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,false);if(n>e.maxFrameBytes)throw new Error(`legacy native-main frame too large: ${n}`);return r.byteLength<4+n?{ready:false,phase:"frame-body",expectedFrameLength:n,consumedBytes:0,payloadBytes:new Uint8Array}:{ready:true,phase:"frame-body",expectedFrameLength:n,consumedBytes:4+n,payloadBytes:r.slice(4,4+n)}}function wr(r){let{host:e,transports:t,trustServices:n}=r;return new jt(e.getContext(),{ensureWasmRuntimeForP2P:()=>e.ensureWasmRuntimeForP2P(),getOptions:()=>e.getOptions(),getWasmClient:()=>e.getWasmClient(),getLocalNodeId:()=>e.getLocalNodeId(),getDeterministicConnectionId:i=>t.peerIdentity.getDeterministicConnectionId(i),getRegisteredChannel:i=>e.getRegisteredChannel(i),isTransportOnlyChannel:i=>n.channelPolicy.isTransportOnlyChannel(i),rememberRouteRepairTokenForNode:(i,o,s)=>e.rememberRouteRepairTokenForNode(i,o,s),resolveExpectedDeviceIdForSessionTokenScope:(i,o,s,a)=>n.trust.resolveExpectedDeviceIdForSessionTokenScope(i,o,s,a),initializeConnectionTrust:(i,o)=>n.trust.initialize(i,o),refreshApplicationRouteHandshake:(i,o,s)=>t.upgrade.refreshApplicationRouteHandshake(i,o,s),ensureWasmManagedTransport:(i,o,s)=>e.ensureWasmManagedTransport(i,o,s),isLocalIrohRuntimeNotInitializedError:i=>e.isLocalIrohRuntimeNotInitializedError(i),recoverLocalIrohRuntime:i=>e.recoverLocalIrohRuntime(i),getSessionTokenApprovedScope:i=>e.getSessionTokenApprovedScope(i),setSessionTokenApprovedScope:(i,o)=>e.setSessionTokenApprovedScope(i,o),getPeerState:i=>e.getPeerState(i),assignConnectionChannel:(i,o)=>n.channelPolicy.assign(i,o),bindConnectionDeviceIdInRust:(i,o)=>n.deviceBinder.bindConnectionDeviceIdInRust(i,o),approveSessionTokenNode:i=>e.approveSessionTokenNode(i),approveSessionTokenConnection:i=>e.approveSessionTokenConnection(i),applySessionTokenTrustApproval:(i,o,s)=>e.applySessionTokenTrustApproval(i,o,s),announceConnectionWhenStable:i=>r.getLifecycle().announceConnectionWhenStable(i),disconnectNodeTransport:i=>t.health.disconnectNodeTransport(i),shouldUseNativeMainFramingForPeer:(i,o,s)=>Sr(i,o,s),writeNativeMainLabelHeaderOnBiStream:(i,o)=>e.writeNativeMainLabelHeaderOnBiStream(i,o),getRTCConfig:()=>t.getRTCConfig(),createTransportContext:i=>t.contexts.create(i),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(i,o,s)=>t.health.handleCurrentConnectionTransportStatus(i,o,s),handleConnectionApplicationRouteReady:(i,o)=>t.health.handleCurrentConnectionApplicationRouteReady(i,o),handleConnectionApplicationRouteMissing:(i,o)=>t.upgrade.handleApplicationRouteMissing(i,o),sendNativeSignalEnvelope:(i,o,s,a)=>e.sendNativeSignalEnvelope(i,o,s,a),registerConnection:i=>r.getLifecycle().registerConnection(i),schedulePeerReconciliation:i=>e.schedulePeerReconciliation(i),consumePendingSessionTokenTrustApproval:i=>e.consumePendingSessionTokenTrustApproval(i),sendTransportHandshake:(i,o)=>t.handshake.sendTransportHandshake(i,o),requestProtectedWebRTCUpgradeIfInitiator:(i,o)=>t.handshake.requestProtectedWebRTCUpgradeIfInitiator(i,o),clearManualDisconnectProjection:i=>e.clearManualDisconnectProjection(i),getPeerScopes:i=>e.getPeerScopes(i),sessionTokenScopeAllowsDeviceBinding:i=>n.trust.sessionTokenScopeAllowsDeviceBinding(i),resolvePromotionEligibility:i=>n.channelPolicy.resolvePromotionEligibility(i),hasRustPeerLifecycleProjection:()=>e.hasRustPeerLifecycleProjection(),dispatchLiveConnectionProjection:(i,o)=>e.dispatchLiveConnectionProjection(i,o),hasApplicationRouteForConnection:i=>t.upgrade.hasApplicationRouteForConnection(i),isWebRtcApplicationRouteReadyForConnection:i=>t.upgrade.isWebRtcApplicationRouteReadyForConnection(i),addPeerScope:(i,o)=>e.addPeerScope(i,o)})}function Tr(r){let{host:e,transports:t,trustServices:n}=r;return new qt({registerDisposer:i=>e.registerDisposer(i),resolveApplicationCryptoForPeer:(i,o)=>e.resolveApplicationCryptoForPeer(i,o),handleApplicationKeyAgreement:(i,o)=>e.handleApplicationKeyAgreement(i,o),releaseApplicationKeyAgreementReply:(i,o,s)=>e.releaseApplicationKeyAgreementReply(i,o,s),isWebRTCTransportEnabled:()=>k(e.getOptions()),requiresManagedTransportTrust:()=>e.requiresManagedTransportTrust(e.getDiscoveryMode()),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),getLocalNodeId:()=>e.getLocalNodeId(),validateIncomingSessionTokenWithRetry:(i,o,s)=>e.validateIncomingSessionTokenWithRetry(i,o,s),applySessionTokenTrustApproval:(i,o,s)=>e.applySessionTokenTrustApproval(i,o,s),getConnectionChannelId:i=>n.channelPolicy.getConnectionChannelId(i),sendTransportHandshake:(i,o)=>t.handshake.sendTransportHandshake(i,o),getMoQState:()=>e.getMoQState(),enableMoQForConnection:i=>e.enableMoQForConnection(i),forgetMoQPeerSubscription:i=>e.forgetMoQPeerSubscription(i),assignConnectionChannel:(i,o)=>n.channelPolicy.assign(i,o),initializeConnectionTrust:i=>n.trust.initialize(i),getKnownDevice:(i,o)=>e.getKnownDevice(i,o),isSessionTokenApproved:(i,o)=>e.isSessionTokenApproved(i,o),getSessionTokenApprovedScope:i=>e.getSessionTokenApprovedScope(i),sessionTokenScopeAllowsDeviceBinding:i=>n.trust.sessionTokenScopeAllowsDeviceBinding(i),applyConnectionTrustProjection:i=>e.applyConnectionTrustProjection(i),getKnownDeviceIdForNode:i=>e.getKnownDeviceIdForNode(i),bindConnectionDeviceIdInRust:(i,o)=>n.deviceBinder.bindConnectionDeviceIdInRust(i,o),sendTransportHandshakeWithRecovery:(i,o,s,a)=>t.handshake.sendTransportHandshakeWithRecovery(i,o,s,a),verifyRemoteTransportTrust:(i,o)=>n.trust.verifyRemoteTransportTrust(i,o),enforceConnectionTrustFailure:(i,o)=>n.trust.enforceFailure(i,o),markConnectionTrustVerified:(i,o)=>n.trust.markVerified(i,o),getConnectionTrustState:i=>n.trust.getStateByConnectionId(i),dispatchMessage:(i,o)=>e.dispatchIncomingMessage(i,o)})}function Ar(r){let{host:e,registry:t,transports:n,trustServices:i}=r;return new Kt({registerDisposer:o=>e.registerDisposer(o),normalizeAuthoritativeIncomingProtocolHint:(o,s,a)=>Qt(o),shouldSkipIncomingStreamProbe:()=>e.shouldSkipIncomingStreamProbe(),tryHandleNativeMainUniStream:(o,s,a)=>e.tryHandleNativeMainUniStream(o,s,a),cancelUnhandledIncomingUniStream:(o,s)=>e.cancelUnhandledIncomingUniStream(o,s,(a,c)=>e.logIncomingDiagnostic(a,c)),handleNativeMainStream:(o,s,a)=>Number.isSafeInteger(a)&&Number(a)>0?e.handleNativeMainStream(o,s,a):e.handleNativeMainStream(o,s),shouldTreatIncomingStreamAsTransportOnly:o=>e.shouldTreatIncomingStreamAsTransportOnly(o),logIncomingDiagnostic:(o,s)=>e.logIncomingDiagnostic(o,s),getDeterministicConnectionId:o=>n.peerIdentity.getDeterministicConnectionId(o),getKnownDevice:(o,s)=>e.getKnownDevice(o,s),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),getConnection:o=>t.get(o),isCoreConnectionHealthy:o=>n.health.isCoreConnectionHealthy(o),cleanupReplacedConnection:o=>r.getLifecycle().cleanupReplacedConnection(o),getLocalNodeId:()=>e.getLocalNodeId(),getRTCConfig:()=>n.getRTCConfig(),createTransportContext:o=>n.contexts.create(o),getOptions:()=>e.getOptions(),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(o,s,a)=>n.health.handleCurrentConnectionTransportStatus(o,s,a),handleConnectionApplicationRouteReady:(o,s)=>n.health.handleCurrentConnectionApplicationRouteReady(o,s),handleConnectionApplicationRouteMissing:(o,s)=>n.upgrade.handleApplicationRouteMissing(o,s),getKnownDeviceIdForNode:o=>e.getKnownDeviceIdForNode(o),initializeConnectionTrust:(o,s)=>i.trust.initialize(o,s),registerConnection:o=>r.getLifecycle().registerConnection(o),bindConnectionDeviceIdInRust:(o,s)=>i.deviceBinder.bindConnectionDeviceIdInRust(o,s),searchDevices:()=>e.searchDevices(),announceConnectionWhenStable:o=>r.getLifecycle().announceConnectionWhenStable(o),sendTransportHandshake:(o,s)=>n.handshake.sendTransportHandshake(o,s),requestProtectedWebRTCUpgradeIfInitiator:(o,s)=>n.handshake.requestProtectedWebRTCUpgradeIfInitiator(o,s)})}function kr(r){let{host:e,registry:t,transports:n,trustServices:i}=r;return new Gt({registerDisposer:o=>e.registerDisposer(o),registry:t,resolveApplicationCryptoForPeer:(o,s)=>e.resolveApplicationCryptoForPeer(o,s),flushPendingNativeMainHandshakesForNode:(o,s)=>e.flushPendingNativeMainHandshakesForNode(o,s),flushPendingNativeMainSignalsForNode:(o,s)=>e.flushPendingNativeMainSignalsForNode(o,s),getConnectionTrustState:o=>i.trust.getStateByConnectionId(o),getKnownDeviceIdByNodeId:o=>e.getKnownDeviceIdForNode(o),bindConnectionDeviceIdInRust:(o,s)=>i.deviceBinder.bindConnectionDeviceIdInRust(o,s),searchDevices:()=>e.searchDevices(),retireSupersededConnections:(o,s,a)=>i.deviceBinder.retireSupersededConnections(o,s,a),hasRustPeerLifecycleProjection:()=>e.hasRustPeerLifecycleProjection(),applyConnectionTrustProjection:o=>e.applyConnectionTrustProjection(o),schedulePeerReconciliation:o=>e.schedulePeerReconciliation(o),maybeHandleWebRTCExplicitFileEnvelope:(o,s)=>e.maybeHandleWebRTCExplicitFileEnvelope(o,s),handleMessage:(o,s)=>r.getMessageHandler().handleMessage(o,s),getExistingPeerProjectionForDisconnect:o=>e.getPeerState(o.id)||e.getPeerProjectionList().find(s=>s.connectionIds.includes(o.id)||s.nodeId===o.deviceId),cleanupConnectionState:(o,s)=>{e.forgetMoQPeerSubscription(o),s!=="physical-route"&&(e.clearApplicationCryptoForConnection(o),i.trust.clearForConnection(o),i.channelPolicy.forget(o),e.clearSessionTokenConnectionApproval(o));},dispatchLiveConnectionProjection:(o,s)=>e.dispatchLiveConnectionProjection(o,s),resolvePromotionEligibility:o=>i.channelPolicy.resolvePromotionEligibility(o),enforceConnectionTrustFailure:(o,s)=>i.trust.enforceFailure(o,s),initializeConnectionTrust:o=>i.trust.initialize(o),getWasmClient:()=>e.getWasmClient(),isCoreConnectionHealthy:o=>n.health.isCoreConnectionHealthy(o),hasApplicationRouteForConnection:o=>n.upgrade.hasApplicationRouteForConnection(o),allowsTransportOnlyStability:o=>i.channelPolicy.allowsTransportOnlyStability(o),stableWindowMs:nr,stableTimeoutMs:ir,stablePollMs:or})}function Nr(r){return new Di({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getWasmClient:()=>r.wasmClient,getLocalNodeId:()=>r.localNodeId,getDiscoveryMode:()=>r.discoveryMode,registerDisposer:e=>r.lifecycleScope.register(e),getTransportServices:()=>r.transportServices,getTrustServices:()=>r.trustServices,ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),ensureWasmManagedTransport:(e,t,n)=>r.managedTransportDialer.ensureWasmManagedTransport(e,t,n),isLocalIrohRuntimeNotInitializedError:e=>r.managedTransportDialer.isLocalIrohRuntimeNotInitializedError(e),recoverLocalIrohRuntime:e=>r.runtimeBootstrap.recoverLocalIrohRuntime(e),requiresManagedTransportTrust:e=>r.runtimeStatus.requiresManagedTransportTrust(e??r.discoveryMode),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),getRegisteredChannel:e=>r.incomingStreamRouter.getRegisteredChannel(e),maybeHandleWebRTCExplicitFileEnvelope:(e,t)=>r.incomingStreamRouter.maybeHandleWebRTCExplicitFileEnvelope(e,t),dispatchIncomingMessage:(e,t)=>r.incomingStreamRouter.dispatchMessage(e,t),shouldSkipIncomingStreamProbe:()=>r.incomingDiagnostics.shouldSkipIncomingStreamProbe(),cancelUnhandledIncomingUniStream:(e,t,n)=>r.incomingDiagnostics.cancelUnhandledIncomingUniStream(e,t,n),logIncomingDiagnostic:(e,t)=>r.incomingDiagnostics.logIncomingDiagnostic(e,t),shouldTreatIncomingStreamAsTransportOnly:e=>r.applicationIncomingStreams.shouldTreatIncomingStreamAsTransportOnly(e),tryHandleNativeMainUniStream:(e,t,n)=>r.nativeMain.tryHandleNativeMainUniStream(e,t??"",n),handleNativeMainStream:(e,t,n)=>Number.isSafeInteger(n)&&Number(n)>0?r.nativeMain.handleNativeMainStream(e,t??"",n):r.nativeMain.handleNativeMainStream(e,t??""),flushPendingNativeMainHandshakesForNode:(e,t)=>r.nativeMain.flushPendingHandshakesForNode(e,t),flushPendingNativeMainSignalsForNode:(e,t)=>r.nativeMain.flushPendingSignalsForNode(e,t),writeNativeMainLabelHeaderOnBiStream:(e,t)=>r.nativeMain.writeLabelHeaderOnBiStream(e,t),sendNativeSignalEnvelope:(e,t,n,i)=>r.nativeMain.sendSignalEnvelope(e,t,n,i),resolveApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.resolveForPeer(e,t),clearApplicationCryptoForConnection:e=>r.applicationCrypto.clearConnection(e),handleApplicationKeyAgreement:(e,t)=>r.applicationCrypto.handleKeyAgreement(e,t),releaseApplicationKeyAgreementReply:(e,t,n)=>r.applicationCrypto.releaseReplyClaim(e,t,n),shouldNegotiateApplicationKeyAgreement:()=>r.applicationCrypto.shouldNegotiateKeyAgreement(),rememberRouteRepairTokenForNode:(e,t,n)=>r.sessionTokens.rememberRouteRepairTokenForNode(e,t,n),getSessionTokenApprovedScope:e=>r.sessionTokens.getApprovedScope(e),setSessionTokenApprovedScope:(e,t)=>r.sessionTokens.setApprovedScope(e,t),approveSessionTokenNode:e=>r.sessionTokens.approveNode(e),approveSessionTokenConnection:e=>r.sessionTokens.approveConnection(e),applySessionTokenTrustApproval:(e,t,n)=>r.sessionTokens.applyTrustApproval(e,t,n),consumePendingSessionTokenTrustApproval:e=>r.sessionTokens.consumePendingTrustApproval(e),validateIncomingSessionTokenWithRetry:(e,t,n)=>r.sessionTokens.validateIncomingSessionTokenWithRetry(e,t,n),isSessionTokenApproved:(e,t)=>r.sessionTokens.isApproved(e,t),clearSessionTokenConnectionApproval:e=>r.sessionTokens.clearConnectionApproval(e),getPeerState:e=>r.peerServices.getPeerState(e),getPeerScopes:e=>r.peerServices.getPeerScopes(e),addPeerScope:(e,t)=>r.peerServices.addPeerScope(e,t),clearManualDisconnectProjection:e=>r.peerServices.clearManualDisconnectProjection(e),getPeerProjectionList:()=>r.peerServices.listPeerStates(),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),dispatchLiveConnectionProjection:(e,t)=>r.peerProjection.dispatchLiveConnectionProjection(e,t),getKnownDevice:(e,t)=>r.deviceDirectory.getKnownDevice(e,t),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),searchDevices:()=>r.deviceDirectory.searchDevices(),getMoQState:()=>r.moqServices.state,enableMoQForConnection:e=>r.moqServices.enableForConnection(e),forgetMoQPeerSubscription:e=>r.moqServices.forgetPeerSubscription(e)})}var Di=class{constructor(e){this.host=e;this.registry=new Wt;}get transports(){return this.host.getTransportServices()}get trustServices(){return this.host.getTrustServices()}get factoryHost(){return {host:this.host,registry:this.registry,transports:this.transports,trustServices:this.trustServices,getLifecycle:()=>this.lifecycle,getMessageHandler:()=>this.messageHandler}}get dialer(){return this._dialer??(this._dialer=wr(this.factoryHost))}get messageHandler(){return this._messageHandler??(this._messageHandler=Tr(this.factoryHost))}get incomingAcceptor(){return this._incomingAcceptor??(this._incomingAcceptor=Ar(this.factoryHost))}get lifecycle(){return this._lifecycle??(this._lifecycle=kr(this.factoryHost))}async ensureManagedApplicationRoute(e){let t=Math.max(1,e.timeoutMs??2e4),n=await this.dialer.connect(e.ticket,t,e.expectedDeviceId,void 0,{admissionAlreadyPresented:true}),i=this.registry.getForPeer(e.connectionId??void 0,e.remoteNodeId??n.remoteNodeId)??n;if(await this.transports.upgrade.refreshApplicationRouteHandshake(i,"managed-transport-adoption",{forceReciprocal:true}),!await this.transports.upgrade.waitForApplicationRouteForConnection(i,t,50))throw new Error(`[Client][HANDSHAKE] application route was not ready for current connection ${i.id}`);return i}};var $t=class{constructor(){this.wasmClient=null;this.node=null;this.localNodeId="";this.deviceId=null;}};var Vt=class{constructor(e=(t,n)=>{console.warn(t,n);}){this.logError=e;this.disposers=[];this.destroyed=false;}get isDestroyed(){return this.destroyed}register(e){if(this.destroyed){try{e();}catch(t){this.logError("[Client] late disposer failed",t);}return}this.disposers.push(e);}destroy(){if(!this.destroyed){this.destroyed=true;for(let e of this.disposers.splice(0).reverse())try{e();}catch(t){this.logError("[Client] disposer failed during destroy",t);}}}};var Yt=class{constructor(e,t={}){this.session=e;this.namespaces=new Map;this.activePublishers=new Map;this.closed=false;this.maxNamespaces=t.maxPendingAnnounces??64,this.maxSubscribedTracks=t.maxSubscribedTracks??256,this.maxActivePublishers=t.maxActivePublishers??256,this.maxTrackIdChars=t.maxTrackIdChars??512;}async announce(e){let t=e.trim();if(!t)throw new Error("MoQ announce namespace must be non-empty");if(this.namespaces.has(t))throw new Error(`MoQ namespace is already announced: ${t}`);if(this.namespaces.size>=this.maxNamespaces)throw new Error(`MoQ namespace limit exceeded (${this.maxNamespaces})`);let n=new Jt.Broadcast,i={broadcast:n,subscribers:new Map};this.namespaces.set(t,i),this.session.requireConnection().publish(Jt.Path.from(t),n),d$2(`[MoQ] Draft 14 namespace published: ${t}`),this.acceptTrackRequests(t,i);}hasTrackSubscriber(e,t){return (this.namespaces.get(e.trim())?.subscribers.get(t)?.size??0)>0}async createTrack(e,t){let n=this.resolveTrackId(e,t);if(!n)throw new Error("MoQ track namespace and name must be non-empty and within length limits");let i=this.activePublishers.get(n);if(i)return i;if(this.activePublishers.size>=this.maxActivePublishers)throw new Error(`MoQ active publisher limit exceeded (${this.maxActivePublishers})`);let o=e.trim(),s={close:()=>this.activePublishers.delete(n),push:async a=>{if(this.closed)throw new Error("MoQ publisher closed");let c=this.namespaces.get(o)?.subscribers.get(t);if(!c?.size)throw new Error(`MoQ track lost all subscribers: ${n}`);let l=[],p=0,u=null;for(let g of c)try{g.writeFrame(a.slice()),p+=1;}catch(y){l.push(g),u=y;}for(let g of l)c.delete(g);if(p===0){let g=u instanceof Error?`: ${u.message}`:"";throw new Error(`MoQ track write failed for every subscriber: ${n}${g}`)}}};return this.activePublishers.set(n,s),s}close(){if(!this.closed){this.closed=true;for(let e of this.namespaces.values()){for(let t of e.subscribers.values())for(let n of t)n.close();e.broadcast.close();}this.namespaces.clear(),this.activePublishers.clear();}}async acceptTrackRequests(e,t){try{for(;!this.closed;){let n=await t.broadcast.requested();if(!n)return;if(!this.resolveTrackId(e,n.track.name)||this.totalSubscriberCount()>=this.maxSubscribedTracks){n.track.close(new Error("track subscription rejected"));continue}let o=t.subscribers.get(n.track.name);o||(o=new Set,t.subscribers.set(n.track.name,o)),o.add(n.track);let s=o;n.track.closed.finally(()=>{s.delete(n.track),s.size===0&&t.subscribers.delete(n.track.name);});}}catch(n){this.closed||console.warn("[MoQ] Draft 14 publisher loop failed",n);}}totalSubscriberCount(){let e=0;for(let t of this.namespaces.values())for(let n of t.subscribers.values())e+=n.size;return e}resolveTrackId(e,t){if(typeof e!="string"||typeof t!="string")return null;let n=e.trim();if(!n||!t.trim())return null;let i=`${n}/${t}`;return i.length<=this.maxTrackIdChars?i:null}};var Xt=class{constructor(e,t,n={}){this.session=e;this.onObject=t;this.subscriptions=new Map;this.closed=false;this.maxSubscriptions=n.maxPendingSubscriptions??128,this.maxSubscribeRetries=n.maxSubscribeRetries??120,this.subscribeRetryDelayMs=n.subscribeRetryDelayMs??250,this.maxObjectPayloadBytes=n.maxObjectPayloadBytes??4*1024*1024,this.onSubscriptionTerminated=n.onSubscriptionTerminated;}async subscribe(e,t){let n=e.trim();if(!n||!t.trim())throw new Error("MoQ subscribe namespace and name must be non-empty");let i=`${n}\0${t}`;if(this.subscriptions.has(i))return;if(this.subscriptions.size>=this.maxSubscriptions)throw new Error(`MoQ subscription limit exceeded (${this.maxSubscriptions})`);let o={broadcast:null,track:null,cancelled:false};this.subscriptions.set(i,o),d$2(`[MoQ] Draft 14 subscription opened: ${n}/${t}`),this.consume(i,n,t,o);}close(){if(!this.closed){this.closed=true;for(let e of this.subscriptions.values())e.cancelled=true,e.track?.close(),e.broadcast?.close();this.subscriptions.clear();}}async consume(e,t,n,i){let o=0,s=null;for(;!this.closed&&!i.cancelled;){let a=this.session.requireConnection().consume(Jt.Path.from(t)),c=a.subscribe(n,0);i.broadcast=a,i.track=c;try{for(;!this.closed&&!i.cancelled;){let l=await c.readFrameSequence();if(!l)throw new Error("MoQ Draft 14 subscription closed");if(o=0,l.data.byteLength>this.maxObjectPayloadBytes)throw new Error(`MoQ object payload length exceeds limit: ${l.data.byteLength}`);this.onObject(t,n,l.data,{groupId:l.group,objectId:l.frame});}}catch(l){o+=1;let p=l instanceof Error&&/payload length exceeds limit/i.test(l.message);if(this.closed||i.cancelled||p||o>this.maxSubscribeRetries){!this.closed&&!i.cancelled&&(console.warn("[MoQ] Draft 14 subscription failed",l),s=l);break}d$2(`[MoQ] Draft 14 subscription retry ${o}/${this.maxSubscribeRetries}: ${t}/${n}`);}finally{c.close(),a.close(),i.track===c&&(i.track=null),i.broadcast===a&&(i.broadcast=null);}!this.closed&&!i.cancelled&&await new Promise(l=>setTimeout(l,this.subscribeRetryDelayMs));}if(this.subscriptions.get(e)===i&&this.subscriptions.delete(e),s!==null&&!this.closed&&!i.cancelled)try{this.onSubscriptionTerminated?.(t,n,s);}catch(a){console.warn("[MoQ] Subscription termination observer failed",a);}}};var Zt=class{constructor(e,t=()=>{},n=3,i=new URL("https://localhost/"),o={}){this.transport=e;this.relayUrl=i;this.setupComplete=false;this.connection=null;this.closeListeners=[];this.closed=false;this.closeEmitted=false;this.setupResolve=null;if(n!==3)throw new Error("MoQ Draft 14 adapter requires the bidirectional publisher/subscriber role");this.setupPromise=new Promise(s=>{this.setupResolve=s;}),this.publisher=new Yt(this),this.subscriber=new Xt(this,t,{onSubscriptionTerminated:o.onSubscriptionTerminated});}requireConnection(){if(this.closed||!this.connection||!this.setupComplete)throw new Error("MoQ Draft 14 session is not ready");return this.connection}async init(){if(this.closed)throw new Error("MoQ session closed");if(this.connection)return;await this.transport.ready;let e=await Jt.Connection.connect(this.relayUrl,{transport:this.transport,websocket:{enabled:false}});if(e.version!=="moq-transport-14")throw e.close(),new Error(`MoQ relay negotiated unsupported protocol ${e.version}`);if(this.closed){e.close();return}this.connection=e,this.setupComplete=true,this.setupResolve?.(),this.setupResolve=null,e.closed.then(()=>this.emitClose("relay-session-closed"),t=>this.emitClose(t));}waitForSetup(){return this.setupPromise}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(t=>t!==e);}}close(){if(!this.closed){this.closed=true,this.publisher.close(),this.subscriber.close();try{this.connection?.close();}catch{}this.connection=null;try{this.transport.close();}catch{}this.emitClose("local-close");}}emitClose(e){if(!this.closeEmitted){this.closeEmitted=true,this.closed=true,this.setupComplete=false,this.publisher.close(),this.subscriber.close(),this.connection=null;for(let t of [...this.closeListeners])try{t(e);}catch{}}}};var Er="#openrtc-moq-route-proof",xr=1,wa=512,Ta=750,Aa=8;function Lr(r){if(r.byteLength===0||r.byteLength>wa)return null;try{let e=JSON.parse(new TextDecoder().decode(r));return e.type!==Er||e.version!==xr||e.role!=="probe"&&e.role!=="ack"||typeof e.probeId!="string"||!/^[A-Za-z0-9_-]{8,64}$/.test(e.probeId)||typeof e.senderId!="string"||e.senderId.length===0||e.senderId.length>128||typeof e.recipientId!="string"||e.recipientId.length===0||e.recipientId.length>128?null:e}catch{return null}}function ka(r){return new TextEncoder().encode(JSON.stringify(r))}function Na(){if(typeof globalThis.crypto?.randomUUID=="function")return globalThis.crypto.randomUUID().replace(/-/g,"");let r=new Uint8Array(16);return globalThis.crypto?.getRandomValues?.(r),r.some(e=>e!==0)?Array.from(r,e=>e.toString(16).padStart(2,"0")).join(""):`${Date.now().toString(36)}${Math.random().toString(36).slice(2,18)}`}var en=class{constructor(e){this.deps=e;this.states=new Map;}request(e){let t=this.deps.getCurrentSession(),n=this.deps.getLocalNodeId();if(!t||!this.deps.isCurrentSession(t)||!n||e.isClosed||!e.peerMoQReady)return;let i=this.states.get(e.id);(!i||i.session!==t||i.peerId!==e.remoteNodeId||i.connection!==e)&&(this.clear(e.id),i=this.createState(e,t,e.remoteNodeId)),!i.proven&&!i.inFlight&&!i.retryTimer&&this.schedule(e,i,0);}requestForPeer(e){let t=this.deps.getConnectionById(this.deps.getDeterministicConnectionId(e));t&&this.request(t);}isProven(e){let t=this.deps.getDeterministicConnectionId(e),n=this.states.get(t),i=this.deps.getConnectionById(t);return !!n&&n.proven&&n.peerId===e&&n.connection===i&&this.deps.isCurrentSession(n.session)}handle(e,t,n,i){let o=this.deps.getLocalNodeId();if(!(!o||i.senderId!==t||i.recipientId!==o)){if(i.role==="ack"){let s=this.states.get(n.id);s&&s.session===e&&s.connection===n&&s.peerId===t&&s.probeId===i.probeId&&this.markProven(n,s,"matching-protected-ack");return}this.ensureState(n,e,t),this.send(n,e,{...i,role:"ack",senderId:o,recipientId:t}).catch(s=>{c$1("[Client] MoQ protected route ACK failed",{connectionId:n.id,error:s});});}}clearForPeer(e){this.clear(this.deps.getDeterministicConnectionId(e));}clear(e){let t=this.states.get(e);t?.retryTimer&&clearTimeout(t.retryTimer),this.states.delete(e);}clearAll(){for(let e of [...this.states.keys()])this.clear(e);}createState(e,t,n){let i={session:t,connection:e,peerId:n,probeId:Na(),attempts:0,inFlight:false,proven:false,retryTimer:null};return this.states.set(e.id,i),i}ensureState(e,t,n){let i=this.states.get(e.id);return i&&i.session===t&&i.connection===e&&i.peerId===n?i:(this.clear(e.id),this.createState(e,t,n))}schedule(e,t,n){t.retryTimer||t.proven||t.attempts>=Aa||(t.retryTimer=setTimeout(()=>{t.retryTimer=null,this.sendProbe(e,t);},n));}async sendProbe(e,t){if(t.inFlight||t.proven||e.isClosed||!e.peerMoQReady||this.states.get(e.id)!==t||!this.deps.isCurrentSession(t.session))return;let n=this.deps.getLocalNodeId();if(n){t.inFlight=true,t.attempts+=1;try{await this.send(e,t.session,{type:Er,version:xr,role:"probe",probeId:t.probeId,senderId:n,recipientId:e.remoteNodeId});}catch(i){c$1("[Client] MoQ protected route probe failed",{connectionId:e.id,attempt:t.attempts,error:i});}finally{t.inFlight=false;}!t.proven&&this.states.get(e.id)===t&&this.deps.isCurrentSession(t.session)&&this.schedule(e,t,Ta);}}async send(e,t,n){if(!this.deps.isCurrentSession(t))throw new Error("MoQ route proof session was replaced");let i=this.deps.protectDirectPayload(ka(n),e.remoteNodeId,e);if(!l$1(i))throw new Error("MoQ route proof requires application crypto");if(await this.deps.sendProtectedData(e.remoteNodeId,i),!this.deps.isCurrentSession(t))throw new Error("MoQ route proof session changed during send")}markProven(e,t,n){if(t.proven||t.connection!==e||this.deps.getConnectionById(e.id)!==e||this.states.get(e.id)!==t)return;let i=e.getTransportStatus();t.proven=true,t.retryTimer&&(clearTimeout(t.retryTimer),t.retryTimer=null),c$1("[Client] MoQ application route proven",{connectionId:e.id,reason:n}),this.deps.publishTransportStatus(e,"moq",i.activeTransport==="moq"?i.parallelTransport??null:i.activeTransport);}};var Da=5e3,Ma=125,Ea=8,tn=class{constructor(e,t){this.ctx=e;this.deps=t;this.session=null;this.state="none";this.readyListeners=[];this.failedListeners=[];this.objectListeners=[];this.reconnectTimer=null;this.reconnectAttempts=0;this.peerSubscriptions=new Set;this.disposed=false;this.routeProofController=new en({getLocalNodeId:()=>this.ctx.localNodeId,getCurrentSession:()=>this.session,isCurrentSession:n=>this.isCurrentSession(n),getDeterministicConnectionId:n=>this.deps.getDeterministicConnectionId(n),getConnectionById:n=>this.deps.getConnectionById(n),protectDirectPayload:(n,i,o)=>this.deps.protectDirectPayload(n,i,o),sendProtectedData:(n,i)=>this.sendDataInternal(n,i,{alreadyProtected:true,allowUnprovenRoute:true}),publishTransportStatus:(n,i,o)=>this.deps.handleCurrentConnectionTransportStatus(n,i,o)}),this.ctx.registerDisposer(()=>this.dispose());}get bundle(){return this.state!=="ready"||!this.session?null:{session:this.session,publisher:this.session.publisher,subscriber:this.session.subscriber}}onReady(e){return this.disposed?()=>{}:(this.readyListeners.push(e),()=>{this.readyListeners=this.readyListeners.filter(t=>t!==e);})}onFailed(e){return this.disposed?()=>{}:(this.failedListeners.push(e),()=>{this.failedListeners=this.failedListeners.filter(t=>t!==e);})}onObject(e){return this.disposed?()=>{}:(this.objectListeners.push(e),()=>{this.objectListeners=this.objectListeners.filter(t=>t!==e);})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}closeSession(e){let t=this.session;if(this.session=null,this.peerSubscriptions.clear(),this.routeProofController.clearAll(),!!t)try{t.close();}catch(n){c$1("[Client] MoQ session close failed",{reason:e,error:n});}}dispose(){this.disposed=true,this.clearReconnectTimer(),this.closeSession("client-dispose"),this.state="none",this.readyListeners=[],this.failedListeners=[],this.objectListeners=[];}handleSessionClosed(e,t){this.disposed||this.session===e&&(this.session=null,this.state="failed",this.peerSubscriptions.clear(),this.routeProofController.clearAll(),this.emitFailed(),c$1("[Client] MoQ session closed; scheduling reconnect",{reason:t}),this.scheduleReconnect(t));}scheduleReconnect(e){if(this.disposed||!this.deps.getMoQConfig()||this.reconnectTimer)return;let t=Math.min(this.deps.initialReconnectDelayMs*Math.max(1,2**this.reconnectAttempts),this.deps.maxReconnectDelayMs);this.reconnectAttempts+=1;let n=(this.reconnectAttempts*17%21-10)/100,i=Math.max(this.deps.initialReconnectDelayMs,Math.trunc(t+t*n));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!(this.disposed||!this.deps.getMoQConfig()||this.state==="ready"||this.state==="connecting")&&(d$2(`[Client] Reconnecting MoQ relay after ${i}ms`,e),this.init());},i);}enableForConnection(e){this.state!=="ready"||!this.bundle||(e.peerMoQReady=true,this.subscribePeer(e));}subscribePeer(e){this.subscribePeerNode(e.remoteNodeId,e.id,()=>e.isClosed),this.routeProofController.request(e);}forgetPeerSubscription(e){this.peerSubscriptions.delete(e),this.routeProofController.clear(e);}isApplicationRouteProven(e){return this.routeProofController.isProven(e)}requestApplicationRouteProofForPeer(e){this.routeProofController.requestForPeer(e);}clearApplicationRouteProofForPeer(e){this.routeProofController.clearForPeer(e);}subscribePeerNode(e,t=e,n){if(this.disposed)return;let i=this.bundle,o=e?.trim(),s=t?.trim()||o;!i||!this.ctx.localNodeId||!o||!s||n?.()||this.peerSubscriptions.has(s)||(this.peerSubscriptions.add(s),this.subscribePeerNodeInBackground(i,o,s));}resubscribePeers(){this.peerSubscriptions.clear(),this.ctx.registry.forEach(e=>{!e.isClosed&&e.peerMoQReady&&this.subscribePeer(e);});}async init(){if(this.disposed||!this.deps.getMoQConfig()||this.state==="ready"||this.state==="connecting")return;this.clearReconnectTimer(),this.closeSession("init"),this.state="connecting";let e=this.deps.getMoQConfig(),t=e&&typeof e=="object"?{...this.deps.getDefaultMoQConfig(),...e}:{...this.deps.getDefaultMoQConfig()},n$1=t.relayUrl?.trim();if(!n$1){this.state="failed",this.emitFailed(),console.warn("[Client] MoQ is enabled without a relay URL; configure transports.moq.relayUrl explicitly.");return}let i=t.serverCertificateHashes?.length?{serverCertificateHashes:t.serverCertificateHashes}:void 0,o;try{o=m(n$1,t.accessToken);}catch(c){this.state="failed",this.emitFailed(),console.warn("[Client] MoQ configuration rejected:",o$1(c,t.accessToken));return}let s=n(n$1),a=null;try{let c=new WebTransport(o,i);if(await c.ready,this.disposed){try{c.close?.();}catch{}return}let l;if(l=new Zt(c,(p,u,g,y)=>{this.handleObject(l,p,u,g,y);},3,new URL(n$1),{onSubscriptionTerminated:(p,u,g)=>this.handleSubscriptionTerminated(l,p,u,g)}),a=l,this.session=a,a.onClose(p=>this.handleSessionClosed(a,p)),await a.init(),this.disposed){a.close();return}if(await a.waitForSetup(),this.disposed||this.session!==a){a.close();return}if(await a.publisher.announce(this.ctx.localNodeId),this.disposed||this.session!==a){a.close();return}if(await this.createDataTracks(),this.disposed||this.session!==a){a.close();return}this.state="ready",this.reconnectAttempts=0,this.peerSubscriptions.clear(),d$2(`[Client] MoQ Session Ready: Pub/Sub via ${s}`),this.emitReady(),this.resubscribePeers(),this.broadcastReadyCapabilityInBackground();}catch(c){if(this.disposed){a&&this.session===a&&(this.session=null),a?.close();return}console.warn("[Client] MoQ init failed:",o$1(c,t.accessToken)),this.session===a&&(this.session=null),a?.close(),this.state="failed",this.emitFailed(),this.scheduleReconnect(c);}}async createDataTracks(){if(!this.disposed&&!(!this.session||!this.ctx.localNodeId))try{await this.session.publisher.createTrack(this.ctx.localNodeId,"data/broadcast"),d$2("[Client] MoQ Data Track created: data / broadcast");}catch(e){console.warn("Failed to create MoQ broadcast track",e);}}isDataReady(e){let t=this.bundle;if(!t||!this.ctx.localNodeId)return false;let n=e?`data / ${e} `:"data / broadcast";return t.publisher.hasTrackSubscriber(this.ctx.localNodeId,n)}async sendData(e,t,n={}){return this.sendDataInternal(e,t,n)}async sendDataInternal(e,t,n={}){if(this.disposed)throw new Error("MoQ not ready");let i=this.bundle;if(!i)throw new Error("MoQ not ready");if(e&&n.allowUnprovenRoute!==true&&!this.isApplicationRouteProven(e))throw this.requestApplicationRouteProofForPeer(e),new Error(`MoQ application route is not proven for peer: ${e}`);let o=e?`data / ${e} `:"data / broadcast";if(!await this.waitForStableDataReady(e,i.session))throw this.isCurrentSession(i.session)?new Error(`MoQ data track is not subscribed: ${o}`):new Error("MoQ not ready");if(!this.isCurrentSession(i.session))throw new Error("MoQ not ready");let s=await i.publisher.createTrack(this.ctx.localNodeId,o);if(!s)return;if(!this.isCurrentSession(i.session))throw new Error("MoQ not ready");let a=Date.now(),c=n.alreadyProtected?t:this.deps.protectDirectPayload(t,e??void 0),l=e?this.deps.getConnectionById(this.deps.getDeterministicConnectionId(e)):void 0;try{await s.push(c,{isKey:!0,timestamp:a,closeAfterPush:!0});}catch(p){if(e&&this.isCurrentSession(i.session)&&(this.routeProofController.clearForPeer(e),l&&!l.isClosed)){let u=l.getTransportStatus();this.deps.handleCurrentConnectionTransportStatus(l,u.activeTransport,u.parallelTransport??null);}throw p}if(this.isCurrentSession(i.session)&&l&&!l.isClosed&&this.isApplicationRouteProven(e)){let p=typeof l.getTransportStatus=="function"?l.getTransportStatus():null;this.deps.handleCurrentConnectionTransportStatus(l,"moq",p?.parallelTransport??null);}}async waitForStableDataReady(e,t){let n=Date.now(),i=0;for(;this.isCurrentSession(t);){if(this.isDataReady(e)){if(i+=1,i>=Ea)return true}else i=0;if(Date.now()-n>=Da)return false;await u(Ma);}return false}isCurrentSession(e){return !this.disposed&&this.state==="ready"&&this.session===e}handleSubscriptionTerminated(e,t,n,i){this.isCurrentSession(e)&&(c$1("[Client] MoQ subscription exhausted; replacing relay session",{namespace:t,name:n,error:i}),e.close(),this.session===e&&this.handleSessionClosed(e,i));}extractTrackPeerId(e){let t=e.replace(/\s+/g,"");if(!t.startsWith("data/"))return;let n=t.slice(5);if(!(!n||n==="broadcast"))return n}handleObject(e,t,n,i,o){if(!this.isCurrentSession(e))return;let s=this.deps.getConnectionById(this.deps.getDeterministicConnectionId(t)),a=this.deps.openDirectPayload(i,t);if(!a.encrypted||!a.payload)return;let c=a.proofEligible?Lr(a.payload):null;if(c){s&&!s.isClosed&&this.routeProofController.handle(e,t,s,c);return}s&&!s.isClosed&&typeof s.receiveDataPayload=="function"&&s.receiveDataPayload(a.payload),this.emitObject(t,n,a.payload,o);}emitReady(){for(let e of [...this.readyListeners])try{e();}catch(t){console.warn("[Client] MoQ ready listener failed",t);}}subscribePeerNodeInBackground(e,t,n){let i=()=>{this.peerSubscriptions.delete(n);};try{Promise.allSettled([e.subscriber.subscribe(t,"data/broadcast"),e.subscriber.subscribe(t,`data / ${this.ctx.localNodeId} `)]).then(o=>{this.disposed||o.some(s=>s.status==="rejected")&&i();});}catch{i();}}broadcastReadyCapabilityInBackground(){try{Promise.resolve(this.deps.broadcastTransportCapabilityUpdate("moq-ready")).catch(e=>{this.disposed||c$1("[Client] Late MoQ capability update failed",e);});}catch(e){if(this.disposed)return;c$1("[Client] Late MoQ capability update failed",e);}}emitFailed(){for(let e of [...this.failedListeners])try{e();}catch(t){console.warn("[Client] MoQ failed listener failed",t);}}emitObject(e,t,n,i){for(let o of [...this.objectListeners])try{o(e,t,n,i);}catch(s){console.warn("[Client] MoQ object listener failed",s);}}};function Fr(r){return new Mi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getDeterministicConnectionId:e=>r.peerIdentity.getDeterministicConnectionId(e),getConnectionById:e=>r.registry.get(e),protectDirectPayload:(e,t,n)=>r.applicationCrypto.protectDirectMoQPayload(e,t,n),openDirectPayload:(e,t,n)=>r.applicationCrypto.openDirectMoQPayload(e,t,n),handleCurrentConnectionTransportStatus:(e,t,n)=>r.transportHealth.handleCurrentConnectionTransportStatus(e,t,n),broadcastTransportCapabilityUpdate:e=>r.transportHandshake.broadcastTransportCapabilityUpdate(e)})}var Mi=class{constructor(e){this.host=e;}get controller(){return this._controller||(this._controller=new tn(this.host.getContext(),{getMoQConfig:()=>this.host.getOptions()?.transports?.moq,getDefaultMoQConfig:()=>({...j}),getDeterministicConnectionId:e=>this.host.getDeterministicConnectionId(e),getConnectionById:e=>this.host.getConnectionById(e),protectDirectPayload:(e,t,n)=>this.host.protectDirectPayload(e,t,n),openDirectPayload:(e,t,n)=>this.host.openDirectPayload(e,t,n),handleCurrentConnectionTransportStatus:(e,t,n)=>this.host.handleCurrentConnectionTransportStatus(e,t,n),broadcastTransportCapabilityUpdate:e=>this.host.broadcastTransportCapabilityUpdate(e),initialReconnectDelayMs:rr,maxReconnectDelayMs:sr})),this._controller}get state(){return this._controller?.state??"none"}get bundle(){return this._controller?.bundle??null}init(){return this.controller.init()}onReady(e){return this.controller.onReady(e)}onFailed(e){return this.controller.onFailed(e)}onObject(e){return this.controller.onObject(e)}isReady(){return this._controller?.state==="ready"}isDataReady(e){return this._controller?.isDataReady(e)??false}isApplicationRouteProven(e){return this._controller?.isApplicationRouteProven(e)??false}requestApplicationRouteProof(e){this._controller?.requestApplicationRouteProofForPeer(e);}clearApplicationRouteProof(e){this._controller?.clearApplicationRouteProofForPeer(e);}enableForConnection(e){this.controller.enableForConnection(e);}subscribePeerNode(e,t){this.controller.subscribePeerNode(e,t);}forgetPeerSubscription(e){this._controller?.forgetPeerSubscription(e);}sendData(e,t,n){return this.controller.sendData(e,t,n)}};function he(){if(typeof navigator>"u")return false;let r=navigator.userAgent||"",e=navigator.userAgentData?.platform||navigator.platform||"";return /iPhone|iPad|iPod|Android|Mobile|CriOS|FxiOS/i.test(`${r} ${e}`)}function nn(){return typeof window>"u"?false:new URLSearchParams(window.location.search).has("ticket")}function on(r){return r?r.routing==="stream-envelope"&&r.readiness==="transport-only":false}function nt(r){let e=r.signalingMode??"hosted",t=he(),n=nn(),i=e==="ticket-only",o=i&&t;return {flow:i?"ticket-only":"default",signalingMode:e,mobileBrowser:t,ticketQueryPresent:n,diagnosticsMode:o,skipIncomingBiProbe:o,skipIncomingChannelEnvelopeInspection:o,readerCloseStrategy:o?"release-lock":"cancel"}}var sn=class sn{constructor(e){this.deps=e;this.pendingReciprocalAdmissions=new Map;this.reciprocalConfirmationsInFlight=new Set;this.legacyReciprocalPresentationsInFlight=new Set;this.disposed=false;}dispose(){this.disposed=true,this.retirePendingReciprocalAdmissions("dispose"),this.legacyReciprocalPresentationsInFlight.clear();}retirePendingReciprocalAdmissions(e){this.pendingReciprocalAdmissions.size>0&&c$1("[Client][AUTH] retiring pending reciprocal admissions",{reason:e,count:this.pendingReciprocalAdmissions.size}),this.pendingReciprocalAdmissions.clear(),this.reciprocalConfirmationsInFlight.clear();}async acceptNativeMessage(e,t,n){if(this.disposed||!t)return false;let i=this.deps.getDeterministicConnectionId(t),o=this.deps.getConnection(i);if(o){try{Promise.resolve(this.deps.handleMessage(o,n)).catch(s=>{this.disposed||console.warn("[Client][NATIVE-MAIN] Existing connection message handling failed",{remoteNodeId:t,connectionId:o.id,error:s});});}catch(s){this.disposed||console.warn("[Client][NATIVE-MAIN] Existing connection message handling failed",{remoteNodeId:t,connectionId:o.id,error:s});}return false}if(n&&typeof n=="object"&&n.type==="handshake"&&(n.action==="hello"||!n.action)){let s=await this.deps.validateIncomingSessionToken(n.sessionToken??"",e??void 0,{remoteNodeId:t,source:"accept-native-message",tokenPayload:typeof n.sessionTokenPayload=="string"?n.sessionTokenPayload:void 0});if(this.disposed)return false;if(!s.ok)return console.warn("[Client][SESSION-TOKEN] Rejecting native connection \u2014 invalid session token",{remoteNodeId:t,reason:s.reason,hasToken:!!n.sessionToken}),true}return false}async resolveLocalHandshakePayload(){let e=await this.deps.getLocalDeviceId().catch(()=>null)||this.deps.getFallbackLocalDeviceId();if(!e)throw new Error("Local device id unavailable for native handshake response");let t=this.deps.isNativeRuntime(),n=t?this.deps.isLikelyMobileBrowser()?"mobile":"desktop":"web",i=t?{canHost:true,canSync:true,readOnly:false}:{canHost:false,canSync:true,readOnly:false},o=n==="mobile"?"Mobile Device":n==="desktop"?"Desktop Device":"Browser Device";return {deviceId:e,deviceName:this.deps.getConfiguredDeviceName()||o,platformType:n,capabilities:i,protocolVersion:this.deps.getNativeMainProtocolVersion(),timestamp:Date.now()}}async handleHandshakeRequest(e,t,n){if(this.disposed)return;let i=await this.resolveLocalHandshakePayload();this.disposed||(await this.deps.writeNativeMainMessage(e,{channel:"handshake",action:"response",requestId:n.requestId,payload:{accepted:true,...i},timestamp:Date.now()}),!this.disposed&&(this.schedulePeerReconciliationBestEffort("native-main-handshake"),c$1("[Client][NATIVE-MAIN] Responded to desktop handshake",{remoteNodeId:t,requestId:n.requestId??null,localDeviceId:i.deviceId})));}async handleSessionTokenRequest(e,t,n,i,o){if(this.disposed)return;let s=this.deps.getSessionTokenRejectionCooldown(t),a=this.deps.getNativeMainConnectionId(t);if(s!==void 0&&Date.now()-s<sn.TOKEN_REJECTION_COOLDOWN_MS){await this.deps.writeNativeMainMessage(e,{channel:"session-token",action:"response",requestId:n.requestId,payload:{approved:false,reason:"session-token-rejection-cooldown",connectionId:a},timestamp:Date.now()}),console.warn("[Client][AUTH] session-token presentation during rejection cooldown \u2014 wrote rejection for dialer",{remoteNodeId:t,connectionId:a});return}let c=n.payload&&typeof n.payload.token=="string"?n.payload.token.trim():"",l=n.payload&&typeof n.payload.tokenPayload=="string"?n.payload.tokenPayload.trim():void 0,p=await this.deps.validateIncomingSessionToken(c,a,{remoteNodeId:t,source:"native-main-session-token",tokenPayload:l||void 0});if(this.disposed)return;let u,g=n.payload?.reciprocalRequested===true,y=g&&n.payload?.reciprocalMode==="inline-v1"&&Number.isSafeInteger(i)&&Number(i)>0&&typeof o=="string"&&o.trim().length>0;if(p.ok&&y){let m=n.payload?.streamContract==="persistent-control"?"persistent-control":"one-shot-admission";try{let v=this.createPresentationId();u={...await this.deps.getReciprocalSessionAdmission(t,m,Number(i),o,v),presentationId:v};}catch(v){this.disposed||console.warn("[Client][AUTH] reciprocal session admission unavailable",{remoteNodeId:t,connectionId:a,error:v});}}if(!this.disposed&&(await this.deps.writeNativeMainMessage(e,p.ok?{channel:"session-token",action:"response",requestId:n.requestId,payload:{approved:true,scope:p.scope??null,connectionId:a,...u?{reciprocalPresentation:u}:{},...u?{reciprocalMode:"inline-v1"}:{}},timestamp:Date.now()}:{channel:"session-token",action:"response",requestId:n.requestId,payload:{approved:false,reason:p.reason??"session-token-rejected",connectionId:a},timestamp:Date.now()}),!this.disposed)){if(p.ok&&u&&i){for(let[m,v]of this.pendingReciprocalAdmissions)v.remoteNodeId===t&&v.transportStableId===i&&this.pendingReciprocalAdmissions.delete(m);this.pendingReciprocalAdmissions.set(u.presentationId,{connectionId:a,remoteNodeId:t,transportStableId:i,streamInstanceId:o,presentationId:u.presentationId});}if(p.ok){let m=this.deps.getConnection(a);m&&!m.isClosed?this.deps.applySessionTokenTrustApproval(m,p.scope??null,"native-main-session-token"):(this.deps.rememberPendingSessionTokenTrustApproval(a,p.scope??null),this.deps.markSessionTokenApprovedNode(t),this.deps.markSessionTokenApprovedConnection(a)),this.deps.clearSessionTokenRejectionCooldown(t),this.deps.clearTrustFailureCooldown(t),c$1("[Client][AUTH] host approved managed session token",{remoteNodeId:t,connectionId:a,scope:p.scope??null}),this.schedulePeerReconciliationBestEffort("session-token-approval"),g&&(!y||!u)&&this.scheduleLegacyReciprocalSessionAdmission(t,a),(!m||m.isClosed)&&this.kickstartApprovedControlConnection(t,a);return}console.warn("[Client][AUTH] host rejected managed session token",{remoteNodeId:t,connectionId:a,reason:p.reason??"session-token-rejected",hasToken:c.length>0}),this.deps.setSessionTokenRejectionCooldown(t,Date.now()),this.deps.disconnectRemoteNode(t);}}async handleSessionTokenResponseAck(e,t,n,i){let o=typeof t.payload?.reciprocalPresentationId=="string"?t.payload.reciprocalPresentationId.trim():"";if(!o||!Number.isSafeInteger(n)||Number(n)<=0)return false;let s=this.pendingReciprocalAdmissions.get(o);if(!s||s.remoteNodeId!==e||s.transportStableId!==n||s.streamInstanceId!==i||t.payload?.connectionId!==s.connectionId)return console.warn("[Client][AUTH] ignored stale reciprocal admission ACK",{remoteNodeId:e,transportStableId:n??null,presentationId:o}),false;if(this.reciprocalConfirmationsInFlight.has(o))return true;this.reciprocalConfirmationsInFlight.add(o);let a=t.payload?.reciprocalAccepted===true,c=typeof t.payload?.reciprocalScope=="string"&&t.payload.reciprocalScope.trim()||null,l=false;try{l=await this.deps.confirmReciprocalSessionAdmission(e,n,s.streamInstanceId,s.presentationId,a,c);}catch(p){console.warn("[Client][AUTH] reciprocal admission confirmation failed",{remoteNodeId:e,transportStableId:n,presentationId:o,error:p});}finally{this.reciprocalConfirmationsInFlight.delete(o);}return l&&this.pendingReciprocalAdmissions.delete(o),a?l?(c$1("[Client][AUTH] reciprocal admission committed",{remoteNodeId:e,transportStableId:n,presentationId:o,approvalScope:c}),this.schedulePeerReconciliationBestEffort("reciprocal-session-admission-committed"),true):(console.warn("[Client][AUTH] reciprocal admission ACK failed generation-bound confirmation",{remoteNodeId:e,transportStableId:n,presentationId:o}),this.schedulePeerReconciliationBestEffort("reciprocal-session-admission-stale"),true):(console.warn("[Client][AUTH] reciprocal admission was not committed by peer",{remoteNodeId:e,transportStableId:n,presentationId:o,reason:t.payload?.reciprocalReason??"rejected"}),this.schedulePeerReconciliationBestEffort("reciprocal-session-admission-rejected"),true)}handleNativeMainStreamClosed(e,t,n){if(!(!Number.isSafeInteger(t)||Number(t)<=0))for(let[i,o]of this.pendingReciprocalAdmissions)o.remoteNodeId===e&&o.transportStableId===t&&o.streamInstanceId===n&&(this.pendingReciprocalAdmissions.delete(i),this.reciprocalConfirmationsInFlight.delete(i));}createPresentationId(){let e=globalThis.crypto?.randomUUID;return typeof e=="function"?e.call(globalThis.crypto):`reciprocal-${Date.now()}-${Math.random().toString(36).slice(2)}`}scheduleLegacyReciprocalSessionAdmission(e,t){this.disposed||this.legacyReciprocalPresentationsInFlight.has(t)||(this.legacyReciprocalPresentationsInFlight.add(t),queueMicrotask(()=>{if(this.disposed){this.legacyReciprocalPresentationsInFlight.delete(t);return}this.deps.presentLegacyReciprocalSessionAdmission(e).catch(n=>{this.disposed||console.warn("[Client][AUTH] legacy reciprocal session admission failed",{remoteNodeId:e,connectionId:t,error:n});}).finally(()=>{this.legacyReciprocalPresentationsInFlight.delete(t);});}));}kickstartApprovedControlConnection(e,t){let n=i=>{this.disposed||console.warn("[Client][AUTH] post-approval kickstart error",{remoteNodeId:e,connectionId:t,error:i});};try{Promise.resolve(this.deps.ensureIncomingConnectionForRemoteNode(e)).then(i=>{this.disposed||(i?c$1("[Client][AUTH] post-approval kickstart opened control connection",{remoteNodeId:e,connectionId:i.id}):console.warn("[Client][AUTH] post-approval kickstart failed to open control connection",{remoteNodeId:e,connectionId:t}));}).catch(n);}catch(i){n(i);}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};sn.TOKEN_REJECTION_COOLDOWN_MS=5e3;var rn=sn;var an=class{constructor(e){this.deps=e;this.pendingConnections=new Map;this.disposed=false;}dispose(){this.disposed=true,this.pendingConnections.clear();}async ensureIncomingConnectionForRemoteNode(e){if(this.disposed)return null;let t=this.deps.getDeterministicConnectionId(e),n=this.deps.getConnection(t);if(n&&!n.isClosed)return this.attachNativeSignalSenderIfEligible(n,e),n;let i=this.pendingConnections.get(t);if(i)return i;let o=this.deps.getTrustFailureCooldown(e),s=this.deps.getTrustFailureCooldownMs();if(o!==void 0&&Date.now()-o<s&&!this.deps.isSessionTokenApprovedNode(e))return c$1("[Client][TRUST] Skipping connection rebuild for node in trust-failure cooldown",{remoteNodeId:e,cooldownRemainingMs:s-(Date.now()-o)}),null;let a=this.createIncomingConnection(t,e);this.pendingConnections.set(t,a);try{return await a}finally{this.pendingConnections.delete(t);}}attachNativeSignalSenderIfEligible(e,t){let n=typeof e.getControlFrameMode=="function"?e.getControlFrameMode():"typed";c$1("[Client][NATIVE-MAIN] Reusing existing control connection",{connectionId:e.id,remoteNodeId:t,upgradeState:typeof e.getUpgradeState=="function"?e.getUpgradeState():null,controlFrameMode:n});let i=this.deps.getKnownDevicePlatform(this.deps.getKnownDeviceIdForNode(t),t);if(!this.deps.isNativeMainPeerPlatform(i)&&!this.deps.isSessionTokenApprovedNode(t))return;let o=this.deps.getWasmClient();if(!o||typeof o.open_bi!="function")return;let s=async a=>{await this.deps.sendNativeSignalEnvelope(e,t,a,o);};n!=="native-main"&&typeof e.promoteToNativeMainControlRoute=="function"?(e.promoteToNativeMainControlRoute(s),c$1("[Client][NATIVE-MAIN] Promoted bootstrap connection to native control route",{connectionId:e.id,remoteNodeId:t})):n==="native-main"&&e.setNativeSignalSender(s);}async createIncomingConnection(e,t){if(this.disposed)return null;let n=this.deps.getWasmClient();if(!n||typeof n.open_bi!="function")return null;let i=this.deps.getKnownDeviceIdForNode(t);if(!this.deps.getKnownDevicePlatform(i,t)&&!this.deps.isSessionTokenApprovedNode(t))return c$1("[Client][NATIVE-MAIN] Deferring native-main connection creation until peer platform is known",{remoteNodeId:t,connectionId:e,knownDeviceId:i}),null;let s;try{s=await this.deps.openNativeSignalBiStream(n,t);}catch(c){return console.warn("[Client][NATIVE-MAIN] Failed to open control stream for native signal routing",{remoteNodeId:t,connectionId:e,error:c}),null}if(this.disposed)return await B$2(s,"native-main-connection-disposed-after-open"),null;try{await this.deps.writeNativeMainLabelHeaderOnBiStream(s,t);}catch(c){return console.warn("[Client][NATIVE-MAIN] Failed to write label header on control stream",{remoteNodeId:t,connectionId:e,error:c}),null}if(this.disposed)return await B$2(s,"native-main-connection-disposed-after-label"),null;let a;return a=new de(e,this.deps.getLocalNodeId(),t,s.send.getWriter(),s.recv.getReader(),{rtcConfig:this.deps.getRTCConfig(),transportContext:this.deps.createTransportContext(t),applicationCrypto:this.deps.getApplicationCrypto(),requireApplicationCrypto:this.deps.shouldNegotiateApplicationKeyAgreement(),controlFrameMode:"native-main",onTransportStatusChange:c=>this.deps.handleConnectionTransportStatus(a,c.activeTransport,c.parallelTransport),onApplicationRouteMissing:c=>{this.deps.handleConnectionApplicationRouteMissing(e,c);}}),a.setNativeSignalSender(async c=>{await this.deps.sendNativeSignalEnvelope(a,t,c,n);}),this.deps.initializeConnectionTrust(a,i),this.deps.markConnectionTrustVerified(a,i),this.deps.registerConnection(a),this.deps.announceConnectionWhenStable(a),c$1("[Client][HANDSHAKE] sending hello (native signal routing path)",{connectionId:a.id,remoteNodeId:a.remoteNodeId}),this.sendNativeRoutingHelloInBackground(a),c$1("[Client][NATIVE-MAIN] Created control connection for native signal routing",{connectionId:a.id,remoteNodeId:t,channelId:this.deps.getConnectionChannelId(a.id)??null,rtcEnabled:this.deps.isWebRTCTransportEnabled()}),a}sendNativeRoutingHelloInBackground(e){let t=n=>{this.disposed||console.warn("[Client][TRUST] Failed to send outgoing handshake for native signal routing",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:n});};try{Promise.resolve(this.deps.sendTransportHandshake(e,"hello")).then(()=>{this.disposed||this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,"protected-hello:native-signal-routing");}).catch(t);}catch(n){t(n);}}};var cn=class{constructor(e,t,n=[0,250,1e3,2500]){this.maxPerNode=e;this.ttlMs=t;this.retryDelaysMs=n;this.pendingByNodeId=new Map;this.retryTimers=new Set;this.disposed=false;}queue(e,t,n,i,o){if(this.disposed)return;let s=this.pendingByNodeId.get(e)??[];s.push({message:t,source:n,traceId:i??null,receivedAtMs:Date.now()}),s.length>this.maxPerNode&&s.splice(0,s.length-this.maxPerNode),this.pendingByNodeId.set(e,s),c$1("[Client][NATIVE-MAIN] Queued TS handshake until control connection is registered",{remoteNodeId:e,action:t.action??"hello",source:n,traceId:i||null,pendingCount:s.length});for(let a of this.retryDelaysMs){let c=setTimeout(()=>{this.retryTimers.delete(c),!this.disposed&&o(e,`queued-handshake-retry:${a}`);},a);this.retryTimers.add(c);}}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear(),this.pendingByNodeId.clear();}}async flush(e,t,n){if(this.disposed)return false;let i=this.pendingByNodeId.get(e);if(!i||i.length===0)return false;let o=n.findManualDisconnectProjectionForNativeNode(e);if(o)return this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Dropped queued TS handshakes for manually disconnected peer",{remoteNodeId:e,peerId:o.peerId,droppedCount:i.length,trigger:t}),false;let s=n.findLiveConnectionForRemoteNode(e);if(s||(s=await n.ensureIncomingConnectionForRemoteNode(e).catch(()=>null)),this.disposed)return false;if(!s){let a=Date.now(),c=i.filter(l=>a-l.receivedAtMs<=this.ttlMs);return c.length===0?(this.pendingByNodeId.delete(e),console.warn("[Client][NATIVE-MAIN] Dropping queued TS handshakes after control connection did not appear",{remoteNodeId:e,trigger:t,droppedCount:i.length})):c.length!==i.length&&this.pendingByNodeId.set(e,c),false}this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Replaying queued TS handshakes to Connection",{remoteNodeId:e,connectionId:s.id,trigger:t,count:i.length});for(let a of i){if(this.disposed)return false;await n.handleMessage(s,a.message);}return true}};var xa="main";function it(){let r=new TextEncoder().encode(xa),e=new ArrayBuffer(5+r.byteLength),t=new Uint8Array(e);return t[0]=0,new DataView(e).setUint32(1,r.byteLength,false),t.set(r,5),t}function Ae(r){let e=JSON.stringify(r),t=new TextEncoder().encode(e),n=new Uint8Array(1+t.byteLength);return n[0]=0,n.set(t,1),n}function me(r){let e=new ArrayBuffer(4+r.byteLength);new DataView(e).setUint32(0,r.byteLength,false);let n=new Uint8Array(e);return n.set(r,4),n}var ln=class{constructor(e,t){this.config=e;this.deps=t;}protocolConfig(){return {protocolByte:this.config.protocolByte,label:this.config.label,maxLabelBytes:this.config.maxLabelBytes,maxFrameBytes:this.config.maxFrameBytes}}encodeFrame(e){return Rr(e,this.protocolConfig())}async dispatchMessage(e,t){return Pr(this.config.eventName,e,this.deps.getRemoteDeviceId(e),t)}async writeAck(e,t,n=null){let i=this.deps.getReceiverDeviceId();await this.writeMessage(e,{channel:"native-main",action:"ack",requestId:t.requestId,payload:{received:true,channel:t.channel,action:t.action,...i?{receiverDeviceId:i}:{},...n!==null?{handlerResponse:n}:{}},timestamp:Date.now(),from:"web"});}async writeMessage(e,t){await e.write(this.encodeFrame(t));}async writeLabeledMessage(e,t){await e.write(it()),await e.write(me(new TextEncoder().encode(JSON.stringify(t))));}async writeLabelHeaderOnBiStream(e,t){let n=e.send.getWriter();try{await n.write(it());}catch(i){throw console.warn("[Client][NATIVE-MAIN] Label header write failed",{remoteNodeId:t,error:i}),i}finally{try{n.releaseLock();}catch{}}}};var dn=class{constructor(e){this.deps=e;this.disposed=false;this.activeReaders=new Set;}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.activeReaders)this.cancelReaderBestEffort(e);this.activeReaders.clear();}}async handleNativeMainStream(e,t,n){if(this.disposed||!y(e))return;let i,o,s=false;try{i=e.recv.getReader(),o=e.send.getWriter();}catch(g){console.warn("[Client][NATIVE-MAIN] Unable to acquire stream handles",{remoteNodeId:t,error:g});return}this.activeReaders.add(i);let a=this.createStreamInstanceId(),c=new Uint8Array(0),l="stream-active",p=0,u=()=>{s||(this.deps.registerInboundNativeMainWriter(t,o),s=true);};try{for(;!this.disposed;){let g=this.tryExtractNativeMainPayload(c);for(;!g.ready&&!this.disposed;){let{done:m,value:v}=await i.read();if(this.disposed)return;if(m){l=g.phase==="frame-start"?p>0?"remote-closed-after-frame":"remote-closed-before-frame-length":"remote-closed-mid-frame",(p===0||g.phase!=="frame-start")&&this.schedulePeerReconciliationBestEffort("native-main-stream-close"),g.phase==="frame-start"?c$1("[Client][NATIVE-MAIN] Remote closed native main stream",{remoteNodeId:t,handledFrameCount:p}):console.warn("[Client][NATIVE-MAIN] Native main stream ended mid-frame",{remoteNodeId:t,messageLen:g.expectedFrameLength,bufferedBytes:c.byteLength});return}v&&v.byteLength>0&&(c=w$1([c,new Uint8Array(v)]));try{g=this.tryExtractNativeMainPayload(c);}catch(S){l="invalid-native-main-frame",console.warn("[Client][NATIVE-MAIN] Invalid native main frame",{remoteNodeId:t,error:S});return}}if(g.expectedFrameLength===0){c=c.slice(g.consumedBytes);continue}let y=g.payloadBytes;c=c.slice(g.consumedBytes),p+=1,await this.handleNativeMainPayloadBytes(y,t,o,void 0,"bi",u,n,a);}}catch(g){if(this.disposed)return;l="handler-error",this.schedulePeerReconciliationBestEffort("native-main-handler-error"),console.error("[Client][NATIVE-MAIN] Native main stream handler failed",{remoteNodeId:t,error:g});}finally{this.deps.handleNativeMainStreamClosed(t,n,a),s&&this.deps.clearInboundNativeMainWriter(t,o,l),this.activeReaders.delete(i);try{o.releaseLock();}catch{}try{i.releaseLock();}catch{}}}tryExtractNativeMainPayload(e){return _r(e,this.deps.getProtocolConfig())}async tryHandleNativeMainUniStream(e,t,n){if(this.disposed||!e||typeof e.getReader!="function")return false;let i;try{i=e.getReader();}catch{return false}this.activeReaders.add(i);let o=new Uint8Array(0),s=false;try{for(;!this.disposed;){let a=this.tryExtractNativeMainPayload(o);for(;!a.ready&&!this.disposed;){let{done:c,value:l}=await i.read();if(this.disposed||c)return s;l&&l.byteLength>0&&(o=w$1([o,new Uint8Array(l)])),a=this.tryExtractNativeMainPayload(o);}s=!0,o=o.slice(a.consumedBytes),await this.handleNativeMainPayloadBytes(a.payloadBytes,t,null,n,"uni");}return s}catch(a){return this.disposed?s:s?(console.warn("[Client][NATIVE-MAIN] Read-only native main uni handler failed",{remoteNodeId:t,traceId:n||null,error:a}),true):false}finally{this.activeReaders.delete(i);try{i.releaseLock();}catch{}}}async handleNativeMainPayloadBytes(e,t,n,i,o,s,a,c){if(this.disposed)return;let l=e.byteLength>1&&e[0]===0?e.slice(1):e,p;try{p=JSON.parse(new TextDecoder().decode(l));}catch(m){let v=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;v?v.receiveDataPayload(l):console.warn("[Client][NATIVE-MAIN] Dropping binary app payload: no control connection",{remoteNodeId:t,traceId:i||null,source:o,error:m});return}let u=this.deps.findManualDisconnectProjectionForNativeNode(t);if(this.isHandshakeMessage(p)){if(s?.(),u){c$1("[Client][NATIVE-MAIN] Dropping TS handshake for manually disconnected peer",{remoteNodeId:t,peerId:u.peerId,action:p.action??"hello",source:o});return}let m=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;if(!m){this.deps.queuePendingNativeMainHandshake(t,p,o,i||null);return}c$1("[Client][NATIVE-MAIN] Routed TS handshake to Connection",{remoteNodeId:t,connectionId:m.id,action:p.action??"hello",source:o}),await this.deps.handleMessage(m,p);return}if(this.isNativeSignalEnvelope(p)){if(s?.(),c$1("[Client][NATIVE-MAIN] Received #pluto-signal envelope",{remoteNodeId:t,signalType:p.content?.type??null,transport:p.content?.transport??null,source:o}),u){c$1("[Client][NATIVE-MAIN] Dropping native WebRTC signal for manually disconnected peer",{remoteNodeId:t,peerId:u.peerId,signalType:p.content?.type??null,source:o});return}let m=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;if(!m){this.deps.queuePendingNativeMainSignal(t,p.content,o,i||null);return}m.receiveInternalSignal(p.content),c$1("[Client][NATIVE-MAIN] Routed #pluto-signal to Connection",{remoteNodeId:t,connectionId:m.id,signalType:p.content?.type??null,source:o});return}let g=p;if(c$1("[Client][NATIVE-MAIN] Received native main message",{remoteNodeId:t,channel:g.channel,action:g.action,requestId:g.requestId??null,source:o}),g.channel==="handshake"&&g.action==="request"){n&&await this.deps.handleNativeHandshakeRequest(n,t,g);return}if(g.channel==="session-token"&&g.action==="request"){n&&await this.deps.handleNativeSessionTokenRequest(n,t,g,a,c);return}if(g.channel==="session-token"&&g.action==="event"&&g.payload?.responseAck===true){await this.deps.handleNativeSessionTokenResponseAck(t,g,a,c);return}if(!g.channel&&!g.action&&!g.requestId){s?.();let m=await this.deps.ensureIncomingConnectionForRemoteNode(t);if(this.disposed)return;if(!m){console.warn("[Client][NATIVE-MAIN] Dropping app payload: no control connection",{remoteNodeId:t,traceId:i||null,source:o});return}m.receiveMessage(p);return}let y=await this.deps.dispatchNativeMainMessage(t,g);this.disposed||n&&await this.writeReceiveAckBestEffort(n,g,y,t,o);}isNativeSignalEnvelope(e){if(!e||typeof e!="object")return false;let t=e;return t.type==="#pluto-signal"&&typeof t.content=="object"&&t.content!==null}isHandshakeMessage(e){return !e||typeof e!="object"?false:e.type==="handshake"}cancelReaderBestEffort(e){try{Promise.resolve(e.cancel("native-main-payload-router-disposed")).catch(()=>{});}catch{}}createStreamInstanceId(){let e=globalThis.crypto?.randomUUID;return typeof e=="function"?e.call(globalThis.crypto):`native-main-stream-${Date.now()}-${Math.random().toString(36).slice(2)}`}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}async writeReceiveAckBestEffort(e,t,n,i,o){if(!this.disposed)try{await this.deps.writeNativeMainReceiveAck(e,t,n);}catch(s){if(this.disposed)return;console.warn("[Client][NATIVE-MAIN] Failed to ack native main message",{remoteNodeId:i,channel:t.channel,action:t.action,source:o,error:s});}}};var pn=class{constructor(e,t,n=[0,250,1e3,2500]){this.maxPerNode=e;this.ttlMs=t;this.retryDelaysMs=n;this.pendingByNodeId=new Map;this.retryTimers=new Set;this.disposed=false;}queue(e,t,n,i,o){if(this.disposed)return;let s=this.pendingByNodeId.get(e)??[];s.push({content:t,source:n,traceId:i??null,receivedAtMs:Date.now()}),s.length>this.maxPerNode&&s.splice(0,s.length-this.maxPerNode),this.pendingByNodeId.set(e,s),c$1("[Client][NATIVE-MAIN] Queued native WebRTC signal until control connection is registered",{remoteNodeId:e,signalType:t?.type??null,source:n,traceId:i||null,pendingCount:s.length});for(let a of this.retryDelaysMs){let c=setTimeout(()=>{this.retryTimers.delete(c),!this.disposed&&o(e,`queued-signal-retry:${a}`);},a);this.retryTimers.add(c);}}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear(),this.pendingByNodeId.clear();}}async flush(e,t,n){if(this.disposed)return false;let i=this.pendingByNodeId.get(e);if(!i||i.length===0)return false;let o=n.findManualDisconnectProjectionForNativeNode(e);if(o)return this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Dropped queued native WebRTC signals for manually disconnected peer",{remoteNodeId:e,peerId:o.peerId,droppedCount:i.length,trigger:t}),false;let s=n.findLiveConnectionForRemoteNode(e);if(s||(s=await n.ensureIncomingConnectionForRemoteNode(e).catch(()=>null)),this.disposed)return false;if(!s){let a=Date.now(),c=i.filter(l=>a-l.receivedAtMs<=this.ttlMs);return c.length===0?(this.pendingByNodeId.delete(e),console.warn("[Client][NATIVE-MAIN] Dropping queued native WebRTC signals after control connection did not appear",{remoteNodeId:e,trigger:t,droppedCount:i.length})):c.length!==i.length&&this.pendingByNodeId.set(e,c),false}this.pendingByNodeId.delete(e),c$1("[Client][NATIVE-MAIN] Replaying queued native WebRTC signals to Connection",{remoteNodeId:e,connectionId:s.id,trigger:t,count:i.length});for(let a of i){if(this.disposed)return false;s.receiveInternalSignal(a.content);}return true}};var un=class{constructor(e){this.deps=e;this.disposed=false;}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Native main signal sender is disposed")}async openNativeSignalBiStream(e,t){this.assertActive();let n=e.open_native_main_control_bi;if(typeof n=="function"){let i=await n.call(e,t);return this.assertActive(),i}throw new Error("[Client][NATIVE-MAIN] open_native_main_control_bi is unavailable on this WASM build; native-main signaling cannot open a control stream under mandatory application crypto. Rebuild the openrtc WASM (pnpm --filter openrtc build:wasm).")}async sendViaDedicatedStream(e,t,n,i){this.assertActive();let o=await this.openNativeSignalBiStream(e,t);this.assertActive();let s=o.send.getWriter();try{if(await s.write(it()),this.disposed)return;await s.write(me(Ae(i)));}catch(a){throw console.warn("[Client][NATIVE-MAIN] Dedicated-stream signal send failed",{remoteNodeId:t,signalType:i?.content?.type??null,error:a}),a}finally{try{s.releaseLock();}catch{}}}async sendEnvelope(e,t,n,i){if(this.disposed)return;let o=n?.content?.transport??null,s=n?.content?.type??null,a=o==="webrtc"&&(s==="sdp"||s==="candidate"||s==="renegotiate"),c=n?.type==="handshake",l=a&&e.getUpgradeState()==="upgrading"||c,p=this.deps.isSessionTokenApprovedNode(t)&&this.deps.isSessionTokenApprovedConnection(e.id),u=p||l,g=this.deps.isSessionTokenApprovedNode(t),y=this.deps.isSessionTokenApprovedConnection(e.id),m=await this.deps.sendViaInboundControlStream(t,n,{ignoreCooldown:l});if(!this.disposed){if(m.sent){if(c$1("[Client][NATIVE-MAIN] Sent native signal over inbound control stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,writerId:m.writerId,writerAgeMs:m.writerAgeMs}),c$1("[Client][NATIVE-MAIN] Signal route=inbound-control",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,writerId:m.writerId,writerAgeMs:m.writerAgeMs}),c$1("[SIGNAL-STREAM][TS] reply-on-persistent-writer",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,writerId:m.writerId,writerAgeMs:m.writerAgeMs}),l&&u&&s!=="renegotiate")try{if(await this.sendViaDedicatedStream(i,t,e,n),this.disposed)return;c$1("[Client][NATIVE-MAIN] Signal route=dedicated-open_bi-mirror",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null});}catch(S){console.warn("[Client][NATIVE-MAIN] Recovery dedicated-stream mirror send failed",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,error:S});}return}if(c$1("[Client][NATIVE-MAIN] Signal route=inbound-control-unavailable",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,reason:m.reason,writerId:m.writerId,writerAgeMs:m.writerAgeMs,inboundError:m.error,hasApprovedNode:g,hasApprovedConnectionId:y,hasApprovedDedicatedStream:p,preferDedicatedSignalPath:l,canUseDedicatedStream:u}),u)try{if(await this.sendViaDedicatedStream(i,t,e,n),this.disposed)return;c$1("[Client][NATIVE-MAIN] Sent native signal over dedicated stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null}),c$1("[Client][NATIVE-MAIN] Signal route=dedicated-open_bi",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,inboundFallbackReason:m.reason});return}catch(v){console.warn("[Client][NATIVE-MAIN] Dedicated-stream signal send failed; falling back to control stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,error:v});}try{if(this.disposed||(await e.sendRawIrohFrame(me(Ae(n))),this.disposed))return;c$1("[Client][NATIVE-MAIN] Sent native signal over control stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null}),c$1("[Client][NATIVE-MAIN] Signal route=cached-control-writer",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,inboundFallbackReason:m.reason});return}catch(v){if(console.warn("[Client][NATIVE-MAIN] Control-stream signal send failed",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,error:v}),!u)throw v}this.disposed||(await this.sendViaDedicatedStream(i,t,e,n),!this.disposed&&(c$1("[Client][NATIVE-MAIN] Sent native signal over dedicated stream",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null}),c$1("[Client][NATIVE-MAIN] Signal route=dedicated-open_bi-fallback",{connectionId:e.id,remoteNodeId:t,signalType:n?.content?.type??null,negotiationId:n?.content?.negotiationId??null,inboundFallbackReason:m.reason})));}}};var gn=class{constructor(){this.writers=new Map;this.writeMutexes=new Map;this.writerMeta=new Map;this.bypassUntilMs=new Map;this.writerSeq=0;this.disposed=false;}dispose(){if(!this.disposed){this.disposed=true;for(let e of this.writers.values())try{e.releaseLock();}catch{}this.writers.clear(),this.writeMutexes.clear(),this.writerMeta.clear(),this.bypassUntilMs.clear();}}registerInboundWriter(e,t){if(this.disposed){try{t.releaseLock();}catch{}return}let n=this.writers instanceof Map?this.writers:null,i=this.writerMeta instanceof Map?this.writerMeta:null;if(!n||!e||!t)return;let o=n.get(e);this.writerSeq+=1;let s=this.writerSeq;n.set(e,t),i?.set(e,{id:s,registeredAtMs:Date.now()}),this.bypassUntilMs instanceof Map&&this.bypassUntilMs.delete(e),c$1("[Client][NATIVE-MAIN] Inbound control writer registered",{remoteNodeId:e,writerId:s,replacedExistingWriter:!!o&&o!==t}),c$1("[SIGNAL-STREAM][TS] writer-registered",{remoteNodeId:e,writerId:s,replacedExistingWriter:!!o&&o!==t});}clearInboundWriter(e,t,n,i="stream-finalize"){if(this.disposed)return;let o=this.writers instanceof Map?this.writers:null,s=this.writeMutexes instanceof Map?this.writeMutexes:null,a=this.writerMeta instanceof Map?this.writerMeta:null;if(!o||!s)return;let c=o.get(e),l=a?.get(e);c===t?(o.delete(e),a?.delete(e),this.bypassUntilMs.set(e,Date.now()+n),c$1("[Client][NATIVE-MAIN] Inbound control writer cleared",{remoteNodeId:e,writerId:l?.id??null,ageMs:l?Date.now()-l.registeredAtMs:null,reason:i}),c$1("[SIGNAL-STREAM][TS] writer-cleared",{remoteNodeId:e,writerId:l?.id??null,ageMs:l?Date.now()-l.registeredAtMs:null,reason:i})):c$1("[Client][NATIVE-MAIN] Inbound control writer clear skipped (mismatch)",{remoteNodeId:e,activeWriterId:l?.id??null,reason:i}),s.delete(e);}async sendViaInboundControlStream(e,t,n,i={}){if(this.disposed)return {sent:false,reason:"writer-registry-disposed",writerId:null,writerAgeMs:null,error:null};let o=this.writers instanceof Map?this.writers:null,s=this.writeMutexes instanceof Map?this.writeMutexes:null,a=this.writerMeta instanceof Map?this.writerMeta:null;if(!o||!s)return {sent:false,reason:"writer-or-mutex-map-unavailable",writerId:null,writerAgeMs:null,error:null};let c=a?.get(e),l=this.bypassUntilMs instanceof Map?this.bypassUntilMs:null,p=l?.get(e)??0;if(!i.ignoreCooldown&&p>Date.now())return {sent:false,reason:"inbound-writer-cooldown",writerId:c?.id??null,writerAgeMs:c?Date.now()-c.registeredAtMs:null,error:null};let u=o.get(e),g=c?.id??null,y=c?Date.now()-c.registeredAtMs:null;if(!u)return l?.set(e,Date.now()+n),{sent:false,reason:"no-inbound-writer",writerId:g,writerAgeMs:y,error:null};let m=me(Ae(t)),v=s.get(e)??Promise.resolve(),S,I=new Promise(k=>{S=k;});s.set(e,I);try{return await v.catch(()=>{}),await u.write(m),{sent:!0,reason:"sent",writerId:g,writerAgeMs:y,error:null}}catch(k){return l?.set(e,Date.now()+n),console.warn("[Client][NATIVE-MAIN] Inbound control-stream signal send failed",{remoteNodeId:e,signalType:t?.content?.type??null,writerId:g,writerAgeMs:y,error:k}),{sent:false,reason:"inbound-writer-write-failed",writerId:g,writerAgeMs:y,error:k?.message??String(k)}}finally{S(),s.get(e)===I&&s.delete(e);}}};var hn=class{constructor(e,t,n){this.deps=e;this.protocolConfig=t;this.timingConfig=n;this.writers=new gn;this.disposed=false;this.messageIO=new ln({eventName:t.eventName,protocolByte:t.protocolByte,label:t.label,maxLabelBytes:t.maxLabelBytes,maxFrameBytes:t.maxFrameBytes},{getReceiverDeviceId:()=>e.getReceiverDeviceId(),getRemoteDeviceId:i=>e.getKnownDeviceIdForNode(i)}),this.handshakeQueue=new cn(n.pendingHandshakeMaxPerNode,n.pendingHandshakeTtlMs),this.signalQueue=new pn(n.pendingHandshakeMaxPerNode,n.pendingHandshakeTtlMs),this.deps.registerDisposer(()=>this.dispose());}get writerRegistry(){return this.writers}get connectionController(){return this.getConnections()}get handshakeQueueController(){return this.handshakeQueue}get messageIOController(){return this.messageIO}get payloadRouterController(){return this.getPayloadRouter()}dispose(){this.disposed=true,this.handshakeQueue.dispose(),this.signalQueue.dispose(),this.admission?.dispose(),this.connections?.dispose(),this.payloadRouter?.dispose(),this.writers.dispose(),this.signalSender?.dispose();}retirePendingReciprocalAdmissions(e){this.admission?.retirePendingReciprocalAdmissions(e);}async acceptNativeMessage(e,t,n){return this.disposed?false:this.getAdmission().acceptNativeMessage(e,t,n)}tryHandleNativeMainUniStream(e,t,n){return this.disposed?Promise.resolve(false):this.getPayloadRouter().tryHandleNativeMainUniStream(e,t,n)}handleNativeMainStream(e,t,n){return this.disposed?Promise.resolve():Number.isSafeInteger(n)&&Number(n)>0?this.getPayloadRouter().handleNativeMainStream(e,t,n):this.getPayloadRouter().handleNativeMainStream(e,t)}writeLabelHeaderOnBiStream(e,t){return this.disposed?Promise.resolve():this.messageIO.writeLabelHeaderOnBiStream(e,t)}openSignalBiStream(e,t){return this.disposed?Promise.reject(new Error("Native main controller is disposed")):this.getSignalSender().openNativeSignalBiStream(e,t)}async sendSignalEnvelope(e,t,n,i){this.disposed||(await this.getSignalSender().sendEnvelope(e,t,n,i),this.disposed||e.handleBaseTransportAvailable("native-main-control-send"));}ensureIncomingConnectionForRemoteNode(e){return this.disposed?Promise.resolve(null):this.getConnections().ensureIncomingConnectionForRemoteNode(e)}flushPendingHandshakesForNode(e,t){return this.disposed?Promise.resolve(false):this.handshakeQueue.flush(e,t,{findManualDisconnectProjectionForNativeNode:n=>this.deps.findManualDisconnectProjectionForNativeNode(n),findLiveConnectionForRemoteNode:n=>this.deps.findLiveConnectionForRemoteNode(n),ensureIncomingConnectionForRemoteNode:n=>this.deps.ensureIncomingConnectionForRemoteNode(n),handleMessage:(n,i)=>Promise.resolve(this.deps.handleMessage(n,i))})}flushPendingSignalsForNode(e,t){return this.disposed?Promise.resolve(false):this.signalQueue.flush(e,t,{findManualDisconnectProjectionForNativeNode:n=>this.deps.findManualDisconnectProjectionForNativeNode(n),findLiveConnectionForRemoteNode:n=>this.deps.findLiveConnectionForRemoteNode(n),ensureIncomingConnectionForRemoteNode:n=>this.deps.ensureIncomingConnectionForRemoteNode(n)})}getSignalSender(){return this.signalSender||(this.signalSender=new un({isSessionTokenApprovedNode:e=>this.deps.isSessionTokenApprovedNode(e),isSessionTokenApprovedConnection:e=>this.deps.isSessionTokenApprovedConnection(e),sendViaInboundControlStream:(e,t,n)=>this.writers.sendViaInboundControlStream(e,t,this.timingConfig.inboundWriterRetryCooldownMs,n)}),this.disposed&&this.signalSender.dispose()),this.signalSender}getConnections(){return this.connections||(this.connections=new an({getDeterministicConnectionId:e=>this.deps.getDeterministicConnectionId(e),getConnection:e=>this.deps.getConnection(e),getWasmClient:()=>this.deps.getWasmClient(),getLocalNodeId:()=>this.deps.getLocalNodeId(),getKnownDeviceIdForNode:e=>this.deps.getKnownDeviceIdForNode(e),getKnownDevicePlatform:(e,t)=>this.deps.getKnownDevicePlatform(e,t),isNativeMainPeerPlatform:e=>this.deps.isNativeMainPeerPlatform(e),getTrustFailureCooldown:e=>this.deps.getTrustFailureCooldown(e),getTrustFailureCooldownMs:()=>this.timingConfig.trustFailureCooldownMs,isSessionTokenApprovedNode:e=>this.deps.isSessionTokenApprovedNode(e),openNativeSignalBiStream:(e,t)=>this.openSignalBiStream(e,t),writeNativeMainLabelHeaderOnBiStream:(e,t)=>this.writeLabelHeaderOnBiStream(e,t),sendNativeSignalEnvelope:(e,t,n,i)=>this.sendSignalEnvelope(e,t,n,i),getRTCConfig:()=>this.deps.getRTCConfig(),createTransportContext:e=>this.deps.createTransportContext(e),getApplicationCrypto:()=>this.deps.getApplicationCrypto(),shouldNegotiateApplicationKeyAgreement:()=>this.deps.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(e,t,n)=>this.deps.handleConnectionTransportStatus(e,t,n??null),handleConnectionApplicationRouteMissing:(e,t)=>this.deps.handleConnectionApplicationRouteMissing(e,t),initializeConnectionTrust:(e,t)=>{this.deps.initializeConnectionTrust(e,t);},markConnectionTrustVerified:(e,t)=>{this.deps.markConnectionTrustVerified(e,t);},registerConnection:e=>this.deps.registerConnection(e),announceConnectionWhenStable:e=>this.deps.announceConnectionWhenStable(e),sendTransportHandshake:(e,t)=>this.deps.sendTransportHandshake(e,t),requestProtectedWebRTCUpgradeIfInitiator:(e,t)=>this.deps.requestProtectedWebRTCUpgradeIfInitiator(e,t),getConnectionChannelId:e=>this.deps.getConnectionChannelId(e),isWebRTCTransportEnabled:()=>this.deps.isWebRTCTransportEnabled()}),this.disposed&&this.connections.dispose()),this.connections}getAdmission(){return this.admission||(this.admission=new rn({getDeterministicConnectionId:e=>this.deps.getDeterministicConnectionId(e),getNativeMainConnectionId:e=>this.deps.getNativeMainConnectionId(e),getConnection:e=>this.deps.getConnection(e),handleMessage:(e,t)=>this.deps.handleMessage(e,t),getLocalDeviceId:()=>this.deps.getLocalDeviceId(),getFallbackLocalDeviceId:()=>this.deps.getFallbackLocalDeviceId(),getConfiguredDeviceName:()=>this.deps.getConfiguredDeviceName(),getNativeMainProtocolVersion:()=>this.protocolConfig.protocolVersion,isNativeRuntime:()=>this.deps.isNativeRuntime(),isLikelyMobileBrowser:()=>this.deps.isLikelyMobileBrowser(),writeNativeMainMessage:(e,t)=>this.messageIO.writeLabeledMessage(e,t),validateIncomingSessionToken:(e,t,n)=>this.deps.validateIncomingSessionToken(e,t,n),applySessionTokenTrustApproval:(e,t,n)=>this.deps.applySessionTokenTrustApproval(e,t,n),rememberPendingSessionTokenTrustApproval:(e,t)=>this.deps.rememberPendingSessionTokenTrustApproval(e,t),markSessionTokenApprovedNode:e=>this.deps.markSessionTokenApprovedNode(e),markSessionTokenApprovedConnection:e=>this.deps.markSessionTokenApprovedConnection(e),clearSessionTokenRejectionCooldown:e=>this.deps.clearSessionTokenRejectionCooldown(e),getSessionTokenRejectionCooldown:e=>this.deps.getSessionTokenRejectionCooldown(e),setSessionTokenRejectionCooldown:(e,t)=>this.deps.setSessionTokenRejectionCooldown(e,t),clearTrustFailureCooldown:e=>{this.deps.clearTrustFailureCooldown(e);},schedulePeerReconciliation:e=>this.deps.schedulePeerReconciliation(e),ensureIncomingConnectionForRemoteNode:e=>this.deps.ensureIncomingConnectionForRemoteNode(e),getReciprocalSessionAdmission:(e,t,n,i,o)=>this.deps.getReciprocalSessionAdmission(e,t,n,i,o),presentLegacyReciprocalSessionAdmission:e=>this.deps.presentLegacyReciprocalSessionAdmission(e),confirmReciprocalSessionAdmission:(e,t,n,i,o,s)=>this.deps.confirmReciprocalSessionAdmission(e,t,n,i,o,s),disconnectRemoteNode:e=>this.deps.disconnectRemoteNode(e)}),this.disposed&&this.admission.dispose()),this.admission}getPayloadRouter(){return this.payloadRouter||(this.payloadRouter=new dn({getProtocolConfig:()=>this.messageIO.protocolConfig(),registerInboundNativeMainWriter:(e,t)=>this.writers.registerInboundWriter(e,t),clearInboundNativeMainWriter:(e,t,n)=>this.writers.clearInboundWriter(e,t,this.timingConfig.inboundWriterRetryCooldownMs,n),schedulePeerReconciliation:e=>this.deps.schedulePeerReconciliation(e),ensureIncomingConnectionForRemoteNode:e=>this.deps.ensureIncomingConnectionForRemoteNode(e),queuePendingNativeMainHandshake:(e,t,n,i)=>this.handshakeQueue.queue(e,t,n,i,(o,s)=>{this.flushPendingHandshakesForNode(o,s);}),queuePendingNativeMainSignal:(e,t,n,i)=>this.signalQueue.queue(e,t,n,i,(o,s)=>{this.flushPendingSignalsForNode(o,s);}),findManualDisconnectProjectionForNativeNode:e=>this.deps.findManualDisconnectProjectionForNativeNode(e),handleMessage:(e,t)=>this.deps.handleMessage(e,t),handleNativeHandshakeRequest:(e,t,n)=>this.getAdmission().handleHandshakeRequest(e,t,n),handleNativeSessionTokenRequest:(e,t,n,i,o)=>this.getAdmission().handleSessionTokenRequest(e,t,n,i,o),handleNativeSessionTokenResponseAck:(e,t,n,i)=>this.getAdmission().handleSessionTokenResponseAck(e,t,n,i),handleNativeMainStreamClosed:(e,t,n)=>this.getAdmission().handleNativeMainStreamClosed(e,t,n),dispatchNativeMainMessage:(e,t)=>this.messageIO.dispatchMessage(e,t),writeNativeMainReceiveAck:(e,t,n)=>this.messageIO.writeAck(e,t,n)}),this.disposed&&this.payloadRouter.dispose()),this.payloadRouter}};function Br(r){let{host:e}=r;return new hn({registerDisposer:t=>e.registerDisposer(t),getDeterministicConnectionId:t=>e.getDeterministicConnectionId(t),getNativeMainConnectionId:t=>e.getNativeMainConnectionId(t),getConnection:t=>e.getConnection(t),getWasmClient:()=>e.getWasmClient(),getLocalNodeId:()=>e.getLocalNodeId(),getReceiverDeviceId:()=>e.getDeviceId()??e.getOptions().localDeviceId??null,getKnownDeviceIdForNode:t=>e.getKnownDeviceIdForNode(t),getKnownDevicePlatform:(t,n)=>e.getKnownDevicePlatform(t,n),isNativeMainPeerPlatform:t=>br(t),getTrustFailureCooldown:t=>e.getTrustFailureCooldown(t),isSessionTokenApprovedNode:t=>e.isSessionTokenApprovedNode(t),isSessionTokenApprovedConnection:t=>e.isSessionTokenApprovedConnection(t),getRTCConfig:()=>l(e.getOptions(),t=>c$1(t)),createTransportContext:t=>e.createTransportContext(t),getApplicationCrypto:()=>e.getApplicationCrypto(),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),handleConnectionTransportStatus:(t,n,i)=>e.handleConnectionTransportStatus(t,n,i??null),handleConnectionApplicationRouteMissing:(t,n)=>e.handleConnectionApplicationRouteMissing(t,n),initializeConnectionTrust:(t,n)=>{e.initializeConnectionTrust(t,n);},markConnectionTrustVerified:(t,n)=>{e.markConnectionTrustVerified(t,n);},registerConnection:t=>e.registerConnection(t),announceConnectionWhenStable:t=>e.announceConnectionWhenStable(t),sendTransportHandshake:(t,n)=>e.sendTransportHandshake(t,n),requestProtectedWebRTCUpgradeIfInitiator:(t,n)=>e.requestProtectedWebRTCUpgradeIfInitiator(t,n),getConnectionChannelId:t=>e.getConnectionChannelId(t),isWebRTCTransportEnabled:()=>k(e.getOptions()),getLocalDeviceId:()=>e.getLocalDeviceId(),getFallbackLocalDeviceId:()=>e.getDeviceId()||e.getOptions().localDeviceId||null,getConfiguredDeviceName:()=>e.getOptions().deviceName,isNativeRuntime:()=>typeof window<"u"&&typeof window.__TAURI__<"u",isLikelyMobileBrowser:()=>he(),validateIncomingSessionToken:(t,n,i)=>e.validateIncomingSessionToken(t,n,i),applySessionTokenTrustApproval:(t,n,i)=>e.applySessionTokenTrustApproval(t,n,i),rememberPendingSessionTokenTrustApproval:(t,n)=>e.rememberPendingSessionTokenTrustApproval(t,n),markSessionTokenApprovedNode:t=>e.markSessionTokenApprovedNode(t),markSessionTokenApprovedConnection:t=>e.markSessionTokenApprovedConnection(t),clearSessionTokenRejectionCooldown:t=>e.clearSessionTokenRejectionCooldown(t),getSessionTokenRejectionCooldown:t=>e.getSessionTokenRejectionCooldown(t),setSessionTokenRejectionCooldown:(t,n)=>e.setSessionTokenRejectionCooldown(t,n),clearTrustFailureCooldown:t=>{e.clearTrustFailureCooldown(t);},schedulePeerReconciliation:t=>e.schedulePeerReconciliation(t),ensureIncomingConnectionForRemoteNode:t=>r.getController().ensureIncomingConnectionForRemoteNode(t),getReciprocalSessionAdmission:async(t,n,i,o,s)=>{let a=e.getRouteRepairSessionTokenForNode(t),c=e.getRouteRepairSessionTokenPayloadForNode(t);if(!a||!c)throw new Error("pending reciprocal session token is unavailable");let l=await e.getLocalDeviceId().catch(()=>null);if(!l)throw new Error("local device identity is unavailable for reciprocal admission");let p=e.getWasmClient();if(typeof p?.prepare_inline_reciprocal_session_admission!="function")throw new Error("WASM runtime does not support inline reciprocal admission");return await p.prepare_inline_reciprocal_session_admission(t,BigInt(i),o,s,a,c,l,n),{token:a,tokenPayload:c,deviceId:l,streamContract:n}},presentLegacyReciprocalSessionAdmission:async t=>{let n=e.getWasmClient(),i=e.getRouteRepairSessionTokenForNode(t),o=e.getRouteRepairSessionTokenPayloadForNode(t);if(!i||!o)throw new Error("pending reciprocal session token is unavailable");let s=await e.getLocalDeviceId().catch(()=>null);if(typeof n?.present_session_token_to_host_with_payload_and_device_id=="function"){await n.present_session_token_to_host_with_payload_and_device_id(t,i,o,s);return}throw new Error("WASM runtime does not support legacy reciprocal session admission")},confirmReciprocalSessionAdmission:async(t,n,i,o,s,a)=>{let c=e.getWasmClient();return typeof c?.confirm_inline_reciprocal_session_admission!="function"?false:c.confirm_inline_reciprocal_session_admission(t,BigInt(n),i,o,s,a)},disconnectRemoteNode:t=>e.disconnectRemoteNode(t),findManualDisconnectProjectionForNativeNode:t=>e.findManualDisconnectProjectionForNativeNode(t),findLiveConnectionForRemoteNode:t=>e.findLiveConnectionForRemoteNode(t),handleMessage:(t,n)=>e.handleMessage(t,n)},{eventName:Vo,protocolByte:Nt,label:Dt,maxLabelBytes:Mt,maxFrameBytes:Qo,protocolVersion:$o},{trustFailureCooldownMs:Xo,inboundWriterRetryCooldownMs:Zo,pendingHandshakeTtlMs:Yo,pendingHandshakeMaxPerNode:Jo})}function Wr(r){return new Ei({registerDisposer:e=>r.lifecycleScope.register(e),getOptions:()=>r.options,getWasmClient:()=>r.wasmClient,getLocalNodeId:()=>r.localNodeId,getDeviceId:()=>r.deviceId,getDeterministicConnectionId:e=>r.peerIdentity.getDeterministicConnectionId(e),getNativeMainConnectionId:e=>r.peerIdentity.getNativeMainConnectionId(e),getConnection:e=>r.registry.get(e),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),getKnownDevicePlatform:(e,t)=>r.deviceDirectory.getKnownDevicePlatform(e,t),getTrustFailureCooldown:e=>r.connectionTrust.getFailureCooldown(e),getRouteRepairSessionTokenForNode:e=>r.sessionTokens.getRouteRepairTokenForNode(e),getRouteRepairSessionTokenPayloadForNode:e=>r.sessionTokens.getRouteRepairTokenPayloadForNode(e),isSessionTokenApprovedNode:e=>r.sessionTokens.isApprovedNode(e),isSessionTokenApprovedConnection:e=>r.sessionTokens.isApprovedConnection(e),createTransportContext:e=>r.transportContexts.create(e),getApplicationCrypto:()=>r.options?.applicationCrypto,shouldNegotiateApplicationKeyAgreement:()=>r.applicationCrypto.shouldNegotiateKeyAgreement(),handleConnectionTransportStatus:(e,t,n)=>r.transportHealth.handleCurrentConnectionTransportStatus(e,t,n),handleConnectionApplicationRouteMissing:(e,t)=>r.transportUpgrade.handleApplicationRouteMissing(e,t),initializeConnectionTrust:(e,t)=>{r.connectionTrust.initialize(e,t);},markConnectionTrustVerified:(e,t)=>{r.connectionTrust.markVerified(e,t);},registerConnection:e=>r.connectionLifecycle.registerConnection(e),announceConnectionWhenStable:e=>r.connectionLifecycle.announceConnectionWhenStable(e),sendTransportHandshake:(e,t)=>r.transportHandshake.sendTransportHandshake(e,t),requestProtectedWebRTCUpgradeIfInitiator:(e,t)=>r.transportHandshake.requestProtectedWebRTCUpgradeIfInitiator(e,t),getConnectionChannelId:e=>r.connectionChannelPolicy.getConnectionChannelId(e),getLocalDeviceId:()=>r.signalingBackendController.getLocalDeviceId(),validateIncomingSessionToken:(e,t,n)=>r.sessionTokens.validateIncomingSessionTokenWithRetry(e,t,n),applySessionTokenTrustApproval:(e,t,n)=>r.sessionTokens.applyTrustApproval(e,t,n),rememberPendingSessionTokenTrustApproval:(e,t)=>r.sessionTokens.rememberPendingTrustApproval(e,t),markSessionTokenApprovedNode:e=>r.sessionTokens.approveNode(e),markSessionTokenApprovedConnection:e=>r.sessionTokens.approveConnection(e),clearSessionTokenRejectionCooldown:e=>r.sessionTokens.clearRejectionCooldown(e),getSessionTokenRejectionCooldown:e=>r.sessionTokens.getRejectionCooldown(e),setSessionTokenRejectionCooldown:(e,t)=>r.sessionTokens.setRejectionCooldown(e,t),clearTrustFailureCooldown:e=>{r.connectionTrust.clearFailureCooldown(e);},schedulePeerReconciliation:e=>r.peerProjection.schedule(e),disconnectRemoteNode:e=>r.runtimeConnections.disconnectNodeBestEffort(e),findManualDisconnectProjectionForNativeNode:e=>r.peerIdentity.findManualDisconnectProjectionForNativeNode(e),findLiveConnectionForRemoteNode:e=>{let t=r.peerIdentity.getDeterministicConnectionId(e);return r.connectionLifecycle.findLiveConnectionForRemoteNode(e,t)},handleMessage:(e,t)=>r.connectionMessageHandler.handleMessage(e,t)})}var Ei=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getController:()=>this.controller}}get controller(){return this._controller??(this._controller=Br(this.factoryHost))}writeLabelHeaderOnBiStream(e,t){return this.controller.writeLabelHeaderOnBiStream(e,t)}flushPendingHandshakesForNode(e,t){return this.controller.flushPendingHandshakesForNode(e,t)}flushPendingSignalsForNode(e,t){return this.controller.flushPendingSignalsForNode(e,t)}};var mn=class{constructor(e,t){this.peerLifecycle=e;this.deps=t;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}watchPeerStates(e){return this.peerLifecycle.watch(e)}getPeerState(e){return this.peerLifecycle.get(e)}listConnectedPeers(){return this.peerLifecycle.listConnected()}isPeerPromotionEligible(e){return this.deps.resolvePromotionEligibility(e)}addPeerScope(e,t="persistent"){let n=this.deps.getWasmClient();return n&&typeof n.add_peer_scope=="function"?(n.add_peer_scope(e,t).then(()=>{this.disposed||this.deps.scheduleRefreshPeerSnapshot();}).catch(()=>{}),this.peerLifecycle.get(e)):this.peerLifecycle.addScope(e,t)}releasePeerScope(e,t){let n=this.deps.getWasmClient();return n&&typeof n.release_peer_scope=="function"?(n.release_peer_scope(e,t??null).then(()=>{this.disposed||this.deps.scheduleRefreshPeerSnapshot();}).catch(()=>{}),this.peerLifecycle.get(e)):this.peerLifecycle.releaseScope(e,t)}getPeerScopes(e){return this.peerLifecycle.get(e)?.scopes??[]}isSamePeer(e,t){let n=this.peerLifecycle.get(e),i=this.peerLifecycle.get(t);return n&&i?n.peerId===i.peerId:false}clearManualDisconnectProjection(e){let t=this.peerLifecycle.get(e);this.peerLifecycle.dispatch({type:"ManualDisconnectCleared",peerId:t?.peerId??e,deviceId:t?.deviceId??e,deviceIdHint:t?.deviceIdHint,nodeId:t?.nodeId,connectionId:t?.connectionId});}async disconnectPeer(e,t="persistent"){let n=this.peerLifecycle.releaseScope(e,t);n&&n.scopes.length>0||await this.forceDisconnectPeer(e);}async forceDisconnectPeer(e){let t=this.peerLifecycle.releaseScope(e),n=this.getPeerCandidates(t?.peerId||e);if(await Promise.allSettled(Array.from(n).map(async i=>{let o=Array.from(this.deps.getConnections()).filter(a=>{let c=a.id.trim().toLowerCase(),l=a.deviceId.trim().toLowerCase();return i===l||i===c||c.includes(i)});await Promise.allSettled(o.map(a=>a.disconnect()));let s=t?.nodeId||(o[0]?.deviceId??null);s&&i===s.trim().toLowerCase()&&await this.deps.disconnectNode(s).catch(()=>{});})),this.deps.hasRustPeerLifecycleProjection()){if(this.disposed)return;await this.deps.schedulePeerReconciliation("disconnect-node").catch(()=>{});}this.disposed||this.peerLifecycle.dispatch({type:"ManualDisconnect",peerId:t?.peerId??e,deviceId:t?.deviceId,deviceIdHint:t?.deviceIdHint,nodeId:t?.nodeId,connectionId:t?.connectionId});}async getPeerHealth(e){let t=this.peerLifecycle.get(e);return t?t.health:"unknown"}getPeerCandidates(e){let t=this.peerLifecycle.get(e),n=new Set;return [e,t?.peerId,t?.deviceId,t?.nodeId,t?.connectionId,...t?.connectionIds??[]].forEach(o=>{if(!o)return;let s=o.trim().toLowerCase();s&&n.add(s);}),n}};function ke(r){if(!r)return null;let e=r.trim();return e?e.toLowerCase():null}function xi(r){return r.deviceId||r.deviceIdHint||r.peerId||null}function fn(r){return [...r].sort()}function Be(r,e){return r?r.peerId===e.peerId&&(r.deviceId??null)===(e.deviceId??null)&&(r.deviceIdHint??null)===(e.deviceIdHint??null)&&(r.nodeId??null)===(e.nodeId??null)&&(r.connectionId??null)===(e.connectionId??null)&&(r.ticket??null)===(e.ticket??null)&&!!r.online==!!e.online&&(r.deviceName??null)===(e.deviceName??null)&&(r.platformType??null)===(e.platformType??null)&&r.status===e.status&&r.health===e.health&&(r.lifecycleStage??null)===(e.lifecycleStage??null)&&(r.generation??null)===(e.generation??null)&&(r.baseTransportState??null)===(e.baseTransportState??null)&&(r.admissionState??null)===(e.admissionState??null)&&(r.transportState??null)===(e.transportState??null)&&(r.protocolState??null)===(e.protocolState??null)&&(r.webrtcState??null)===(e.webrtcState??null)&&!!r.routable==!!e.routable&&(r.activeTransportStableId??null)===(e.activeTransportStableId??null)&&(r.transportGeneration??null)===(e.transportGeneration??null)&&(r.routeGeneration??null)===(e.routeGeneration??null)&&(r.activeTransport??null)===(e.activeTransport??null)&&(r.fallbackTransport??null)===(e.fallbackTransport??null)&&(r.parallelTransport??null)===(e.parallelTransport??null)&&!!r.manualDisconnect==!!e.manualDisconnect&&(r.lastAuthoritativeEventAt??null)===(e.lastAuthoritativeEventAt??null)&&(r.lastTransientEventAt??null)===(e.lastTransientEventAt??null)&&(r.promotionEligible??true)===(e.promotionEligible??true)&&(r.error??null)===(e.error??null)&&JSON.stringify(fn(r.connectionIds))===JSON.stringify(fn(e.connectionIds))&&JSON.stringify(fn(r.scopes))===JSON.stringify(fn(e.scopes)):false}function We(r){return r==="closed"||r==="disconnected"||r==="failed"}function Or(r){let{status:e,health:t,lifecycleStage:n,generation:i,baseTransportState:o,admissionState:s,transportState:a,protocolState:c,webrtcState:l,routable:p,activeTransportStableId:u,transportGeneration:g,routeGeneration:y,activeTransport:m,fallbackTransport:v,parallelTransport:S,connectionId:I,error:k,...T}=r;return T}function jr(r){if(We(r.status))return "closed";let e=(r.transportState??"").trim().toLowerCase();return e==="connected"||r.connectionId||r.activeTransport?"connected":e==="connecting"||r.status==="connecting"?"connecting":e==="failed"||e==="degraded"?"degraded":"unknown"}function ot(r){return We(r.status)||r.webrtcState!=="ready"||!r.connectionId||r.activeTransportStableId===null||r.activeTransportStableId===void 0||r.health!=="healthy"||r.transportState!=="connected"?false:[r.activeTransport,r.parallelTransport].filter(t=>typeof t=="string").some(f$1)}function Hr(r){return f$1(r)}function Li(r){return We(r.status)?"closed":ot(r)?"ready":r.webrtcState?r.webrtcState:[r.activeTransport,r.parallelTransport].filter(t=>typeof t=="string").some(f$1)?r.transportState==="connected"?"transport-open":"connecting":"unknown"}function La(r){if(r.manualDisconnect||We(r.status))return "closed";let e=Li(r);if(e==="ready")return "webrtc-ready";if(e==="connecting"||e==="transport-open"||e==="route-probing")return "upgrading";if(r.routable===true||r.protocolState==="routable")return "protocol-ready";if(r.admissionState==="admitted")return "admitted";let t=r.baseTransportState??jr(r);return t==="connected"?"base-connected":t==="degraded"||r.health==="suspect"||r.health==="stale"?"degraded":r.status==="connecting"?"dialing":"discovered"}function Fa(r){return We(r.status)?r.status:r.routable===true||r.protocolState==="routable"||ot(r)?"connected":r.status}function Ur(r){return {peerId:r.peerId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,nodeId:r.nodeId??null,connectionId:r.connectionId??null,status:r.status,health:r.health,lifecycleStage:r.lifecycleStage??null,generation:r.generation??null,baseTransportState:r.baseTransportState??null,admissionState:r.admissionState??null,transportState:r.transportState??null,protocolState:r.protocolState??null,webrtcState:r.webrtcState??null,routable:r.routable??null,activeTransportStableId:r.activeTransportStableId??null,transportGeneration:r.transportGeneration??null,routeGeneration:r.routeGeneration??null,activeTransport:r.activeTransport??null,parallelTransport:r.parallelTransport??null,manualDisconnect:r.manualDisconnect??false,scopes:r.scopes,error:r.error??null}}function Ba(r,e,t){let n={event:r,before:e?Ur(e):null,after:Ur(t)};c$1("[OpenRTC][projection]",n);}var yn=class{constructor(){this.peers=new Map;this.aliases=new Map;this.watchers=new Set;this.disposed=false;}resolveCanonicalPeerId(e){let t=[e.deviceId,e.deviceIdHint,e.nodeId,e.peerId,e.connectionId];for(let n of t){let i=ke(n);if(!i)continue;let o=this.aliases.get(i);if(o)return o}return xi(e)}setAlias(e,t){let n=ke(e);n&&this.aliases.set(n,t);}snapshot(e){let t=ot(e),n=e.baseTransportState??jr(e),i=Li(e),o=e.routable,s=e.protocolState;return {peerId:e.peerId,deviceId:e.deviceId,deviceIdHint:e.deviceIdHint,nodeId:e.nodeId,connectionId:e.connectionId,connectionIds:Array.from(e.connectionIds.values()),ticket:e.ticket,online:e.online,deviceName:e.deviceName,platformType:e.platformType,status:Fa(e),health:e.health,lifecycleStage:e.lifecycleStage??La(e),generation:e.generation??e.transportGeneration,baseTransportState:n,admissionState:e.admissionState,transportState:e.transportState,protocolState:s,webrtcState:i,routable:o,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,fallbackTransport:e.fallbackTransport,parallelTransport:e.parallelTransport,manualDisconnect:e.manualDisconnect,lastAuthoritativeEventAt:e.lastAuthoritativeEventAt,lastTransientEventAt:e.lastTransientEventAt,promotionEligible:e.promotionEligible,scopes:Array.from(e.scopes.values()),lastSeenAt:e.lastSeenAt,error:t?void 0:e.error}}emit(){if(this.disposed)return;let e=this.list();this.watchers.forEach(t=>t(e));}rekeyPeer(e,t){let n=this.peers.get(e);if(!n)throw new Error(`Cannot rekey missing peer ${e}`);if(e===t)return n;this.peers.delete(e),n.peerId=t,this.peers.set(t,n);for(let[i,o]of this.aliases.entries())o===e&&this.aliases.set(i,t);return n}upsert(e){let t=e,n=this.resolveCanonicalPeerId(t)??xi(t);if(!n)throw new Error("Peer projection upsert requires a device-keyed identifier.");let i=xi(t)??n,o=this.peers.get(n),s=!!o;o||(o={peerId:n,connectionIds:new Set,status:t.status??"disconnected",health:t.health??"unknown",scopes:new Set},this.peers.set(n,o));let a=s?this.snapshot(o):void 0;if(i!==o.peerId){let E=t.deviceId||o.deviceId||t.deviceIdHint||o.deviceIdHint||t.nodeId||o.nodeId||o.peerId;E&&E!==o.peerId&&(o=this.rekeyPeer(o.peerId,E));}s&&typeof t.transportGeneration=="number"&&typeof o.transportGeneration=="number"&&t.transportGeneration<o.transportGeneration&&t.manualDisconnect!==true&&(t=Or(t)),s&&typeof t.routeGeneration=="number"&&typeof o.routeGeneration=="number"&&(typeof t.transportGeneration!="number"||typeof o.transportGeneration!="number"||t.transportGeneration===o.transportGeneration)&&t.routeGeneration<o.routeGeneration&&t.manualDisconnect!==true&&(t=Or(t)),t.deviceId&&(o.deviceId=t.deviceId),t.deviceIdHint!==void 0&&(o.deviceIdHint=t.deviceIdHint),t.nodeId&&(o.nodeId=t.nodeId);let c={generation:o.generation,lifecycleStage:o.lifecycleStage,protocolState:o.protocolState,webrtcState:o.webrtcState,routable:o.routable,activeTransportStableId:o.activeTransportStableId,transportGeneration:o.transportGeneration,routeGeneration:o.routeGeneration,activeTransport:o.activeTransport,fallbackTransport:o.fallbackTransport,parallelTransport:o.parallelTransport},l=ot(o)||Li(o)==="ready",u=(t.connectionId===void 0||o.connectionId===void 0||t.connectionId===o.connectionId)&&(t.transportGeneration===void 0||o.transportGeneration===void 0||t.transportGeneration===o.transportGeneration)&&(t.activeTransportStableId===void 0||o.activeTransportStableId===void 0||o.activeTransportStableId===null||t.activeTransportStableId===o.activeTransportStableId),g=t.connectionId!==void 0&&o.connectionId!==void 0&&t.connectionId!==o.connectionId||t.transportGeneration!==void 0&&o.transportGeneration!==void 0&&t.transportGeneration>o.transportGeneration||t.activeTransportStableId!==void 0&&t.activeTransportStableId!==null&&o.activeTransportStableId!==void 0&&o.activeTransportStableId!==null&&t.activeTransportStableId!==o.activeTransportStableId,y=t.activeTransport!==void 0||t.parallelTransport!==void 0||t.activeTransportStableId!==void 0||t.transportGeneration!==void 0||t.routeGeneration!==void 0||t.transportState!==void 0,m=Hr(t.activeTransport)||Hr(t.parallelTransport)||t.webrtcState==="ready"||t.webrtcState==="connecting",v=t.webrtcState==="closed"||t.webrtcState==="failed"||t.lifecycleStage==="closed"||t.status==="closed"||t.status==="disconnected"||t.status==="failed"||t.manualDisconnect===true,S=t.routable===true||t.protocolState==="routable",I=l&&u&&y&&S&&!m&&!v;g&&(o.generation=void 0,o.lifecycleStage=void 0,o.webrtcState=void 0,o.fallbackTransport=null,o.parallelTransport=null),t.connectionId&&(o.connectionId=t.connectionId,o.connectionIds.add(t.connectionId)),t.ticket!==void 0&&(o.ticket=t.ticket),t.online!==void 0&&(o.online=t.online),t.deviceName!==void 0&&(o.deviceName=t.deviceName),t.platformType!==void 0&&(o.platformType=t.platformType);let k=s&&(o.manualDisconnect===true||We(o.status)&&typeof o.error=="string"&&o.error.toLowerCase().includes("manual disconnect")),T=t.status==="connected"||t.status==="connecting"||t.routable===true||t.protocolState==="routable"||t.transportState==="connected"||t.activeTransport!==void 0||t.parallelTransport!==void 0;if(k&&T){let E=this.snapshot(o);return Be(a,E)||this.emit(),E}if(T&&(o.lifecycleStage==="closed"&&t.lifecycleStage===void 0&&(o.lifecycleStage=void 0),o.baseTransportState==="closed"&&t.baseTransportState===void 0&&(o.baseTransportState=void 0),o.webrtcState==="closed"&&t.webrtcState===void 0&&(o.webrtcState=void 0),o.transportState==="closed"&&t.transportState===void 0&&(o.transportState=void 0),o.protocolState==="closed"&&t.protocolState===void 0&&(o.protocolState=void 0)),t.status&&(o.status=t.status),t.health&&(o.health=t.health),t.lifecycleStage!==void 0&&(o.lifecycleStage=t.lifecycleStage),t.generation!==void 0&&(o.generation=t.generation),t.baseTransportState!==void 0&&(o.baseTransportState=t.baseTransportState),t.admissionState!==void 0&&(o.admissionState=t.admissionState),t.transportState!==void 0&&(o.transportState=t.transportState),t.protocolState!==void 0&&(o.protocolState=t.protocolState),t.webrtcState!==void 0&&(o.webrtcState=t.webrtcState),t.routable!==void 0&&(o.routable=t.routable),t.activeTransportStableId!==void 0&&(o.activeTransportStableId=t.activeTransportStableId),t.transportGeneration!==void 0&&(o.transportGeneration=t.transportGeneration),t.routeGeneration!==void 0&&(o.routeGeneration=t.routeGeneration),t.activeTransport!==void 0&&(o.activeTransport=t.activeTransport),t.fallbackTransport!==void 0&&(o.fallbackTransport=t.fallbackTransport),t.parallelTransport!==void 0&&(o.parallelTransport=t.parallelTransport),t.manualDisconnect!==void 0&&(o.manualDisconnect=t.manualDisconnect),t.lastAuthoritativeEventAt!==void 0&&(o.lastAuthoritativeEventAt=t.lastAuthoritativeEventAt),t.lastTransientEventAt!==void 0&&(o.lastTransientEventAt=t.lastTransientEventAt),t.promotionEligible!==void 0&&(o.promotionEligible=t.promotionEligible),(t.transportState!==void 0||t.activeTransportStableId!==void 0||t.activeTransport!==void 0||t.parallelTransport!==void 0)&&!S&&!ot(o)&&(o.routable=false,o.protocolState==="routable"&&(o.protocolState=o.transportState==="connected"?"transport-only":o.transportState)),I&&(o.generation=c.generation,o.lifecycleStage=c.lifecycleStage,o.protocolState=c.protocolState,o.webrtcState=c.webrtcState,o.routable=c.routable,o.activeTransportStableId=c.activeTransportStableId,o.transportGeneration=c.transportGeneration,o.routeGeneration=c.routeGeneration,o.activeTransport=c.activeTransport,o.fallbackTransport=c.fallbackTransport,o.parallelTransport=c.parallelTransport),t.clearError?(o.error=void 0,t.manualDisconnect!==true&&(o.manualDisconnect=false)):t.error!==void 0&&(o.error=t.error,t.error.toLowerCase().includes("manual disconnect")&&(o.manualDisconnect=true)),t.lastSeenAt!==void 0&&(o.lastSeenAt=t.lastSeenAt),t.scopes)for(let E of t.scopes)o.scopes.add(E);(o.status==="closed"||o.status==="failed"||o.status==="disconnected")&&(o.routable=false,o.activeTransportStableId=null,o.activeTransport=void 0,o.fallbackTransport=null,o.parallelTransport=null,o.webrtcState="closed",o.baseTransportState="closed",o.lifecycleStage="closed",(!o.transportState||o.transportState==="connected")&&(o.transportState="closed"),(!o.protocolState||o.protocolState==="routable")&&(o.protocolState="closed")),this.setAlias(o.peerId,o.peerId),this.setAlias(o.deviceId,o.peerId),this.setAlias(o.deviceIdHint,o.peerId),this.setAlias(o.nodeId,o.peerId),this.setAlias(o.connectionId,o.peerId);for(let E of o.connectionIds)this.setAlias(E,o.peerId);let _=this.snapshot(o);return Be(a,_)||(Ba(s?"upsert":"create",a??null,_),this.emit()),_}dispatch(e){let t={peerId:e.peerId,deviceId:e.deviceId,deviceIdHint:e.deviceIdHint,nodeId:e.nodeId,connectionId:e.connectionId};switch(e.type){case "ConnectionStateProjected":{let{type:n,...i}=e;return this.upsert(i)}case "ManualDisconnectCleared":return this.upsert({...t,status:"disconnected",health:"unknown",manualDisconnect:false,clearError:true,lastSeenAt:Date.now()});case "RosterDeviceDiscovered":return this.upsert({...t,deviceName:e.deviceName,platformType:e.platformType,ticket:e.ticket,online:e.online??true,scopes:e.scopes,lastSeenAt:e.lastSeenAt??Date.now()});case "PresenceOnline":return this.upsert({...t,online:true,lastSeenAt:e.lastSeenAt??Date.now()});case "PresenceOffline":return this.upsert({...t,online:false});case "DialStarted":return this.get(this.targetLookupId(t))?.status==="connected"?this.get(this.targetLookupId(t)):this.upsert({...t,status:"connecting"});case "BaseTransportConnected":return this.upsert({...t,status:this.get(this.targetLookupId(t))?.status==="connected"?void 0:"connecting",transportState:"connected",baseTransportState:"connected",transportGeneration:e.transportGeneration});case "AdmissionAccepted":return this.upsert({...t,admissionState:"admitted"});case "AdmissionRejected":return this.upsert({...t,admissionState:"rejected",error:e.reason});case "WebRtcNegotiationStarted":return this.upsert({...t,webrtcState:"connecting",generation:e.generation,transportGeneration:e.generation});case "WebRtcFailed":return this.upsert({...t,webrtcState:"failed",transportGeneration:e.transportGeneration});case "ControlPathClosed":return this.upsert({...t,status:"disconnected"});case "HealthObserved":return this.updateHealth(this.targetLookupId(t),e.health);case "ManualDisconnect":return this.upsert({...t,status:"closed",health:"stale",manualDisconnect:true,error:"manual disconnect"});case "ExplicitUnshare":return this.upsert({...t,status:"closed",manualDisconnect:true,error:"explicit unshare"})}}targetLookupId(e){return e.deviceId||e.deviceIdHint||e.peerId||e.nodeId||e.connectionId||""}upsertDevice(e){return this.upsert({deviceId:e.deviceId,nodeId:e.nodeId,ticket:e.ticket,online:e.online,deviceName:e.deviceName,platformType:e.platformType,lastSeenAt:typeof e.updatedAt=="number"?e.updatedAt:typeof e.lastSeenAt=="number"?e.lastSeenAt:Date.now()})}watch(e){return this.disposed?()=>{}:(this.watchers.add(e),e(this.list()),()=>{this.watchers.delete(e);})}dispose(){this.disposed=true,this.watchers.clear();}get(e){let t=ke(e),n=t?this.aliases.get(t):void 0,i=n&&this.peers.get(n)||this.peers.get(e);return i?this.snapshot(i):void 0}list(){return Array.from(this.peers.values()).map(e=>this.snapshot(e)).sort((e,t)=>{let n=e.lastSeenAt??0,i=t.lastSeenAt??0;return n!==i?i-n:e.peerId.localeCompare(t.peerId)})}listConnected(){return this.list().filter(e=>e.status==="connected")}addScope(e,t="persistent"){let n=this.resolveRecord(e);if(!n)return;let i=this.snapshot(n);n.scopes.add(t);let o=this.snapshot(n);return Be(i,o)||this.emit(),o}releaseScope(e,t){let n=this.resolveRecord(e);if(!n)return;let i=this.snapshot(n);t?n.scopes.delete(t):n.scopes.clear();let o=this.snapshot(n);return Be(i,o)||this.emit(),o}hasScopes(e){return (this.resolveRecord(e)?.scopes.size??0)>0}removeConnection(e){let t=this.resolveRecord(e);if(!t)return;let n=this.snapshot(t),i=ke(e);if(i){let s=Array.from(t.connectionIds).find(a=>ke(a)===i);s&&t.connectionIds.delete(s);}t.connectionId&&ke(t.connectionId)===i&&(t.connectionId=Array.from(t.connectionIds)[0]),t.connectionIds.size===0&&t.status==="connected"&&(t.status="closed",t.routable=false,t.transportState="closed",t.protocolState="closed");let o=this.snapshot(t);return Be(n,o)||this.emit(),o}updateHealth(e,t,n){let i=this.resolveRecord(e);if(!i)return;let o=this.snapshot(i);i.health=t,n&&(i.status=n),i.lastSeenAt=Date.now();let s=this.snapshot(i);return Be(o,s)||this.emit(),s}resolveRecord(e){let t=ke(e),n=t?this.aliases.get(t):void 0;return n&&this.peers.get(n)||this.peers.get(e)}};function Fi(r){return r.webRtcDataPlaneLive&&!r.routeReady?{activeTransport:r.parallelTransport??"iroh-relay",fallbackTransport:"webrtc",parallelTransport:"webrtc"}:{activeTransport:r.activeTransport??void 0,fallbackTransport:r.parallelTransport??null,parallelTransport:r.parallelTransport??null}}function Gr(r){return r.settledReady?"routable":r.hasActiveConnection?"transport-only":r.rustStatusIsConnecting?"connecting":"closed"}function qr(r){return r.hasActiveConnection?"connected":r.rustStatusIsConnecting?"connecting":r.mappedStatusIsTerminal?"closed":"unknown"}function Kr(r){return r.routeReady?"ready":r.webRtcDataPlaneLive?"route-probing":r.anyWebRtcTransportLabel?"connecting":"unknown"}function zr(r){return r.terminal?"closed":r.activeIsWebRtc?r.routeReady?"ready":"route-probing":r.parallelIsWebRtc?"route-probing":"unknown"}function Wa(r,e){let t=b$1(r)??"",n=[r,e].map(b$1).filter(i=>!!i);return {activeTransportLabel:t,labels:n}}function vn(r){let{activeTransportLabel:e,labels:t}=Wa(r.activeTransport,r.parallelTransport),n=t.some(f$1);return {webRtcDataPlaneLive:r.source==="rust-session"?!!r.activeConnectionId&&r.activeTransportStableId!==null&&r.activeTransportStableId!==void 0&&(r.sessionStatusNormalized==="connected"||r.sessionStatusNormalized==="connecting")&&r.mappedHealth==="healthy"&&f$1(e):f$1(r.activeTransport),routeReady:r.routeReady,anyWebRtcTransportLabel:n}}function Oa(r){if(r.isClosed)return "closed";let e=r.getUpgradeState();return e==="upgraded"?"webrtc":e==="upgrading"?"webrtc-upgrading":e==="failed"?"iroh-fallback":"connected"}function Qr(r){let{connection:e,trustProjection:t,existingProjection:n,terminalTransportClose:i}=r;if(i){let c=n?.peerId??r.peerId??r.deviceId??r.deviceIdHint??e.id;return !c&&!r.deviceId&&!r.deviceIdHint?null:{event:{type:"ConnectionStateProjected",peerId:c,deviceId:n?.deviceId??r.deviceId,deviceIdHint:n?.deviceIdHint??r.deviceIdHint,nodeId:n?.nodeId??e.deviceId,connectionId:e.id,status:"closed",health:"stale",baseTransportState:"closed",transportState:"closed",protocolState:"closed",routable:false,promotionEligible:r.promotionEligible,lastSeenAt:Date.now()}}}if(t)return {event:{type:"ConnectionStateProjected",peerId:t.deviceId??e.remoteNodeId??e.id,deviceId:t.deviceId??void 0,deviceIdHint:t.deviceId??e.remoteNodeId??void 0,nodeId:e.remoteNodeId||e.deviceId,connectionId:e.id,status:e.isClosed?"closed":"connected",health:t.health,transportState:Oa(e),activeTransport:e.getTransportStatus().activeTransport,protocolState:t.protocolState,routable:t.routable,promotionEligible:r.promotionEligible,error:t.error,lastSeenAt:Date.now()}};if(r.peerId||r.deviceId)return {event:{type:"ConnectionStateProjected",peerId:r.peerId??r.deviceId??e.remoteNodeId??e.id,deviceId:r.deviceId,nodeId:e.deviceId,connectionId:e.id,ticket:r.ticket,status:e.isClosed?"closed":"connected",health:"healthy",activeTransport:e.getTransportStatus().activeTransport,promotionEligible:r.promotionEligible,scopes:r.scopes,lastSeenAt:Date.now()}};let o=n?.peerId||n?.deviceId||n?.deviceIdHint,s=n?.deviceId,a=n?.deviceIdHint;return !o&&!s&&!a?null:{event:{type:"ConnectionStateProjected",peerId:o,deviceId:s,deviceIdHint:a,nodeId:e.deviceId,connectionId:e.id,status:e.isClosed?"closed":"connected",health:e.isClosed?"stale":"healthy",activeTransport:e.getTransportStatus().activeTransport,promotionEligible:r.promotionEligible,lastSeenAt:Date.now()}}}function $r(r,e){let t=r.activeConnectionId||r.candidateConnectionIds?.[0]||void 0,n=e.mapRustPeerStatus(r.status),i=String(n).trim().toLowerCase(),o=typeof r.readinessState=="string"&&r.readinessState.trim().length>0,s=e.mapRustPeerHealth(r.health),a=e.localTerminalClosed===true&&!!t,c=vn({source:"rust-session",activeConnectionId:t,activeTransportStableId:r.activeTransportStableId,sessionStatusNormalized:i,mappedHealth:s,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport,routeReady:e.webRtcApplicationRouteReady}),l=o?r.readinessState==="routable":!!r.settledReady,p=l&&!e.applicationRouteFailed,u=a?p:e.trustProjection?e.trustProjection.routable&&l&&!e.applicationRouteFailed:l&&!e.applicationRouteFailed,g=r.status==="connecting",y=Gr({settledReady:u,hasActiveConnection:!!t,rustStatusIsConnecting:g}),m=c.webRtcDataPlaneLive&&!c.routeReady,v=u&&!m,S=m&&y==="routable"?"transport-only":y,I=Fi({webRtcDataPlaneLive:c.webRtcDataPlaneLive,routeReady:c.routeReady,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport});return {event:{type:"ConnectionStateProjected",peerId:r.peerId??e.transientPeerId??e.anonymousSpacePeerId,deviceId:e.trustProjection?.deviceId??r.deviceId??void 0,deviceIdHint:r.deviceIdHint,nodeId:r.nodeId,connectionId:t,status:a&&!p?"closed":e.applicationRouteFailed?"failed":v?"connected":n,health:a&&!p||e.applicationRouteFailed?"stale":e.trustProjection?.health??s,generation:r.transportGeneration,baseTransportState:a&&!p?"closed":qr({hasActiveConnection:!!t,rustStatusIsConnecting:g,mappedStatusIsTerminal:n==="closed"||n==="failed"||n==="disconnected"}),admissionState:a&&!p?"unknown":u||t?"admitted":"unknown",transportState:a&&!p?"closed":t?"connected":r.status==="connecting"?"connecting":"closed",protocolState:a&&!p?"closed":S,routable:v,activeTransportStableId:a&&!p?void 0:r.activeTransportStableId??void 0,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,activeTransport:a&&!p?void 0:I.activeTransport,fallbackTransport:a&&!p?void 0:I.fallbackTransport,parallelTransport:a&&!p?void 0:I.parallelTransport,webrtcState:a&&!p?"closed":Kr({routeReady:c.routeReady,webRtcDataPlaneLive:c.webRtcDataPlaneLive,anyWebRtcTransportLabel:c.anyWebRtcTransportLabel}),promotionEligible:e.promotionEligible,scopes:e.sessionScopes,error:a&&!p?"local-transport-closed":e.applicationRouteFailed?"application-route-timeout":e.trustProjection?.error??(v?void 0:r.error??void 0),clearError:v,lastSeenAt:r.lastSeenAtMs},clearApplicationRouteFailure:p&&v&&t?t:void 0}}function Ha(r){return !(!r.projectedDeviceId&&!r.projectedDeviceIdHint&&!r.existingProjection&&!r.anonymousTerminalProjectionAllowed&&!r.localTerminalClosed)}function Vr(r,e){if(!Ha(e))return null;let t=e.localTerminalClosed===true,n=vn({source:"backend-state",activeTransport:r.activeTransport,parallelTransport:r.parallelTransport,routeReady:e.webRtcApplicationRouteReady}),i=e.liveConnection?e.applicationRouteReady:r.routable===true&&(!n.webRtcDataPlaneLive||n.routeReady),o=r.routable===true&&i&&!e.terminalState,s=t&&!o,a=e.terminalState||s,c=a?false:e.trustProjection?e.trustProjection.routable:r.routable,l=c&&i,p=s?"closed":e.terminalState?r.protocolState??"closed":l?"routable":r.transportState==="connected"?"transport-only":e.trustProjection?.protocolState??r.protocolState,u=a?s?"local-transport-closed":r.error??r.lastDisconnectReason??e.trustProjection?.error:e.trustProjection?.error??r.error,g=a?"stale":e.trustProjection?.health??(l||r.transportState==="connected"?"healthy":r.state==="failed"||r.state==="closed"?"stale":"unknown"),y=Fi({webRtcDataPlaneLive:n.webRtcDataPlaneLive,routeReady:n.routeReady,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport});return {event:{type:"ConnectionStateProjected",peerId:e.existingProjection?.peerId??(e.anonymousTerminalProjectionAllowed?r.remoteNodeId??r.connectionId:void 0),deviceId:e.projectedDeviceId,deviceIdHint:e.projectedDeviceIdHint,nodeId:r.remoteNodeId??e.existingProjection?.nodeId??void 0,connectionId:r.connectionId,status:s?"closed":r.state==="connected"?"connected":r.state==="connecting"||r.state==="new"?"connecting":r.state==="failed"?"failed":r.state==="closed"?"closed":"disconnected",health:g,generation:r.transportGeneration,baseTransportState:a?"closed":r.transportState==="connected"?"connected":r.transportState==="connecting"||r.state==="connecting"||r.state==="new"?"connecting":r.transportState==="failed"?"degraded":"unknown",admissionState:c||r.readinessState==="routable"?"admitted":a?"unknown":"pending",transportState:s?"closed":r.transportState,protocolState:p,webrtcState:zr({terminal:a,activeIsWebRtc:n.webRtcDataPlaneLive,routeReady:n.routeReady,parallelIsWebRtc:f$1(r.parallelTransport)}),routable:l,activeTransportStableId:s?void 0:r.activeTransportStableId??void 0,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,activeTransport:s?void 0:y.activeTransport,fallbackTransport:s?void 0:y.fallbackTransport,parallelTransport:s?void 0:y.parallelTransport,error:u,lastAuthoritativeEventAt:r.updatedAt??Date.now(),lastSeenAt:r.updatedAt??Date.now()}}}function Yr(r,e,t){let n=Ua(e,{status:r.status,health:r.health,routable:r.routable,protocolState:r.protocolState},t);return n?{...r,...n}:r}function Ua(r,e,t){if(!r||r.isClosed)return null;let{activeTransport:n,parallelTransport:i}=r.getTransportStatus(),o=f$1(n)||f$1(i);if(!o||!r.getWebRTCTransport()||e.status==="closed"||e.status==="failed"||e.status==="disconnected")return null;let c=t.applicationRouteReady&&(e.routable===true||e.protocolState==="routable"),l=t.webRtcApplicationRouteReady;return {status:e.status==="connected"||c?"connected":e.status,health:e.health==="stale"?"healthy":e.health,baseTransportState:"connected",transportState:"connected",protocolState:c?"routable":o&&!l?"transport-only":e.protocolState,webrtcState:l?"ready":"route-probing",routable:c,activeTransport:l?n:"iroh-relay",fallbackTransport:i,parallelTransport:l?i:"webrtc",clearError:c&&l,lastTransientEventAt:Date.now()}}var Bi=2e3,Wi=3e3,Cn=class{constructor(e=Bi,t=Wi){this.tsGraceMs=e;this.rustGraceMs=t;this.tsOrphanSince=new Map;this.rustOrphanSince=new Map;this.reportedRustOrphans=new Set;}evaluateTsOrphans(e,t){let n=new Set(e);for(let o of [...this.tsOrphanSince.keys()])n.has(o)||this.tsOrphanSince.delete(o);for(let o of n)this.tsOrphanSince.has(o)||this.tsOrphanSince.set(o,t);let i=[];for(let o of n){let s=this.tsOrphanSince.get(o);s!==void 0&&t-s>=this.tsGraceMs&&i.push(o);}return {toDisconnect:i}}evaluateRustOrphans(e,t){let n=new Set(e);for(let o of [...this.rustOrphanSince.keys()])n.has(o)||(this.rustOrphanSince.delete(o),this.reportedRustOrphans.delete(o));for(let o of n)this.rustOrphanSince.has(o)||this.rustOrphanSince.set(o,t);let i=[];for(let o of n){let s=this.rustOrphanSince.get(o);s!==void 0&&t-s>=this.rustGraceMs&&!this.reportedRustOrphans.has(o)&&(this.reportedRustOrphans.add(o),i.push(o));}return {toReport:i}}clear(){this.tsOrphanSince.clear(),this.rustOrphanSince.clear(),this.reportedRustOrphans.clear();}};function Jr(r){let e=String(r??"").trim().toLowerCase();return e==="connected"||e==="connecting"||e==="new"}function ja(r){let e=String(r.state??"").trim().toLowerCase();return e==="connected"||e==="connecting"||e==="new"}function Oi(r){return r.activeConnectionId||r.candidateConnectionIds?.[0]||void 0}function Ga(r,e,t){return e.some(i=>Oi(i)===r&&Jr(i.status))?true:t.some(i=>i.connectionId===r&&ja(i))}function qa(r,e){return r.routable===true&&(r.connectionId===e||r.connectionIds.includes(e))}function Ka(r){let e=[],t=[];if(r.hasRustProjection)for(let[n,i]of r.connections)i.isClosed||Ga(n,r.rustSessions,r.backendStates)||e.push(n);for(let n of r.rustSessions){let i=Oi(n);if(!i||!Jr(n.status)||!(n.settledReady===true||n.readinessState==="routable"||r.peerStates.some(a=>qa(a,i))))continue;let s=r.connections.get(i);(!s||s.isClosed)&&t.push(i);}return {orphanTsConnectionIds:e,orphanRustRecordConnectionIds:t}}function za(r,e,t,n=Date.now()){if(!r.hasRustPeerLifecycleProjection())return t.clear(),{reportedDrift:{orphanTsConnectionIds:[],orphanRustRecordConnectionIds:[]},closedTsConnectionIds:[]};t.evaluateTsOrphans(e.orphanTsConnectionIds,n);let{toReport:i}=t.evaluateRustOrphans(e.orphanRustRecordConnectionIds,n);return {reportedDrift:{orphanTsConnectionIds:e.orphanTsConnectionIds,orphanRustRecordConnectionIds:i},closedTsConnectionIds:[]}}var bn=class{constructor(e){this.run=e;this.inFlight=null;this.queuedReason=null;this.disposed=false;this.stats={scheduled:0,coalesced:0,ran:0,orphanTsConnection:0,orphanRustRecord:0,orphanTsConnectionHealed:0};}getStats(){return this.stats}dispose(){this.disposed=true,this.queuedReason=null;}recordDrift(e){e.orphanTsConnectionIds.length>0&&(this.stats.orphanTsConnection+=e.orphanTsConnectionIds.length,b$2("[Client][PEER-RECONCILE] orphan_ts_connection",{count:e.orphanTsConnectionIds.length,connectionIds:e.orphanTsConnectionIds})),e.orphanRustRecordConnectionIds.length>0&&(this.stats.orphanRustRecord+=e.orphanRustRecordConnectionIds.length,b$2("[Client][PEER-RECONCILE] orphan_rust_record",{count:e.orphanRustRecordConnectionIds.length,connectionIds:e.orphanRustRecordConnectionIds}));}recordSelfHeal(e){e.closedTsConnectionIds.length>0&&(this.stats.orphanTsConnectionHealed+=e.closedTsConnectionIds.length,b$2("[Client][PEER-RECONCILE] orphan_ts_connection_healed",{count:e.closedTsConnectionIds.length,connectionIds:e.closedTsConnectionIds})),this.recordDrift(e.reportedDrift);}schedule(e){return this.disposed?Promise.resolve([]):(this.stats.scheduled+=1,this.inFlight?(this.stats.coalesced+=1,this.queuedReason=e,b$2("[Client][PEER-RECONCILE] coalesced",{reason:e}),this.inFlight):(b$2("[Client][PEER-RECONCILE] started",{reason:e}),this.inFlight=this.executeRun(e),this.inFlight))}async executeRun(e){let t=e;try{for(;;){this.stats.ran+=1;let n=await this.run(t);b$2("[Client][PEER-RECONCILE] finished",{reason:t,stats:this.getStats()});let i=this.queuedReason;if(this.queuedReason=null,this.disposed)return [];if(!i)return n;t=i,b$2("[Client][PEER-RECONCILE] rerun",{reason:t});}}finally{this.inFlight=null;}}};async function Xr(r,e){let t=r.hasRustPeerLifecycleProjection(),n=false,i=[];if(r.wasmClient&&typeof r.wasmClient.peer_sessions=="function"){let p=await r.wasmClient.peer_sessions();if(Array.isArray(p)){i=p;for(let u of p){let g=Oi(u);if(!r.hasResolvablePeerIdentity({deviceId:u.deviceId,deviceIdHint:u.deviceIdHint,nodeId:u.nodeId,connectionId:g})){b$2("[Client][PEER-SNAPSHOT] skipping rust session without identity",{status:u.status,health:u.health,settledReady:u.settledReady});continue}r.applyComposedRustSession(u),n=true;}}}(await r.searchDevices().catch(()=>[])).forEach(p=>{if(!r.hasResolvablePeerIdentity({deviceId:p.deviceId??null,nodeId:p.nodeId??null})){b$2("[Client][PEER-SNAPSHOT] skipping device projection without identity",{deviceName:p.deviceName??null,online:p.online??null});return}r.peerLifecycle.upsertDevice(p);}),t||r.connections.forEach(p=>{r.syncConnectionPeerLifecycle(p);});let s=await r.signaling.getConnectionStates().catch(()=>[]);s.forEach(p=>{r.applyBackendConnectionState(p);});let a=r.peerLifecycle.list(),c=Ka({hasRustProjection:t,connections:r.connections,rustSessions:i,backendStates:s,peerStates:a}),l=r.getOrphanDriftTracker?.();if(l){let p=za(r,c,l);r.recordReconciliationSelfHeal?.(p);}else r.recordReconciliationDrift?.(c);return t&&!n&&s.length===0,a}function Hi(r,e){return r&&typeof r.supportsRustPeerLifecycleProjection=="function"&&r.supportsRustPeerLifecycleProjection()?true:!!(e&&typeof e.peer_sessions=="function")}var Sn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.orphanDriftTracker=new Cn(t.orphanReconciliationGrace?.tsConnectionMs??Bi,t.orphanReconciliationGrace?.rustRecordMs??Wi),this.scheduler=new bn(n=>Xr(this.asReconciliationHost())),this.ctx.registerDisposer(()=>this.dispose());}schedule(e){return this.scheduler.schedule(e)}dispose(){this.disposed=true,this.scheduler.dispose(),this.orphanDriftTracker.clear();}getStats(){return this.scheduler.getStats()}hasRustPeerLifecycleProjection(){return Hi(this.deps.getSignaling(),this.getPeerSessionReader())}dispatchLiveConnectionProjection(e,t){if(this.disposed)return;let n=Qr({connection:e,...t});n&&this.dispatchComposedConnectionState(n.event,e,{applicationRouteReady:t.applicationRouteReady,webRtcApplicationRouteReady:t.webRtcApplicationRouteReady});}applyConnectionTrustProjection(e){if(this.disposed||this.hasRustPeerLifecycleProjection())return;let t=this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId}),n=this.deps.getConnectionTrustProjection({connectionId:e.id,nodeId:e.remoteNodeId}),i=this.deps.hasApplicationRouteForConnection(e),o=this.deps.isWebRtcApplicationRouteReadyForConnection(e);if(!n){this.syncConnectionPeerLifecycle(e);return}this.dispatchLiveConnectionProjection(e,{trustProjection:n,promotionEligible:t,applicationRouteReady:i,webRtcApplicationRouteReady:o});}applyBackendConnectionState(e){if(this.disposed||!e?.connectionId)return;let t=this.deps.getConnectionTrustProjection({connectionId:e.connectionId,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.remoteNodeId??void 0}),n=this.getPeerState(e.connectionId)??(e.remoteNodeId?this.getPeerState(e.remoteNodeId):void 0),i=e.deviceId??t?.deviceId??n?.deviceId??void 0,o=e.deviceIdHint??n?.deviceIdHint??void 0,s=e.state==="closed"||e.state==="failed"||e.state==="disconnected",a=this.deps.hasLocalTerminalConnectionClose(e.connectionId),c=(s||a)&&!!(e.connectionId||e.remoteNodeId);if(!i&&!o&&!n&&!c)return;b$2("[Client] applyBackendConnectionState",{connectionId:e.connectionId,deviceId:i??null,deviceIdHint:o??null,remoteNodeId:e.remoteNodeId??null,state:e.state,transportState:e.transportState??null,protocolState:e.protocolState??null,routable:e.routable??null,updatedAt:e.updatedAt??null,error:e.error??null,mappedPeerId:n?.peerId??null});let l=this.ctx.registry.get(e.connectionId)??(e.remoteNodeId?this.deps.getConnectionForPeer(void 0,e.remoteNodeId):null),p=this.deps.hasApplicationRouteForConnection(l),u=this.deps.isWebRtcApplicationRouteReadyForConnection(l),g=Vr(e,{trustProjection:t,existingProjection:n,liveConnection:l,applicationRouteReady:p,webRtcApplicationRouteReady:u,terminalState:s,localTerminalClosed:a,anonymousTerminalProjectionAllowed:c,projectedDeviceId:i,projectedDeviceIdHint:o});g&&this.dispatchComposedConnectionState(g.event,l,{applicationRouteReady:p,webRtcApplicationRouteReady:u});}applyComposedRustSession(e){if(this.disposed)return;let t=e.activeConnectionId||e.candidateConnectionIds?.[0],n=this.deps.hasLocalTerminalConnectionClose(t),i=e.scopes??[],o=!!e.nodeId&&this.deps.sessionTokenApprovedNodes().has(e.nodeId)||!!t&&this.deps.sessionTokenApprovedConnectionIds().has(t),s=!e.peerId&&!e.deviceId&&!e.deviceIdHint&&o?`session-token:${i[0]??"unscoped"}:${e.nodeId??t}`:void 0,a=!e.peerId&&!e.deviceId&&!e.deviceIdHint&&this.ctx.discoveryMode==="space"?e.nodeId??t:void 0,c=this.deps.resolvePromotionEligibility({connectionId:t||void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}),l=this.deps.getConnectionTrustProjection({connectionId:t||void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}),p=this.deps.getConnectionForPeer(t||void 0,e.nodeId??void 0),u=this.deps.hasApplicationRouteForConnection(p),g=!!t&&!u&&this.deps.hasApplicationRouteFailure(t),y=String(this.mapRustPeerStatus(e.status)).trim().toLowerCase(),v=vn({source:"rust-session",activeConnectionId:t,activeTransportStableId:e.activeTransportStableId,sessionStatusNormalized:y,mappedHealth:this.mapRustPeerHealth(e.health),activeTransport:e.activeTransport,parallelTransport:e.parallelTransport,routeReady:false}).webRtcDataPlaneLive&&this.deps.isWebRtcApplicationRouteReadyForConnection(p),S=$r(e,{trustProjection:l,promotionEligible:c,liveConnection:p,applicationRouteReady:u,webRtcApplicationRouteReady:v,applicationRouteFailed:g,localTerminalClosed:n,mapRustPeerStatus:I=>this.mapRustPeerStatus(I),mapRustPeerHealth:I=>this.mapRustPeerHealth(I),peerId:e.peerId,transientPeerId:s,anonymousSpacePeerId:a,sessionScopes:i});S.clearApplicationRouteFailure&&this.deps.clearApplicationRouteFailure(S.clearApplicationRouteFailure),this.dispatchComposedConnectionState(S.event,p,{applicationRouteReady:u,webRtcApplicationRouteReady:v});}syncConnectionPeerLifecycle(e){if(this.disposed)return;let t=this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId}),n=this.getPeerState(e.id)||this.listPeerStates().find(i=>i.connectionIds.includes(e.id)||i.nodeId===e.deviceId);this.dispatchLiveConnectionProjection(e,{trustProjection:null,promotionEligible:t,existingProjection:n,applicationRouteReady:this.deps.hasApplicationRouteForConnection(e),webRtcApplicationRouteReady:this.deps.isWebRtcApplicationRouteReadyForConnection(e)});}mapRustPeerStatus(e){switch((e||"").toLowerCase()){case "connected":return "connected";case "connecting":case "pending":return "connecting";case "failed":return "failed";case "closing":case "closed":return "closed";default:return "disconnected"}}mapRustPeerHealth(e){switch((e||"").toLowerCase()){case "healthy":return "healthy";case "suspect":return "suspect";case "stale":return "stale";default:return "unknown"}}asReconciliationHost(){return {hasRustPeerLifecycleProjection:()=>this.hasRustPeerLifecycleProjection(),wasmClient:this.getPeerSessionReader(),signaling:this.deps.getSignaling(),peerLifecycle:this.deps.peerLifecycle,connections:this.ctx.registry,discoveryMode:this.ctx.discoveryMode,sessionTokenApprovedNodes:this.deps.sessionTokenApprovedNodes(),sessionTokenApprovedConnectionIds:this.deps.sessionTokenApprovedConnectionIds(),hasResolvablePeerIdentity:e=>this.hasResolvablePeerIdentity(e),applyComposedRustSession:e=>this.applyComposedRustSession(e),applyBackendConnectionState:e=>this.applyBackendConnectionState(e),searchDevices:()=>this.deps.searchDevices(),syncConnectionPeerLifecycle:e=>this.syncConnectionPeerLifecycle(e),getOrphanDriftTracker:()=>this.orphanDriftTracker,recordReconciliationSelfHeal:e=>this.scheduler.recordSelfHeal(e),recordReconciliationDrift:e=>this.scheduler.recordDrift(e)}}getPeerSessionReader(){return this.ctx.wasmClient&&typeof this.ctx.wasmClient=="object"?this.ctx.wasmClient:null}hasResolvablePeerIdentity(e){if(e.deviceId||e.deviceIdHint)return true;let t=[e.nodeId,e.connectionId].map(o=>typeof o=="string"?o.trim():"").filter(o=>o.length>0);if(this.ctx.discoveryMode==="space"&&t.length>0)return true;let n=this.deps.sessionTokenApprovedNodes(),i=this.deps.sessionTokenApprovedConnectionIds();return t.some(o=>!!this.getPeerState(o)||n.has(o)||i.has(o))}dispatchComposedConnectionState(e,t,n){let i=Yr(e,t,n);this.deps.peerLifecycle.dispatch(i);}getPeerState(e){let t=this.deps.peerLifecycle;return typeof t.get=="function"?t.get(e):void 0}listPeerStates(){let e=this.deps.peerLifecycle;return typeof e.list=="function"?e.list():[]}};function Zr(r){return new Ui({getContext:()=>r.getClientContext(),getWasmClient:()=>r.wasmClient,getSignaling:()=>r.signaling,getConnections:()=>r.registry.values(),disconnectNode:e=>r.runtimeConnections.disconnectNode(e),registerDisposer:e=>r.lifecycleScope.register(e),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),getOrphanReconciliationGrace:()=>r.options?.orphanReconciliationGrace,getSessionTokenApprovedNodes:()=>r.sessionTokens.getApprovedNodes(),getSessionTokenApprovedConnectionIds:()=>r.sessionTokens.getApprovedConnectionIds(),resolvePromotionEligibility:e=>r.connectionChannelPolicy.resolvePromotionEligibility(e),getConnectionTrustProjection:e=>r.connectionTrust.getProjection(e),getConnectionForPeer:(e,t)=>r.registry.getForPeer(e??void 0,t??void 0),hasApplicationRouteForConnection:e=>r.transportServices.hasApplicationRouteForConnectionSnapshot(e,e?.id,e?.remoteNodeId),isWebRtcApplicationRouteReadyForConnection:e=>r.transportServices.isWebRtcApplicationRouteReadyForConnectionSnapshot(e),hasLocalTerminalConnectionClose:e=>r.registry.hasLocalTerminalClose(e),hasApplicationRouteFailure:e=>r.transportServices.hasApplicationRouteFailure(e),clearApplicationRouteFailure:e=>r.transportServices.clearApplicationRouteFailure(e),searchDevices:()=>r.deviceDirectory.searchDevices(),healOrphanTsConnection:e=>r.connectionLifecycle.healOrphanTsConnection(e)})}var Ui=class{constructor(e){this.host=e;this.store=new yn;this.host.registerDisposer(()=>{this.store.dispose();});}get projection(){return this._projection||(this._projection=new Sn(this.host.getContext(),{orphanReconciliationGrace:this.host.getOrphanReconciliationGrace(),sessionTokenApprovedNodes:()=>this.host.getSessionTokenApprovedNodes(),sessionTokenApprovedConnectionIds:()=>this.host.getSessionTokenApprovedConnectionIds(),resolvePromotionEligibility:e=>this.host.resolvePromotionEligibility(e),getConnectionTrustProjection:e=>this.host.getConnectionTrustProjection(e),getConnectionForPeer:(e,t)=>this.host.getConnectionForPeer(e,t),hasApplicationRouteForConnection:e=>this.host.hasApplicationRouteForConnection(e),isWebRtcApplicationRouteReadyForConnection:e=>this.host.isWebRtcApplicationRouteReadyForConnection(e),hasLocalTerminalConnectionClose:e=>this.host.hasLocalTerminalConnectionClose(e),hasApplicationRouteFailure:e=>this.host.hasApplicationRouteFailure(e),clearApplicationRouteFailure:e=>this.host.clearApplicationRouteFailure(e),searchDevices:()=>this.host.searchDevices(),healOrphanTsConnection:e=>this.host.healOrphanTsConnection(e),getSignaling:()=>this.host.getSignaling(),peerLifecycle:this.store})),this._projection}get client(){return this._client||(this._client=new mn(this.store,{getWasmClient:()=>this.host.getWasmClient(),getConnections:()=>this.host.getConnections(),disconnectNode:e=>this.host.disconnectNode(e),hasRustPeerLifecycleProjection:()=>this.host.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:e=>this.projection.schedule(e),scheduleRefreshPeerSnapshot:()=>this.projection.schedule("peer-lifecycle-client").then(()=>{}),registerDisposer:e=>this.host.registerDisposer(e),resolvePromotionEligibility:e=>this.host.resolvePromotionEligibility(e)})),this._client}getProjectionStats(){return this._projection?.getStats()}watchPeerStates(e){return this.store.watch?.(e)??(()=>{})}getPeerState(e){return this.store.get?.(e)}listConnectedPeers(){return this.store.listConnected?.()??[]}listPeerStates(){return this.store.list?.()??[]}getPeerScopes(e){return this.getPeerState(e)?.scopes??[]}getPeerStatus(e){return this.getPeerState(e)?.status}hasPeerScopes(e){return this.store.hasScopes?.(e)??this.getPeerScopes(e).length>0}isSamePeer(e,t){let n=this.getPeerState(e),i=this.getPeerState(t);return !!n&&!!i&&n.peerId===i.peerId}getPeerHealth(e){return this.getPeerState(e)?.health??"unknown"}isPeerPromotionEligible(e){return this.client.isPeerPromotionEligible(e)}addPeerScope(e,t="persistent"){return this.client.addPeerScope(e,t)}releasePeerScope(e,t){return this.client.releasePeerScope(e,t)}clearManualDisconnectProjection(e){this.client.clearManualDisconnectProjection(e);}disconnectPeer(e,t="persistent"){return this.client.disconnectPeer(e,t)}forceDisconnectPeer(e){return this.client.forceDisconnectPeer(e)}applyDiscoveredDevice(e){this.store.upsertDevice?.(e);}};function Qa(r){return qo({get wasmClient(){return r.getWasmClient()},get roomCreationMode(){return r.getRoomCreationMode()},get appLimits(){return r.getAppLimits()},ensureAuthenticated:e=>r.ensureAuthenticated(e),getTicketWithToken:(e,t)=>r.getTicketWithToken(e,t),getNodeId:()=>r.getNodeId(),connect:(e,t)=>r.connect(e,t),refreshHostedAppSettings:e=>r.refreshHostedAppSettings(e),usesDirectRoomBackend:()=>r.usesDirectRoomBackend(),getRoomBackendTag:()=>r.getRoomBackendTag()})}function es(r){return Qa({getWasmClient:()=>r.wasmClient,getRoomCreationMode:()=>r.getRoomCreationMode(),getAppLimits:()=>r.getAppLimits(),ensureAuthenticated:e=>r.auth.ensureAuthenticated(e),getTicketWithToken:(e,t)=>r.sessionTokens.getEndpointTicketWithToken(e,t),getNodeId:()=>r.runtimeIdentity.getNodeId(),connect:(e,t)=>r.connectionDialer.connect(e,t),refreshHostedAppSettings:e=>r.signalingBackendController.refreshHostedAppSettings(e),usesDirectRoomBackend:()=>r.runtimeStatus.usesDirectRoomBackend(),getRoomBackendTag:()=>r.runtimeStatus.getRoomBackendTag()})}var In=class{constructor(e){this.ctx=e;this.browserBackgrounded=false;this.disposed=false;this.removeBrowserListeners=null;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.removeBrowserListeners?.(),this.removeBrowserListeners=null);}installListeners(){if(this.disposed||this.removeBrowserListeners||typeof document>"u"||typeof window>"u")return;let e=()=>{if(this.disposed)return;let i=document.visibilityState==="hidden";this.handleBackgroundState(i,"visibilitychange");},t=()=>{this.disposed||this.handleBackgroundState(false,"pageshow");},n=()=>{this.disposed||this.reconcileConnectionsAfterAvailabilityHint("online");};e(),document.addEventListener("visibilitychange",e),window.addEventListener("pageshow",t),window.addEventListener("online",n),this.removeBrowserListeners=()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("pageshow",t),window.removeEventListener("online",n);};}async handleBackgroundState(e,t){if(this.disposed)return;let n=this.browserBackgrounded!==e;this.browserBackgrounded=e;let i=this.ctx.wasmClient;if(i&&typeof i.set_app_backgrounded=="function")try{await i.set_app_backgrounded(e);}catch(o){console.warn("[Client][APP] Failed to propagate background state to wasm runtime",{backgrounded:e,source:t,error:o});}this.disposed||!e&&n&&this.reconcileConnectionsAfterAvailabilityHint(t);}reconcileConnectionsAfterForeground(e){this.reconcileConnectionsAfterAvailabilityHint(e);}reconcileConnectionsAfterAvailabilityHint(e){if(!this.disposed)for(let t of this.ctx.registry.values()){if(t.isClosed)continue;let n=t.getUpgradeState();c$1("[Client][APP] Availability recovery reconcile",{source:e,connectionId:t.id,remoteNodeId:t.remoteNodeId,upgradeState:n}),t.handleAppForeground();}}};var Rn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.admissionRepairInFlight=new Map;this.repairedAdmissionStableIdByNode=new Map;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true,this.admissionRepairInFlight.clear(),this.repairedAdmissionStableIdByNode.clear();}assertActive(){if(this.disposed)throw new Error("Managed transport dialer is disposed")}async repairAdmissionForTransportGeneration(e,t){if(this.assertActive(),!e||!Number.isSafeInteger(t)||t<=0)return false;if(this.repairedAdmissionStableIdByNode.get(e)===t)return true;let n=this.deps.getRouteRepairTokenForNode?.(e)?.trim()??"",i=this.deps.getRouteRepairTokenPayloadForNode?.(e)?.trim()??"";if(!n||!i)return false;let o=this.admissionRepairInFlight.get(e);if(o?.transportStableId===t)return o.promise;let s=this.performAdmissionRepair(e,t,n,i);this.admissionRepairInFlight.set(e,{transportStableId:t,promise:s});try{let a=await s,c=this.admissionRepairInFlight.get(e);return a&&c?.promise===s&&c.transportStableId===t&&this.repairedAdmissionStableIdByNode.set(e,t),a}finally{this.admissionRepairInFlight.get(e)?.promise===s&&this.admissionRepairInFlight.delete(e);}}async performAdmissionRepair(e,t,n,i){let o=this.ctx.wasmClient;if(!o)return false;let s=(await this.deps.getLocalDeviceId().catch(()=>null))?.trim()||this.deps.getFallbackLocalDeviceId()?.trim()||null;this.assertActive();let a=4;for(let c=1;c<=a;c+=1)try{return await this.presentSessionTokenToHost(o,e,n,i,s,2e4),this.assertActive(),c$1("[ManagedTransportDialer] repaired admission for physical generation",{remoteNodeId:e,transportStableId:t,attempt:c}),!0}catch(l){if(!this.isTransientSessionTokenPresentationError(l)||c>=a)throw l;console.warn("[ManagedTransportDialer] current-generation admission repair lost transiently; retrying",{remoteNodeId:e,transportStableId:t,attempt:c,nextAttempt:c+1,error:l instanceof Error?l.message:String(l)}),await this.sleepSessionTokenRetry(c),this.assertActive();}return false}normalizeConnectResult(e,t,n,i){let o=e&&typeof e=="object"?e:{},s=typeof o.connectionId=="string"&&o.connectionId.trim()?o.connectionId.trim():t,a=typeof o.remoteNodeId=="string"&&o.remoteNodeId.trim()?o.remoteNodeId.trim():n,c=typeof o.deviceId=="string"&&o.deviceId.trim()?o.deviceId.trim():i??null,l=typeof o.deviceIdHint=="string"&&o.deviceIdHint.trim()?o.deviceIdHint.trim():c,p=typeof o.state=="string"&&o.state.trim()?o.state.trim():"connected",u=typeof o.approvedScope=="string"&&o.approvedScope.trim()?o.approvedScope.trim():typeof o.approved_scope=="string"&&o.approved_scope.trim()?o.approved_scope.trim():null;return {connectionId:s,deviceId:c,deviceIdHint:l,remoteNodeId:a,state:p,approvedScope:u}}async ensureWasmManagedTransport(e,t,n){this.assertActive();let i=this.ctx.wasmClient;if(!i||typeof i.connect_device!="function")throw new Error("[Client] WASM managed transport requires connect_device()");let o=n?.timeoutMs??2e4,s=e.trim(),{irohTicket:a,tokenSuffix:c}=se(s),l=c===null?s:a,p=c!==null?ue(a,c):null;if(c!==null&&!p)throw new Error("invalid compound ticket payload for endpoint ticket");let u=typeof p?.t=="string"&&p.t.trim()?p.t.trim():null;if(c!==null&&!u)throw new Error("invalid compound ticket payload for endpoint ticket");let g=await i.endpoint_id_from_ticket(a);this.assertActive(),u&&c&&this.deps.rememberRouteRepairTokenForNode(g,u,c);let y=this.deps.getDeterministicConnectionId(g),m=u?await this.deps.getLocalDeviceId().catch(()=>null):null,v=u&&(m?.trim()||this.deps.getFallbackLocalDeviceId()?.trim())||null;if(this.assertActive(),n?.skipIfConnected&&typeof i.is_connected=="function")try{let D=await i.is_connected(g);if(this.assertActive(),D){let _=c===null?this.deps.getApprovedScope(y):null;if(!(c!==null&&!_&&!n?.admissionAlreadyPresented))return {connectionId:y,deviceId:t??null,deviceIdHint:t??null,remoteNodeId:g,state:"connected",approvedScope:_}}}catch(D){if(this.disposed)throw D}let S=await E(i.connect_device(t??null,l),o,"wasmClient.connect_device");this.assertActive();let I=this.normalizeConnectResult(S,y,g,t??null),k=I.approvedScope??(c===null?this.deps.getApprovedScope(I.connectionId):null);if(c!==null&&!k&&!n?.admissionAlreadyPresented){for(let _=1;_<=4&&!k;_+=1)try{k=await this.presentSessionTokenToHost(i,g,u,c,v,o);}catch(E$1){if(!this.isTransientSessionTokenPresentationError(E$1)||_>=4)throw E$1;console.warn("[ManagedTransportDialer] session-token presentation lost transiently; redialing over iroh",{nodeId:g,remoteDeviceId:t??null,claimedLocalDeviceId:v,attempt:_,nextAttempt:_+1,error:E$1 instanceof Error?E$1.message:String(E$1)}),await this.sleepSessionTokenRetry(_),S=await E(i.connect_device(t??null,l),o,`wasmClient.connect_device(session-token-retry-${_})`),this.assertActive(),I=this.normalizeConnectResult(S,y,g,t??null),k=I.approvedScope??(c===null?this.deps.getApprovedScope(I.connectionId):null);}this.assertActive();}let T=k?{...I,approvedScope:k}:I;if(c!==null&&!T.approvedScope&&!n?.admissionAlreadyPresented)throw new Error("Failed to present session token: session token admission failed");return T}async presentSessionTokenToHost(e,t,n,i,o,s){try{if(typeof e.present_session_token_to_host_with_payload_and_device_id=="function"){let a=await E(e.present_session_token_to_host_with_payload_and_device_id(t,n,i,o),s,"wasmClient.present_session_token_to_host_with_payload_and_device_id");return this.normalizeApprovedScope(a)}if(typeof e.present_session_token_to_host_with_payload=="function"){let a=await E(e.present_session_token_to_host_with_payload(t,n,i),s,"wasmClient.present_session_token_to_host_with_payload");return this.normalizeApprovedScope(a)}if(typeof e.present_session_token_to_host=="function"){let a=await E(e.present_session_token_to_host(t,n),s,"wasmClient.present_session_token_to_host");return this.normalizeApprovedScope(a)}}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Failed to present session token: ${c}`)}return null}normalizeApprovedScope(e){return typeof e=="string"&&e.trim()?e.trim():null}isTransientSessionTokenPresentationError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:String(e?.message??e??"");return /session-token-response|missing connection for session-token presentation|failed to open bi-stream|connection lost|stream finished early|0 bytes read|locallyclosed|connection closed|stream closed|reset/i.test(t)}isLocalIrohRuntimeNotInitializedError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:String(e?.message??e??"");return /\bIroh node not initialized\b|\bNode not initialized\b/i.test(t)}sleepSessionTokenRetry(e){let t=Math.min(500,100*Math.max(1,e));return u(t)}};var ct=class r{static __wrap(e){let t=Object.create(r.prototype);return t.__wbg_ptr=e,ts.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ts.unregister(this),e}free(){let e=this.__destroy_into_raw();d.__wbg_bistream_free(e,0);}get applicationCryptoWrapped(){return d.bistream_applicationCryptoWrapped(this.__wbg_ptr)!==0}get endpoint_id(){let e,t;try{let o=d.__wbindgen_add_to_stack_pointer(-16);d.bistream_endpoint_id(o,this.__wbg_ptr);var n=M().getInt32(o+0,!0),i=M().getInt32(o+4,!0);return e=n,t=i,$(n,i)}finally{d.__wbindgen_add_to_stack_pointer(16),d.__wbindgen_export4(e,t,1);}}finishSend(){let e=d.bistream_finishSend(this.__wbg_ptr);return P(e)}get recv(){let e=d.bistream_recv(this.__wbg_ptr);return P(e)}get send(){let e=d.bistream_send(this.__wbg_ptr);return P(e)}};Symbol.dispose&&(ct.prototype[Symbol.dispose]=ct.prototype.free);var lt=class r{static __wrap(e){let t=Object.create(r.prototype);return t.__wbg_ptr=e,ns.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ns.unregister(this),e}free(){let e=this.__destroy_into_raw();d.__wbg_intounderlyingsink_free(e,0);}abort(e){let t=this.__destroy_into_raw(),n=d.intounderlyingsink_abort(t,R(e));return P(n)}close(){let e=this.__destroy_into_raw(),t=d.intounderlyingsink_close(e);return P(t)}write(e){let t=d.intounderlyingsink_write(this.__wbg_ptr,R(e));return P(t)}};Symbol.dispose&&(lt.prototype[Symbol.dispose]=lt.prototype.free);var dt=class r{static __wrap(e){let t=Object.create(r.prototype);return t.__wbg_ptr=e,is.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,is.unregister(this),e}free(){let e=this.__destroy_into_raw();d.__wbg_intounderlyingsource_free(e,0);}cancel(){let e=this.__destroy_into_raw();d.intounderlyingsource_cancel(e);}pull(e){let t=d.intounderlyingsource_pull(this.__wbg_ptr,R(e));return P(t)}};Symbol.dispose&&(dt.prototype[Symbol.dispose]=dt.prototype.free);var pt=class r{static __wrap(e){let t=Object.create(r.prototype);return t.__wbg_ptr=e,os.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,os.unregister(this),e}free(){let e=this.__destroy_into_raw();d.__wbg_peerunistream_free(e,0);}get applicationCryptoWrapped(){return d.peerunistream_applicationCryptoWrapped(this.__wbg_ptr)!==0}finishSend(){let e=d.peerunistream_finishSend(this.__wbg_ptr);return P(e)}get writable(){let e=d.peerunistream_writable(this.__wbg_ptr);return P(e)}};Symbol.dispose&&(pt.prototype[Symbol.dispose]=pt.prototype.free);var He=class r{static __wrap(e){let t=Object.create(r.prototype);return t.__wbg_ptr=e,ji.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,ji.unregister(this),e}free(){let e=this.__destroy_into_raw();d.__wbg_wasmclient_free(e,0);}add_peer_scope(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=d.wasmclient_add_peer_scope(this.__wbg_ptr,n,i,o,s);return P(a)}bind_connection_device_id(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=d.wasmclient_bind_connection_device_id(this.__wbg_ptr,n,i,o,s);return P(a)}bind_node_device_id(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=d.wasmclient_bind_node_device_id(this.__wbg_ptr,n,i,o,s);return P(a)}clearConnectionApplicationCryptoKey(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C;d.wasmclient_clearConnectionApplicationCryptoKey(this.__wbg_ptr,t,n);}clear_session_tokens(){d.wasmclient_clear_session_tokens(this.__wbg_ptr);}confirm_inline_reciprocal_session_admission(e,t,n,i,o,s){let a=b(e,d.__wbindgen_export,d.__wbindgen_export2),c=C,l=b(n,d.__wbindgen_export,d.__wbindgen_export2),p=C,u=b(i,d.__wbindgen_export,d.__wbindgen_export2),g=C;var y=x(s)?0:b(s,d.__wbindgen_export,d.__wbindgen_export2),m=C;let v=d.wasmclient_confirm_inline_reciprocal_session_admission(this.__wbg_ptr,a,c,t,l,p,u,g,o,y,m);return P(v)}connect(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_connect(this.__wbg_ptr,t,n);return P(i)}connect_device(e,t){var n=x(e)?0:b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C;let o=b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=d.wasmclient_connect_device(this.__wbg_ptr,n,i,o,s);return P(a)}connection_state(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_connection_state(this.__wbg_ptr,t,n);return P(i)}connection_states(){let e=d.wasmclient_connection_states(this.__wbg_ptr);return P(e)}create_room(e,t,n,i,o,s){let a=b(e,d.__wbindgen_export,d.__wbindgen_export2),c=C,l=b(t,d.__wbindgen_export,d.__wbindgen_export2),p=C,u=b(n,d.__wbindgen_export,d.__wbindgen_export2),g=C,y=b(i,d.__wbindgen_export,d.__wbindgen_export2),m=C,v=b(o,d.__wbindgen_export,d.__wbindgen_export2),S=C,I=d.wasmclient_create_room(this.__wbg_ptr,a,c,l,p,u,g,y,m,v,S,x(s)?Number.MAX_SAFE_INTEGER:s>>>0);return P(I)}create_session(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_create_session(this.__wbg_ptr,t,n);return P(i)}delete_device(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=d.wasmclient_delete_device(this.__wbg_ptr,n,i,o,s);return P(a)}devices_with_status(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_devices_with_status(this.__wbg_ptr,t,n);return P(i)}disconnect(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_disconnect(this.__wbg_ptr,t,n);return P(i)}disconnect_device(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C;var o=x(t)?0:b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C;let a=d.wasmclient_disconnect_device(this.__wbg_ptr,n,i,o,s);return P(a)}disconnect_transient(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_disconnect_transient(this.__wbg_ptr,t,n);return P(i)}endpoint_id_from_ticket(e){let t,n;try{let p=d.__wbindgen_add_to_stack_pointer(-16),u=b(e,d.__wbindgen_export,d.__wbindgen_export2),g=C;d.wasmclient_endpoint_id_from_ticket(p,this.__wbg_ptr,u,g);var i=M().getInt32(p+0,!0),o=M().getInt32(p+4,!0),s=M().getInt32(p+8,!0),a=M().getInt32(p+12,!0),c=i,l=o;if(a)throw c=0,l=0,P(s);return t=c,n=l,$(c,l)}finally{d.__wbindgen_add_to_stack_pointer(16),d.__wbindgen_export4(t,n,1);}}endpoint_ticket(){let e=d.wasmclient_endpoint_ticket(this.__wbg_ptr);return P(e)}endpoint_ticket_with_token(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=d.wasmclient_endpoint_ticket_with_token(this.__wbg_ptr,n,i,t);return P(o)}force_reconnect_snapshot(){d.wasmclient_force_reconnect_snapshot(this.__wbg_ptr);}get_members(e,t,n){let i=b(e,d.__wbindgen_export,d.__wbindgen_export2),o=C,s=b(t,d.__wbindgen_export,d.__wbindgen_export2),a=C,c=b(n,d.__wbindgen_export,d.__wbindgen_export2),l=C,p=d.wasmclient_get_members(this.__wbg_ptr,i,o,s,a,c,l);return P(p)}heartbeat_tick(e,t,n){let i=b(e,d.__wbindgen_export,d.__wbindgen_export2),o=C,s=b(t,d.__wbindgen_export,d.__wbindgen_export2),a=C,c=b(n,d.__wbindgen_export,d.__wbindgen_export2),l=C,p=d.wasmclient_heartbeat_tick(this.__wbg_ptr,i,o,s,a,c,l);return P(p)}incoming_streams(){let e=d.wasmclient_incoming_streams(this.__wbg_ptr);return P(e)}init_iroh(e){var t=x(e)?0:Pn(e,d.__wbindgen_export),n=C;let i=d.wasmclient_init_iroh(this.__wbg_ptr,t,n);return P(i)}iroh_path_kind(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_iroh_path_kind(this.__wbg_ptr,t,n);return P(i)}iroh_secret_key(){let e=d.wasmclient_iroh_secret_key(this.__wbg_ptr);return P(e)}iroh_transport_rtt_ms(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_iroh_transport_rtt_ms(this.__wbg_ptr,t,n);return P(i)}is_auto_connect_excluded(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C;return d.wasmclient_is_auto_connect_excluded(this.__wbg_ptr,t,n)!==0}is_connected(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_is_connected(this.__wbg_ptr,t,n);return P(i)}is_current_transport_stable_id(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=d.wasmclient_is_current_transport_stable_id(this.__wbg_ptr,n,i,t);return P(o)}join_room(e,t,n,i,o){let s=b(e,d.__wbindgen_export,d.__wbindgen_export2),a=C,c=b(t,d.__wbindgen_export,d.__wbindgen_export2),l=C,p=b(n,d.__wbindgen_export,d.__wbindgen_export2),u=C,g=b(i,d.__wbindgen_export,d.__wbindgen_export2),y=C,m=b(o,d.__wbindgen_export,d.__wbindgen_export2),v=C,S=d.wasmclient_join_room(this.__wbg_ptr,s,a,c,l,p,u,g,y,m,v);return P(S)}leave_room(e,t,n){let i=b(e,d.__wbindgen_export,d.__wbindgen_export2),o=C,s=b(t,d.__wbindgen_export,d.__wbindgen_export2),a=C,c=b(n,d.__wbindgen_export,d.__wbindgen_export2),l=C,p=d.wasmclient_leave_room(this.__wbg_ptr,i,o,s,a,c,l);return P(p)}list_managed_connections(){let e=d.wasmclient_list_managed_connections(this.__wbg_ptr);return P(e)}constructor(e,t){try{let s=d.__wbindgen_add_to_stack_pointer(-16),a=b(e,d.__wbindgen_export,d.__wbindgen_export2),c=C,l=b(t,d.__wbindgen_export,d.__wbindgen_export2),p=C;d.wasmclient_new(s,a,c,l,p);var n=M().getInt32(s+0,!0),i=M().getInt32(s+4,!0),o=M().getInt32(s+8,!0);if(o)throw P(i);return this.__wbg_ptr=n,ji.register(this,this.__wbg_ptr,this),this}finally{d.__wbindgen_add_to_stack_pointer(16);}}static newWithAppTag(e,t){try{let s=d.__wbindgen_add_to_stack_pointer(-16),a=b(e,d.__wbindgen_export,d.__wbindgen_export2),c=C,l=b(t,d.__wbindgen_export,d.__wbindgen_export2),p=C;d.wasmclient_newWithAppTag(s,a,c,l,p);var n=M().getInt32(s+0,!0),i=M().getInt32(s+4,!0),o=M().getInt32(s+8,!0);if(o)throw P(i);return r.__wrap(n)}finally{d.__wbindgen_add_to_stack_pointer(16);}}node_addr(){let e=d.wasmclient_node_addr(this.__wbg_ptr);return P(e)}open_bi(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_open_bi(this.__wbg_ptr,t,n);return P(i)}open_native_main_control_bi(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_open_native_main_control_bi(this.__wbg_ptr,t,n);return P(i)}open_peer_bi(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=d.wasmclient_open_peer_bi(this.__wbg_ptr,n,i,x(t)?Number.MAX_SAFE_INTEGER:t>>>0);return P(o)}open_peer_bi_explicit_file_sender(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=d.wasmclient_open_peer_bi_explicit_file_sender(this.__wbg_ptr,n,i,x(t)?Number.MAX_SAFE_INTEGER:t>>>0);return P(o)}open_peer_bi_transport_only(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=d.wasmclient_open_peer_bi_transport_only(this.__wbg_ptr,n,i,x(t)?Number.MAX_SAFE_INTEGER:t>>>0);return P(o)}open_peer_native_bi(e,t,n){let i=b(e,d.__wbindgen_export,d.__wbindgen_export2),o=C,s=b(t,d.__wbindgen_export,d.__wbindgen_export2),a=C,c=d.wasmclient_open_peer_native_bi(this.__wbg_ptr,i,o,s,a,x(n)?Number.MAX_SAFE_INTEGER:n>>>0);return P(c)}open_peer_uni(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=d.wasmclient_open_peer_uni(this.__wbg_ptr,n,i,x(t)?Number.MAX_SAFE_INTEGER:t>>>0);return P(o)}open_uni(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_open_uni(this.__wbg_ptr,t,n);return P(i)}peer_scopes(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_peer_scopes(this.__wbg_ptr,t,n);return P(i)}peer_session(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_peer_session(this.__wbg_ptr,t,n);return P(i)}peer_sessions(){let e=d.wasmclient_peer_sessions(this.__wbg_ptr);return P(e)}peer_snapshot(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_peer_snapshot(this.__wbg_ptr,t,n);return P(i)}prepare_inline_reciprocal_session_admission(e,t,n,i,o,s,a,c){let l=b(e,d.__wbindgen_export,d.__wbindgen_export2),p=C,u=b(n,d.__wbindgen_export,d.__wbindgen_export2),g=C,y=b(i,d.__wbindgen_export,d.__wbindgen_export2),m=C,v=b(o,d.__wbindgen_export,d.__wbindgen_export2),S=C,I=b(s,d.__wbindgen_export,d.__wbindgen_export2),k=C,T=b(a,d.__wbindgen_export,d.__wbindgen_export2),D=C,_=b(c,d.__wbindgen_export,d.__wbindgen_export2),E=C,A=d.wasmclient_prepare_inline_reciprocal_session_admission(this.__wbg_ptr,l,p,t,u,g,y,m,v,S,I,k,T,D,_,E);return P(A)}present_session_token_to_host(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=d.wasmclient_present_session_token_to_host(this.__wbg_ptr,n,i,o,s);return P(a)}present_session_token_to_host_with_payload(e,t,n){let i=b(e,d.__wbindgen_export,d.__wbindgen_export2),o=C,s=b(t,d.__wbindgen_export,d.__wbindgen_export2),a=C;var c=x(n)?0:b(n,d.__wbindgen_export,d.__wbindgen_export2),l=C;let p=d.wasmclient_present_session_token_to_host_with_payload(this.__wbg_ptr,i,o,s,a,c,l);return P(p)}present_session_token_to_host_with_payload_and_device_id(e,t,n,i){let o=b(e,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=b(t,d.__wbindgen_export,d.__wbindgen_export2),c=C;var l=x(n)?0:b(n,d.__wbindgen_export,d.__wbindgen_export2),p=C,u=x(i)?0:b(i,d.__wbindgen_export,d.__wbindgen_export2),g=C;let y=d.wasmclient_present_session_token_to_host_with_payload_and_device_id(this.__wbg_ptr,o,s,a,c,l,p,u,g);return P(y)}rankRoutes(e,t){try{let s=d.__wbindgen_add_to_stack_pointer(-16),a=ss(e,d.__wbindgen_export),c=C,l=ss(t,d.__wbindgen_export),p=C;d.wasmclient_rankRoutes(s,this.__wbg_ptr,a,c,l,p);var n=M().getInt32(s+0,!0),i=M().getInt32(s+4,!0),o=uc(n,i).slice();return d.__wbindgen_export4(n,i*4,4),o}finally{d.__wbindgen_add_to_stack_pointer(16);}}register_session_token(e,t,n){let i=b(e,d.__wbindgen_export,d.__wbindgen_export2),o=C,s=b(t,d.__wbindgen_export,d.__wbindgen_export2),a=C;d.wasmclient_register_session_token(this.__wbg_ptr,i,o,s,a,n);}register_session_token_with_expiry_ms(e,t,n,i){let o=b(e,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=b(t,d.__wbindgen_export,d.__wbindgen_export2),c=C;d.wasmclient_register_session_token_with_expiry_ms(this.__wbg_ptr,o,s,a,c,n,i);}reject_connection_admission(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=d.wasmclient_reject_connection_admission(this.__wbg_ptr,n,i,o,s);return P(a)}release_peer_scope(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C;var o=x(t)?0:b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C;let a=d.wasmclient_release_peer_scope(this.__wbg_ptr,n,i,o,s);return P(a)}remote_session_admission_ready_for_ticket(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_remote_session_admission_ready_for_ticket(this.__wbg_ptr,t,n);return P(i)}report_managed_connection_settled(e,t,n,i,o,s){let a=b(e,d.__wbindgen_export,d.__wbindgen_export2),c=C;var l=x(n)?0:b(n,d.__wbindgen_export,d.__wbindgen_export2),p=C;let u=d.wasmclient_report_managed_connection_settled(this.__wbg_ptr,a,c,t,l,p,!x(i),x(i)?BigInt(0):i,!x(o),x(o)?BigInt(0):o,!x(s),x(s)?BigInt(0):s);return P(u)}report_transport_status(e,t,n,i,o,s){let a=b(e,d.__wbindgen_export,d.__wbindgen_export2),c=C,l=b(t,d.__wbindgen_export,d.__wbindgen_export2),p=C;var u=x(n)?0:b(n,d.__wbindgen_export,d.__wbindgen_export2),g=C;let y=d.wasmclient_report_transport_status(this.__wbg_ptr,a,c,l,p,u,g,!x(i),x(i)?BigInt(0):i,!x(o),x(o)?BigInt(0):o,!x(s),x(s)?BigInt(0):s);return P(y)}resolve_peer_connection_records(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_resolve_peer_connection_records(this.__wbg_ptr,t,n);return P(i)}revoke_session_token(e){try{let o=d.__wbindgen_add_to_stack_pointer(-16),s=b(e,d.__wbindgen_export,d.__wbindgen_export2),a=C;d.wasmclient_revoke_session_token(o,this.__wbg_ptr,s,a);var t=M().getInt32(o+0,!0),n=M().getInt32(o+4,!0),i=M().getInt32(o+8,!0);if(i)throw P(n);return P(t)}finally{d.__wbindgen_add_to_stack_pointer(16);}}revoke_tokens_by_scope(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_revoke_tokens_by_scope(this.__wbg_ptr,t,n);return P(i)}runtime_policy(){try{let i=d.__wbindgen_add_to_stack_pointer(-16);d.wasmclient_runtime_policy(i,this.__wbg_ptr);var e=M().getInt32(i+0,!0),t=M().getInt32(i+4,!0),n=M().getInt32(i+8,!0);if(n)throw P(t);return P(e)}finally{d.__wbindgen_add_to_stack_pointer(16);}}same_peer(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=d.wasmclient_same_peer(this.__wbg_ptr,n,i,o,s);return P(a)}search_devices(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_search_devices(this.__wbg_ptr,t,n);return P(i)}send_message(e,t,n,i){let o=b(e,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=b(t,d.__wbindgen_export,d.__wbindgen_export2),c=C;var l=x(n)?0:b(n,d.__wbindgen_export,d.__wbindgen_export2),p=C,u=x(i)?0:b(i,d.__wbindgen_export,d.__wbindgen_export2),g=C;let y=d.wasmclient_send_message(this.__wbg_ptr,o,s,a,c,l,p,u,g);return P(y)}send_peer(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=Pn(t,d.__wbindgen_export),s=C,a=d.wasmclient_send_peer(this.__wbg_ptr,n,i,o,s);return P(a)}send_peer_application_frame(e,t,n){let i=b(e,d.__wbindgen_export,d.__wbindgen_export2),o=C,s=Pn(t,d.__wbindgen_export),a=C,c=d.wasmclient_send_peer_application_frame(this.__wbg_ptr,i,o,s,a,x(n)?Number.MAX_SAFE_INTEGER:n>>>0);return P(c)}setConnectionApplicationCryptoKey(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=Pn(t,d.__wbindgen_export),s=C,a=d.wasmclient_setConnectionApplicationCryptoKey(this.__wbg_ptr,n,i,o,s);return P(a)}setConnectionApplicationCryptoRequired(e){try{let i=d.__wbindgen_add_to_stack_pointer(-16),o=b(e,d.__wbindgen_export,d.__wbindgen_export2),s=C;d.wasmclient_setConnectionApplicationCryptoRequired(i,this.__wbg_ptr,o,s);var t=M().getInt32(i+0,!0),n=M().getInt32(i+4,!0);if(n)throw P(t)}finally{d.__wbindgen_add_to_stack_pointer(16);}}set_auth_token(e){var t=x(e)?0:b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C;d.wasmclient_set_auth_token(this.__wbg_ptr,t,n);}set_auto_connect_excluded(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=d.wasmclient_set_auto_connect_excluded(this.__wbg_ptr,n,i,t);return P(o)}set_offline(e){let t=b(e,d.__wbindgen_export,d.__wbindgen_export2),n=C,i=d.wasmclient_set_offline(this.__wbg_ptr,t,n);return P(i)}start_auto_connect(e,t){try{let o=d.__wbindgen_add_to_stack_pointer(-16),s=b(e,d.__wbindgen_export,d.__wbindgen_export2),a=C,c=b(t,d.__wbindgen_export,d.__wbindgen_export2),l=C;d.wasmclient_start_auto_connect(o,this.__wbg_ptr,s,a,c,l);var n=M().getInt32(o+0,!0),i=M().getInt32(o+4,!0);if(i)throw P(n)}finally{d.__wbindgen_add_to_stack_pointer(16);}}start_presence_loop(e,t,n,i){let o=b(e,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=b(t,d.__wbindgen_export,d.__wbindgen_export2),c=C,l=b(n,d.__wbindgen_export,d.__wbindgen_export2),p=C;var u=x(i)?0:b(i,d.__wbindgen_export,d.__wbindgen_export2),g=C;d.wasmclient_start_presence_loop(this.__wbg_ptr,o,s,a,c,l,p,u,g);}stop_auth_scoped_activity(){d.wasmclient_stop_auth_scoped_activity(this.__wbg_ptr);}stop_auto_connect(){d.wasmclient_stop_auto_connect(this.__wbg_ptr);}stop_presence_loop(){d.wasmclient_stop_presence_loop(this.__wbg_ptr);}submit_browser_desired_peers(e,t){try{let s=d.__wbindgen_add_to_stack_pointer(-16),a=b(t,d.__wbindgen_export,d.__wbindgen_export2),c=C;d.wasmclient_submit_browser_desired_peers(s,this.__wbg_ptr,e,a,c);var n=M().getInt32(s+0,!0),i=M().getInt32(s+4,!0),o=M().getInt32(s+8,!0);if(o)throw P(i);return n!==0}finally{d.__wbindgen_add_to_stack_pointer(16);}}update_device(e,t,n,i,o){let s=b(e,d.__wbindgen_export,d.__wbindgen_export2),a=C,c=b(t,d.__wbindgen_export,d.__wbindgen_export2),l=C;var p=x(n)?0:b(n,d.__wbindgen_export,d.__wbindgen_export2),u=C,g=x(o)?0:b(o,d.__wbindgen_export,d.__wbindgen_export2),y=C;let m=d.wasmclient_update_device(this.__wbg_ptr,s,a,c,l,p,u,x(i)?0:R(i),g,y);return P(m)}update_presence(e,t,n,i,o){let s=b(e,d.__wbindgen_export,d.__wbindgen_export2),a=C,c=b(t,d.__wbindgen_export,d.__wbindgen_export2),l=C,p=b(n,d.__wbindgen_export,d.__wbindgen_export2),u=C;var g=x(i)?0:b(i,d.__wbindgen_export,d.__wbindgen_export2),y=C;let m=d.wasmclient_update_presence(this.__wbg_ptr,s,a,c,l,p,u,g,y,!x(o),x(o)?BigInt(0):o);return P(m)}update_session(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=d.wasmclient_update_session(this.__wbg_ptr,n,i,o,s);return P(a)}validate_session_token(e){let t,n;try{let p=d.__wbindgen_add_to_stack_pointer(-16),u=b(e,d.__wbindgen_export,d.__wbindgen_export2),g=C;d.wasmclient_validate_session_token(p,this.__wbg_ptr,u,g);var i=M().getInt32(p+0,!0),o=M().getInt32(p+4,!0),s=M().getInt32(p+8,!0),a=M().getInt32(p+12,!0),c=i,l=o;if(a)throw c=0,l=0,P(s);return t=c,n=l,$(c,l)}finally{d.__wbindgen_add_to_stack_pointer(16),d.__wbindgen_export4(t,n,1);}}validate_session_token_for_connection(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=b(t,d.__wbindgen_export,d.__wbindgen_export2),s=C,a=d.wasmclient_validate_session_token_for_connection(this.__wbg_ptr,n,i,o,s);return P(a)}validate_session_token_for_connection_with_payload(e,t,n){let i=b(e,d.__wbindgen_export,d.__wbindgen_export2),o=C,s=b(t,d.__wbindgen_export,d.__wbindgen_export2),a=C;var c=x(n)?0:b(n,d.__wbindgen_export,d.__wbindgen_export2),l=C;let p=d.wasmclient_validate_session_token_for_connection_with_payload(this.__wbg_ptr,i,o,s,a,c,l);return P(p)}wait_for_settled_peer(e,t){let n=b(e,d.__wbindgen_export,d.__wbindgen_export2),i=C,o=d.wasmclient_wait_for_settled_peer(this.__wbg_ptr,n,i,x(t)?Number.MAX_SAFE_INTEGER:t>>>0);return P(o)}wake_browser_auto_connect(){return d.wasmclient_wake_browser_auto_connect(this.__wbg_ptr)!==0}};Symbol.dispose&&(He.prototype[Symbol.dispose]=He.prototype.free);function as(){d.start();}function $a(){return {__proto__:null,"./openrtc_bg.js":{__proto__:null,__wbg_Error_9dc85fe1bc224456:function(e,t){let n=Error($(e,t));return R(n)},__wbg_String_8564e559799eccda:function(e,t){let n=String(f(t)),i=b(n,d.__wbindgen_export,d.__wbindgen_export2),o=C;M().setInt32(e+4,o,true),M().setInt32(e+0,i,true);},__wbg___wbindgen_boolean_get_b131b2f36d6b2f55:function(e){let t=f(e),n=typeof t=="boolean"?t:void 0;return x(n)?16777215:n?1:0},__wbg___wbindgen_debug_string_56c147eb1a51f0c4:function(e,t){let n=qi(f(t)),i=b(n,d.__wbindgen_export,d.__wbindgen_export2),o=C;M().setInt32(e+4,o,true),M().setInt32(e+0,i,true);},__wbg___wbindgen_in_ce8569b2fc6f5088:function(e,t){return f(e)in f(t)},__wbg___wbindgen_is_function_147961669f068cd4:function(e){return typeof f(e)=="function"},__wbg___wbindgen_is_null_ced4761460071341:function(e){return f(e)===null},__wbg___wbindgen_is_object_3a2c414391dbf751:function(e){let t=f(e);return typeof t=="object"&&t!==null},__wbg___wbindgen_is_string_6541b0f6ecd4e8e5:function(e){return typeof f(e)=="string"},__wbg___wbindgen_is_undefined_4410e3c20a99fa97:function(e){return f(e)===void 0},__wbg___wbindgen_jsval_eq_174c93ec61bab0c5:function(e,t){return f(e)===f(t)},__wbg___wbindgen_jsval_loose_eq_e07e3b1f5db6da6c:function(e,t){return f(e)==f(t)},__wbg___wbindgen_number_get_588ed6b97f0d7e14:function(e,t){let n=f(t),i=typeof n=="number"?n:void 0;M().setFloat64(e+8,x(i)?0:i,true),M().setInt32(e+0,!x(i),true);},__wbg___wbindgen_string_get_fa2687d531ed17a5:function(e,t){let n=f(t),i=typeof n=="string"?n:void 0;var o=x(i)?0:b(i,d.__wbindgen_export,d.__wbindgen_export2),s=C;M().setInt32(e+4,s,true),M().setInt32(e+0,o,true);},__wbg___wbindgen_throw_bbadd78c1bac3a77:function(e,t){throw new Error($(e,t))},__wbg__wbg_cb_unref_c2301a3c9b78104b:function(e){f(e)._wbg_cb_unref();},__wbg_abort_56c00f462c9261d9:function(e,t){f(e).abort(f(t));},__wbg_abort_f2416f4a9852003e:function(e){f(e).abort();},__wbg_addEventListener_b635263c509aa7de:function(){return H(function(e,t,n,i){f(e).addEventListener($(t,n),f(i));},arguments)},__wbg_append_c5a0c94a6a73b22e:function(){return H(function(e,t,n,i,o){f(e).append($(t,n),$(i,o));},arguments)},__wbg_arrayBuffer_cc7704fa158b907a:function(){return H(function(e){let t=f(e).arrayBuffer();return R(t)},arguments)},__wbg_bistream_new:function(e){let t=ct.__wrap(e);return R(t)},__wbg_body_442a47f02322d7b0:function(e){let t=f(e).body;return x(t)?0:R(t)},__wbg_buffer_8524b3453cde4918:function(e){let t=f(e).buffer;return R(t)},__wbg_byobRequest_cc72d210de793e64:function(e){let t=f(e).byobRequest;return x(t)?0:R(t)},__wbg_byteLength_96807b1d9ab24a4c:function(e){return f(e).byteLength},__wbg_byteOffset_a9c7002428843c41:function(e){return f(e).byteOffset},__wbg_call_91f00ddc43e01490:function(){return H(function(e,t){let n=f(e).call(f(t));return R(n)},arguments)},__wbg_call_ec09a4cf93377d3a:function(){return H(function(e,t,n){let i=f(e).call(f(t),f(n));return R(i)},arguments)},__wbg_cancel_f3a197b26dc88b39:function(e){let t=f(e).cancel();return R(t)},__wbg_catch_66060324c27be6f7:function(e,t){let n=f(e).catch(f(t));return R(n)},__wbg_clearTimeout_113b1cde814ec762:function(e){let t=clearTimeout(P(e));return R(t)},__wbg_clearTimeout_333bba87532ab9d3:function(e){let t=clearTimeout(P(e));return R(t)},__wbg_clearTimeout_47a40e3be01ed7a3:function(){return H(function(e,t){f(e).clearTimeout(P(t));},arguments)},__wbg_clearTimeout_6b8d9a38b9263d65:function(e){let t=clearTimeout(P(e));return R(t)},__wbg_close_296263cfe1bb2999:function(){return H(function(e){f(e).close();},arguments)},__wbg_close_388d99468213b286:function(){return H(function(e){f(e).close();},arguments)},__wbg_close_4857e22d08b71356:function(){return H(function(e){f(e).close();},arguments)},__wbg_code_1cda2855fcd9b009:function(e){return f(e).code},__wbg_code_70beb7b22374d55e:function(e){return f(e).code},__wbg_createDataChannel_122bd3d8aacee49b:function(e,t,n){let i=f(e).createDataChannel($(t,n));return R(i)},__wbg_crypto_38df2bab126b63dc:function(e){let t=f(e).crypto;return R(t)},__wbg_data_8a04443c1e5a8cd3:function(e){let t=f(e).data;return R(t)},__wbg_dispatchEvent_cc62a6a43d28b01c:function(){return H(function(e,t){return f(e).dispatchEvent(f(t))},arguments)},__wbg_done_6a8439e544ec6206:function(e){return f(e).done},__wbg_enqueue_bbeb09ba0b140f76:function(){return H(function(e,t){f(e).enqueue(f(t));},arguments)},__wbg_entries_4e00eefd3fd54cf1:function(e){let t=f(e).entries();return R(t)},__wbg_error_6651fee1c71e5da9:function(e){console.error(f(e));},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,i;try{n=e,i=t,console.error($(e,t));}finally{d.__wbindgen_export4(n,i,1);}},__wbg_fetch_074561c3e313c86f:function(e){let t=fetch(f(e));return R(t)},__wbg_fetch_22858a12fcf93152:function(e,t){let n=f(e).fetch(f(t));return R(n)},__wbg_fetch_9dad4fe911207b37:function(e){let t=fetch(f(e));return R(t)},__wbg_fetch_c374c6d9532750f2:function(e,t){let n=f(e).fetch(f(t));return R(n)},__wbg_getRandomValues_76dfc69825c9c552:function(){return H(function(e,t){globalThis.crypto.getRandomValues(Ne(e,t));},arguments)},__wbg_getRandomValues_c44a50d8cfdaebeb:function(){return H(function(e,t){f(e).getRandomValues(f(t));},arguments)},__wbg_getReader_0cd37e95fbf00f7f:function(e){let t=f(e).getReader();return R(t)},__wbg_getReader_9facd4f899beac89:function(){return H(function(e){let t=f(e).getReader();return R(t)},arguments)},__wbg_get_44e98e27bda25b5b:function(){return H(function(e,t){let n=Reflect.get(f(e),f(t));return R(n)},arguments)},__wbg_get_4b90d6d8c5deb5d5:function(e,t){let n=f(e)[t>>>0];return R(n)},__wbg_get_52a8a619f7b88df6:function(){return H(function(e,t){let n=Reflect.get(f(e),f(t));return R(n)},arguments)},__wbg_get_a82defe8d6b5b2e5:function(){return H(function(e,t,n,i){let o=f(t).get($(n,i));var s=x(o)?0:b(o,d.__wbindgen_export,d.__wbindgen_export2),a=C;M().setInt32(e+4,a,true),M().setInt32(e+0,s,true);},arguments)},__wbg_get_done_c21b9933fc9a9e9c:function(e){let t=f(e).done;return x(t)?16777215:t?1:0},__wbg_get_value_ad568c7d3db9073f:function(e){let t=f(e).value;return R(t)},__wbg_get_with_ref_key_6412cf3094599694:function(e,t){let n=f(e)[f(t)];return R(n)},__wbg_has_14676d88c1340d2c:function(){return H(function(e,t){return Reflect.has(f(e),f(t))},arguments)},__wbg_headers_5b19cf40627ae54d:function(e){let t=f(e).headers;return R(t)},__wbg_info_a2b5f8a5dae8b26c:function(e){console.info(f(e));},__wbg_instanceof_ArrayBuffer_a581da923203f29f:function(e){let t;try{t=f(e)instanceof ArrayBuffer;}catch{t=false;}return t},__wbg_instanceof_Blob_5c4e145be35f9b1e:function(e){let t;try{t=f(e)instanceof Blob;}catch{t=false;}return t},__wbg_instanceof_ReadableStreamDefaultReader_2ab4b6bb85f96463:function(e){let t;try{t=f(e)instanceof ReadableStreamDefaultReader;}catch{t=false;}return t},__wbg_instanceof_Response_36a65a969abaa7c6:function(e){let t;try{t=f(e)instanceof Response;}catch{t=false;}return t},__wbg_instanceof_Uint8Array_b6fe1ac89eba107e:function(e){let t;try{t=f(e)instanceof Uint8Array;}catch{t=false;}return t},__wbg_instanceof_Window_9e0fe7d3d1ff4342:function(e){let t;try{t=f(e)instanceof Window;}catch{t=false;}return t},__wbg_isArray_139f48e3c057ede8:function(e){return Array.isArray(f(e))},__wbg_iterator_9b36cebf3be7b7cd:function(){return R(Symbol.iterator)},__wbg_length_68a9d5278d084f4f:function(e){return f(e).length},__wbg_log_6614a4effdb4e983:function(e){console.log(f(e));},__wbg_message_12958526424a887b:function(e,t){let n=f(t).message,i=b(n,d.__wbindgen_export,d.__wbindgen_export2),o=C;M().setInt32(e+4,o,true),M().setInt32(e+0,i,true);},__wbg_msCrypto_bd5a034af96bcba6:function(e){let t=f(e).msCrypto;return R(t)},__wbg_new_0_878c6ec3a1c600f3:function(){return R(new Date)},__wbg_new_0b303268aa395a38:function(){let e=new Array;return R(e)},__wbg_new_189262ff31890c23:function(){return H(function(){let e=new Headers;return R(e)},arguments)},__wbg_new_20b778a4c5c691c3:function(){let e=new Object;return R(e)},__wbg_new_227d7c05414eb861:function(){let e=new Error;return R(e)},__wbg_new_24739629d416f982:function(){return H(function(){let e=new AbortController;return R(e)},arguments)},__wbg_new_5fae30e6b23db8df:function(e,t){let n=new Error($(e,t));return R(n)},__wbg_new_883c0db065f06efd:function(){return R(new Map)},__wbg_new_a3e5112401a82338:function(){return H(function(e,t){let n=new WebSocket($(e,t));return R(n)},arguments)},__wbg_new_b06772b280cc6e52:function(e){let t=new Uint8Array(f(e));return R(t)},__wbg_new_from_slice_bb2d1778c0b87eb1:function(e,t){let n=new Uint8Array(Ne(e,t));return R(n)},__wbg_new_typed_90c3f6c29ba36d19:function(e,t){try{var n={a:e,b:t},i=(s,a)=>{let c=n.a;n.a=0;try{return oc(c,n.b,s,a)}finally{n.a=c;}};let o=new Promise(i);return R(o)}finally{n.a=0;}},__wbg_new_with_byte_offset_and_length_9e1e664fe1a5d385:function(e,t,n){let i=new Uint8Array(f(e),t>>>0,n>>>0);return R(i)},__wbg_new_with_configuration_3a96aa953ca17197:function(){return H(function(e){let t=new RTCPeerConnection(f(e));return R(t)},arguments)},__wbg_new_with_event_init_dict_bd850674488710b1:function(){return H(function(e,t,n){let i=new CustomEvent($(e,t),f(n));return R(i)},arguments)},__wbg_new_with_into_underlying_sink_2596343f9b6c8e58:function(e){let t=new WritableStream(lt.__wrap(e));return R(t)},__wbg_new_with_into_underlying_source_fd904252f385f59c:function(e,t){let n=new ReadableStream(dt.__wrap(e),P(t));return R(n)},__wbg_new_with_length_4b57a7a5dc67221c:function(e){let t=new Uint8Array(e>>>0);return R(t)},__wbg_new_with_str_and_init_df876572184fe639:function(){return H(function(e,t,n){let i=new Request($(e,t),f(n));return R(i)},arguments)},__wbg_new_with_str_sequence_505a4829cc247e79:function(){return H(function(e,t,n){let i=new WebSocket($(e,t),f(n));return R(i)},arguments)},__wbg_next_8cb028b6ba50743f:function(){return H(function(e){let t=f(e).next();return R(t)},arguments)},__wbg_next_cfd0b146c9538df8:function(e){let t=f(e).next;return R(t)},__wbg_node_84ea875411254db1:function(e){let t=f(e).node;return R(t)},__wbg_now_bce4dc999095ea77:function(){return Date.now()},__wbg_now_e7c6795a7f81e10f:function(e){return f(e).now()},__wbg_ok_2279b99c57bfdfba:function(e){return f(e).ok},__wbg_parse_a5c06e19bc1187fd:function(e,t){return Date.parse($(e,t))},__wbg_peerunistream_new:function(e){let t=pt.__wrap(e);return R(t)},__wbg_performance_3fcf6e32a7e1ed0a:function(e){let t=f(e).performance;return R(t)},__wbg_process_44c7a14e11e9f69e:function(e){let t=f(e).process;return R(t)},__wbg_protocol_28aaef5ea42981d6:function(e,t){let n=f(t).protocol,i=b(n,d.__wbindgen_export,d.__wbindgen_export2),o=C;M().setInt32(e+4,o,true),M().setInt32(e+0,i,true);},__wbg_prototypesetcall_956c7493c68e29b4:function(e,t,n){Uint8Array.prototype.set.call(Ne(e,t),f(n));},__wbg_push_ceb8ef046afb2041:function(e,t){return f(e).push(f(t))},__wbg_queueMicrotask_4698f900840e3286:function(e){queueMicrotask(f(e));},__wbg_queueMicrotask_477a5533c7100338:function(e){let t=f(e).queueMicrotask;return R(t)},__wbg_randomFillSync_6c25eac9869eb53c:function(){return H(function(e,t){f(e).randomFillSync(P(t));},arguments)},__wbg_read_8426c146431f2905:function(e){let t=f(e).read();return R(t)},__wbg_readyState_25243ad6ce649774:function(e){return f(e).readyState},__wbg_reason_4ec455bac79b33ce:function(e,t){let n=f(t).reason,i=b(n,d.__wbindgen_export,d.__wbindgen_export2),o=C;M().setInt32(e+4,o,true),M().setInt32(e+0,i,true);},__wbg_releaseLock_188846ef719acb10:function(e){f(e).releaseLock();},__wbg_removeEventListener_016c1d24523b4730:function(){return H(function(e,t,n,i){f(e).removeEventListener($(t,n),f(i));},arguments)},__wbg_require_b4edbdcf3e2a1ef0:function(){return H(function(){let e=module.require;return R(e)},arguments)},__wbg_resolve_0183de2e8c6b1d54:function(e){let t=Promise.resolve(f(e));return R(t)},__wbg_respond_3cdb4cf32683fd79:function(){return H(function(e,t){f(e).respond(t>>>0);},arguments)},__wbg_send_99d049cae69c53cc:function(){return H(function(e,t,n){f(e).send(Ne(t,n));},arguments)},__wbg_send_bac9d3dc4f21ef28:function(){return H(function(e,t,n){f(e).send($(t,n));},arguments)},__wbg_setTimeout_3a808dd861dd3c12:function(e,t){let n=setTimeout(f(e),t);return R(n)},__wbg_setTimeout_6613a51400c1bf9f:function(){return H(function(e,t,n){let i=f(e).setTimeout(P(t),n);return R(i)},arguments)},__wbg_setTimeout_ef24d2fc3ad97385:function(){return H(function(e,t){let n=setTimeout(f(e),t);return R(n)},arguments)},__wbg_setTimeout_f757f00851f76c42:function(e,t){let n=setTimeout(f(e),t);return R(n)},__wbg_set_3ab3dfede3bae139:function(){return H(function(e,t,n,i,o){f(e).set($(t,n),$(i,o));},arguments)},__wbg_set_5f806304fb633ab3:function(e,t,n){let i=f(e).set(f(t),f(n));return R(i)},__wbg_set_6be42768c690e380:function(e,t,n){f(e)[P(t)]=P(n);},__wbg_set_86698c227e5b9dad:function(e,t,n){f(e).set(Ne(t,n));},__wbg_set_a6ba3ac0e634b822:function(){return H(function(e,t,n){return Reflect.set(f(e),f(t),f(n))},arguments)},__wbg_set_binaryType_8c2dd2cf1cfc2e28:function(e,t){f(e).binaryType=rc[t];},__wbg_set_body_d1153b16a2b95ca1:function(e,t){f(e).body=f(t);},__wbg_set_cache_5a01a8b5e6ca6cf2:function(e,t){f(e).cache=ac[t];},__wbg_set_credentials_e9120ed88b1fc0b8:function(e,t){f(e).credentials=cc[t];},__wbg_set_da33c120a6584674:function(e,t,n){f(e)[t>>>0]=P(n);},__wbg_set_detail_c7af5edea934390b:function(e,t){f(e).detail=f(t);},__wbg_set_handle_event_6147c38b782c7b42:function(e,t){f(e).handleEvent=f(t);},__wbg_set_headers_877ed41890d28af2:function(e,t){f(e).headers=f(t);},__wbg_set_high_water_mark_77da20c49668427d:function(e,t){f(e).highWaterMark=t;},__wbg_set_method_b4ede299b2064f37:function(e,t,n){f(e).method=$(t,n);},__wbg_set_mode_d6c2e1991aa963c6:function(e,t){f(e).mode=lc[t];},__wbg_set_onclose_9cb5c3372e16c192:function(e,t){f(e).onclose=f(t);},__wbg_set_onerror_190fe67e911ebf28:function(e,t){f(e).onerror=f(t);},__wbg_set_onmessage_96337495f0bfb796:function(e,t){f(e).onmessage=f(t);},__wbg_set_onopen_3e2bf6b11d434c2d:function(e,t){f(e).onopen=f(t);},__wbg_set_signal_9022b5aa06a6ce5b:function(e,t){f(e).signal=f(t);},__wbg_signal_41dd1a8913cd0b7d:function(e){let t=f(e).signal;return R(t)},__wbg_stack_3b0d974bbf31e44f:function(e,t){let n=f(t).stack,i=b(n,d.__wbindgen_export,d.__wbindgen_export2),o=C;M().setInt32(e+4,o,true),M().setInt32(e+0,i,true);},__wbg_static_accessor_GLOBAL_60a4124bab7dcc9a:function(){let e=typeof global>"u"?null:global;return x(e)?0:R(e)},__wbg_static_accessor_GLOBAL_THIS_95ca6460658b5d13:function(){let e=typeof globalThis>"u"?null:globalThis;return x(e)?0:R(e)},__wbg_static_accessor_SELF_4c95f759a91e9aae:function(){let e=typeof self>"u"?null:self;return x(e)?0:R(e)},__wbg_static_accessor_WINDOW_44b435597f9e9ee7:function(){let e=typeof window>"u"?null:window;return x(e)?0:R(e)},__wbg_status_9e6505cfa3e73a7c:function(e){return f(e).status},__wbg_stringify_a42c95ea9a7591c9:function(){return H(function(e){let t=JSON.stringify(f(e));return R(t)},arguments)},__wbg_subarray_42216645a367cd7a:function(e,t,n){let i=f(e).subarray(t>>>0,n>>>0);return R(i)},__wbg_text_d0039cf442b19ec4:function(){return H(function(e){let t=f(e).text();return R(t)},arguments)},__wbg_then_254bab9b266a77a5:function(e,t,n){let i=f(e).then(f(t),f(n));return R(i)},__wbg_then_3ea18602c6a5123b:function(e,t){let n=f(e).then(f(t));return R(n)},__wbg_toISOString_1c29c14154d57c76:function(e){let t=f(e).toISOString();return R(t)},__wbg_url_72c67c175685a054:function(e,t){let n=f(t).url,i=b(n,d.__wbindgen_export,d.__wbindgen_export2),o=C;M().setInt32(e+4,o,true),M().setInt32(e+0,i,true);},__wbg_url_d0b8042af0d1bbba:function(e,t){let n=f(t).url,i=b(n,d.__wbindgen_export,d.__wbindgen_export2),o=C;M().setInt32(e+4,o,true),M().setInt32(e+0,i,true);},__wbg_value_3d3defe09fb1ffca:function(e){let t=f(e).value;return R(t)},__wbg_versions_276b2795b1c6a219:function(e){let t=f(e).versions;return R(t)},__wbg_view_15fa5865c6b336e3:function(e){let t=f(e).view;return x(t)?0:R(t)},__wbg_warn_633bacc13ba7e6c3:function(e){console.warn(f(e));},__wbg_wasClean_f17429d064911939:function(e){return f(e).wasClean},__wbindgen_cast_0000000000000001:function(e,t){let n=be(e,t,ec);return R(n)},__wbindgen_cast_0000000000000002:function(e,t){let n=be(e,t,ic);return R(n)},__wbindgen_cast_0000000000000003:function(e,t){let n=be(e,t,tc);return R(n)},__wbindgen_cast_0000000000000004:function(e,t){let n=be(e,t,nc);return R(n)},__wbindgen_cast_0000000000000005:function(e,t){let n=be(e,t,Va);return R(n)},__wbindgen_cast_0000000000000006:function(e,t){let n=be(e,t,Ya);return R(n)},__wbindgen_cast_0000000000000007:function(e,t){let n=be(e,t,Ja);return R(n)},__wbindgen_cast_0000000000000008:function(e,t){let n=gc(e,t,Xa);return R(n)},__wbindgen_cast_0000000000000009:function(e,t){let n=be(e,t,Za);return R(n)},__wbindgen_cast_000000000000000a:function(e){return R(e)},__wbindgen_cast_000000000000000b:function(e){return R(e)},__wbindgen_cast_000000000000000c:function(e,t){let n=Ne(e,t);return R(n)},__wbindgen_cast_000000000000000d:function(e,t){let n=$(e,t);return R(n)},__wbindgen_cast_000000000000000e:function(e){let t=BigInt.asUintN(64,e);return R(t)},__wbindgen_cast_000000000000000f:function(e,t){var n=Ne(e,t).slice();return d.__wbindgen_export4(e,t*1,1),R(n)},__wbindgen_object_clone_ref:function(e){let t=f(e);return R(t)},__wbindgen_object_drop_ref:function(e){P(e);}}}}function Va(r,e){d.__wasm_bindgen_func_elem_5255(r,e);}function Ya(r,e){d.__wasm_bindgen_func_elem_9678(r,e);}function Ja(r,e){d.__wasm_bindgen_func_elem_10808(r,e);}function Xa(r,e){d.__wasm_bindgen_func_elem_10883(r,e);}function Za(r,e){d.__wasm_bindgen_func_elem_18452(r,e);}function ec(r,e,t){d.__wasm_bindgen_func_elem_9880(r,e,R(t));}function tc(r,e,t){d.__wasm_bindgen_func_elem_7356(r,e,R(t));}function nc(r,e,t){d.__wasm_bindgen_func_elem_11522(r,e,R(t));}function ic(r,e,t){try{let o=d.__wbindgen_add_to_stack_pointer(-16);d.__wasm_bindgen_func_elem_18598(o,r,e,R(t));var n=M().getInt32(o+0,!0),i=M().getInt32(o+4,!0);if(i)throw P(n)}finally{d.__wbindgen_add_to_stack_pointer(16);}}function oc(r,e,t,n){d.__wasm_bindgen_func_elem_18600(r,e,R(t),R(n));}var rc=["blob","arraybuffer"],ac=["default","no-store","reload","no-cache","force-cache","only-if-cached"],cc=["omit","same-origin","include"],lc=["same-origin","no-cors","cors","navigate"],ts=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(r=>d.__wbg_bistream_free(r,1));typeof FinalizationRegistry>"u"?{}:new FinalizationRegistry(r=>d.__wbg_intounderlyingbytesource_free(r,1));var ns=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(r=>d.__wbg_intounderlyingsink_free(r,1)),is=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(r=>d.__wbg_intounderlyingsource_free(r,1)),os=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(r=>d.__wbg_peerunistream_free(r,1)),ji=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(r=>d.__wbg_wasmclient_free(r,1));typeof FinalizationRegistry>"u"?{}:new FinalizationRegistry(r=>d.__wbg_wasmconnection_free(r,1));function R(r){st===fe.length&&fe.push(fe.length+1);let e=st;return st=fe[e],fe[e]=r,e}var An=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(r=>d.__wbindgen_export5(r.a,r.b));function qi(r){let e=typeof r;if(e=="number"||e=="boolean"||r==null)return `${r}`;if(e=="string")return `"${r}"`;if(e=="symbol"){let i=r.description;return i==null?"Symbol":`Symbol(${i})`}if(e=="function"){let i=r.name;return typeof i=="string"&&i.length>0?`Function(${i})`:"Function"}if(Array.isArray(r)){let i=r.length,o="[";i>0&&(o+=qi(r[0]));for(let s=1;s<i;s++)o+=", "+qi(r[s]);return o+="]",o}let t=/\[object ([^\]]+)\]/.exec(toString.call(r)),n;if(t&&t.length>1)n=t[1];else return toString.call(r);if(n=="Object")try{return "Object("+JSON.stringify(r)+")"}catch{return "Object"}return r instanceof Error?`${r.name}: ${r.message}
3
+ ${r.stack}`:n}function pc(r){r<1028||(fe[r]=st,st=r);}function uc(r,e){r=r>>>0;let t=M(),n=[];for(let i=r;i<r+4*e;i+=4)n.push(P(t.getUint32(i,true)));return n}function Ne(r,e){return r=r>>>0,Oe().subarray(r/1,r/1+e)}var De=null;function M(){return (De===null||De.buffer.detached===true||De.buffer.detached===void 0&&De.buffer!==d.memory.buffer)&&(De=new DataView(d.memory.buffer)),De}function $(r,e){return mc(r>>>0,e)}var rt=null;function Oe(){return (rt===null||rt.byteLength===0)&&(rt=new Uint8Array(d.memory.buffer)),rt}function f(r){return fe[r]}function H(r,e){try{return r.apply(this,e)}catch(t){d.__wbindgen_export3(R(t));}}var fe=new Array(1024).fill(void 0);fe.push(void 0,null,true,false);var st=fe.length;function x(r){return r==null}function gc(r,e,t){let n={a:r,b:e,cnt:1},i=(...o)=>{n.cnt++;try{return t(n.a,n.b,...o)}finally{i._wbg_cb_unref();}};return i._wbg_cb_unref=()=>{--n.cnt===0&&(d.__wbindgen_export5(n.a,n.b),n.a=0,An.unregister(n));},An.register(i,n,n),i}function be(r,e,t){let n={a:r,b:e,cnt:1},i=(...o)=>{n.cnt++;let s=n.a;n.a=0;try{return t(s,n.b,...o)}finally{n.a=s,i._wbg_cb_unref();}};return i._wbg_cb_unref=()=>{--n.cnt===0&&(d.__wbindgen_export5(n.a,n.b),n.a=0,An.unregister(n));},An.register(i,n,n),i}function Pn(r,e){let t=e(r.length*1,1)>>>0;return Oe().set(r,t/1),C=r.length,t}function ss(r,e){let t=e(r.length*4,4)>>>0,n=M();for(let i=0;i<r.length;i++)n.setUint32(t+4*i,R(r[i]),true);return C=r.length,t}function b(r,e,t){if(t===void 0){let a=at.encode(r),c=e(a.length,1)>>>0;return Oe().subarray(c,c+a.length).set(a),C=a.length,c}let n=r.length,i=e(n,1)>>>0,o=Oe(),s=0;for(;s<n;s++){let a=r.charCodeAt(s);if(a>127)break;o[i+s]=a;}if(s!==n){s!==0&&(r=r.slice(s)),i=t(i,n,n=s+r.length*3,1)>>>0;let a=Oe().subarray(i+s,i+n),c=at.encodeInto(r,a);s+=c.written,i=t(i,n,s,1)>>>0;}return C=s,i}function P(r){let e=f(r);return pc(r),e}var _n=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true});_n.decode();var hc=2146435072,Gi=0;function mc(r,e){return Gi+=e,Gi>=hc&&(_n=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true}),_n.decode(),Gi=e),_n.decode(Oe().subarray(r,r+e))}var at=new TextEncoder;"encodeInto"in at||(at.encodeInto=function(r,e){let t=at.encode(r);return e.set(t),{read:r.length,written:t.length}});var C=0,d;function vc(r,e){return d=r.exports,De=null,rt=null,d.__wbindgen_start(),d}async function Cc(r,e){if(typeof Response=="function"&&r instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(r,e)}catch(i){if(r.ok&&t(r.type)&&r.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",i);else throw i}let n=await r.arrayBuffer();return await WebAssembly.instantiate(n,e)}else {let n=await WebAssembly.instantiate(r,e);return n instanceof WebAssembly.Instance?{instance:n,module:r}:n}function t(n){switch(n){case "basic":case "cors":case "default":return true}return false}}async function cs(r){if(d!==void 0)return d;r!==void 0&&(Object.getPrototypeOf(r)===Object.prototype?{module_or_path:r}=r:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),r===void 0&&(r=new URL("openrtc_bg.wasm",import.meta.url));let e=$a();(typeof r=="string"||typeof Request=="function"&&r instanceof Request||typeof URL=="function"&&r instanceof URL)&&(r=fetch(r));let{instance:t,module:n}=await Cc(await r,e);return vc(t)}function bc(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}function Sc(r){let t=(Array.isArray(r.urls)?r.urls:[r.urls]).filter(n=>typeof n=="string"&&!n.startsWith("stun:"));return t.length===0?null:{...r,urls:Array.isArray(r.urls)?t:t[0]}}function ls(r){if(r)return r.map(e=>Sc(e)).filter(e=>e!==null)}async function ds(r,e,t){for(let n=0;n<e;n+=1){if(await r().catch(()=>false))return true;n<e-1&&await u(t);}return false}function Ki(r){return !!r?.signaling?.nativeIpc&&r?.transport?.wasm===false&&r?.fallback?.wasm===false}var kn=class{constructor(e){this.host=e;this.wasmLoaded=false;this.initPromise=null;this.initPendingTimer=null;this.disposed=false;this.host.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true,this.initPromise=null,this.clearInitPendingTimer();}clearInitPendingTimer(){this.initPendingTimer&&(clearInterval(this.initPendingTimer),this.initPendingTimer=null);}async bootstrapRuntime(e){let t=e.initializeClient??true;if(e.platform==="web")return await e.initializeWeb?.(),t&&await this.init(),{ready:true,mode:"web"};let n=e.quickPollAttempts??5,i=e.quickPollIntervalMs??300,o=e.retryPollAttempts??8,s=e.retryPollIntervalMs??300,a=e.nativeInitEventTimeoutMs??4e3;if(!e.isNativeReady)return console.warn("[Client][INIT] No isNativeReady callback provided for native platform; treating runtime as not ready"),{ready:false,mode:"native"};if(!await ds(e.isNativeReady,n,i)){await e.retryNativeInit?.();let[l,p]=await Promise.all([e.waitForNativeInitEvent?.(a)??Promise.resolve(false),ds(e.isNativeReady,o,s)]);if(!(l||p))return {ready:false,mode:"native"}}return t&&await this.init(),{ready:true,mode:"native"}}async init(){if(!this.disposed){if(this.initPromise)return this.initPromise;if(!(this.wasmLoaded&&this.host.wasmClient&&this.host.localNodeId)){if(this.usesNativeIpcRuntimeWithoutWasmFallback())throw this.nativeWasmInitForbiddenError("Client.init()");return this.initPromise=(async()=>{try{if(d$2("[Client][INIT] Loading WASM module..."),await cs(bc()),this.disposed)return;as(),this.wasmLoaded=!0,d$2("[Client][INIT] WASM module loaded");let e=e$2(this.host.options),t=typeof this.host.options.apiKey=="string"?this.host.options.apiKey.trim():"",n=typeof this.host.options.spaceKey=="string"?this.host.options.spaceKey.trim():"",i=(this.host.options.discoveryMode===void 0||this.host.options.discoveryMode==="space")&&!!t&&!!n,o=c$3(this.host.options);if(i){let g=await b$3(t,n);if(this.disposed)return;o=`space::${g}`,d$2(`[Client][INIT] space mode: WASM rooms routed to spaces/${g.slice(0,8)}...`);}if(this.disposed)return;this.host.setEffectiveRoomBackendTag(o);let s=new He(e,o);if(this.disposed)return;if(this.host.setWasmClient(s),d$2("PlutoRTC WASM Core Initialized"),this.host.setSignalingWasmClient(s),this.host.installAppLifecycleListeners(),!this.host.usesTicketOnlySignalingMode()){if(await this.host.ensureAuthenticated("init"),this.disposed||(await this.host.syncAuthTokenToWasm("init"),this.disposed))return;this.host.installAuthTokenSync();}let a=`iroh_secret_key_${f$3(this.host.options)}`,c=this.resolveIrohPersistenceMode(),l=await this.resolveIrohSecretKeyBytes(a,c);if(this.disposed||(this.host.setDeviceId(await this.host.getLocalDeviceId().catch(()=>null)),this.disposed))return;let p=Date.now();d$2(`[Client][INIT][IROH] start persistence=${c} hasSecretKey=${!!l} secretKeyLen=${l?.length||0} hasStoredDeviceId=${!!this.host.deviceId}`),this.clearInitPendingTimer(),this.initPendingTimer=setInterval(()=>{let g=Date.now()-p;console.warn(`[Client][INIT][IROH] pending elapsedMs=${g} hasWasmClient=${!!this.host.wasmClient}`);},5e3);let u="";try{u=await E(s.init_iroh(l),2e4);}catch(g){let y=Date.now()-p;throw new Error(`[Client] init_iroh stalled or failed: ${g?.message||g}; elapsed_ms=${y}; persistence=${c}; has_secret_key=${!!l}`)}finally{this.clearInitPendingTimer();}if(this.disposed)return;if(d$2(`[Client][INIT][IROH] complete elapsedMs=${Date.now()-p} nodeId=${u}`),!u)throw new Error("[Client] init_iroh returned empty node id");if(this.host.setLocalNodeId(u),this.host.deviceId||this.host.setDeviceId(await this.host.getLocalDeviceId().catch(()=>null)),this.disposed||(this.host.setNode({initialized:!0,localNodeId:u}),c==="persistent"&&!this.host.options.secretKey&&(await this.persistCurrentIrohSecret(a,l,u),this.disposed)))return;if(this.host.options.transports?.moq)try{Promise.resolve(this.host.initMoQ()).catch(g=>{this.disposed||c$1("[Client][INIT] MoQ startup handoff failed",g);});}catch(g){if(this.disposed)return;c$1("[Client][INIT] MoQ startup handoff failed",g);}if(await this.configureWebRtcIceServers(),this.disposed)return;this.host.isWebRTCTransportEnabled()&&this.broadcastWebRtcReadyCapabilityInBackground();}catch(e){throw console.error("Failed to initialize PlutoRTC:",e),this.initPromise=null,e}})(),this.initPromise}}}broadcastWebRtcReadyCapabilityInBackground(){try{Promise.resolve(this.host.broadcastTransportCapabilityUpdate("webrtc-ready")).catch(e=>{this.disposed||c$1("[Client] Late WebRTC capability update failed",e);});}catch(e){if(this.disposed)return;c$1("[Client] Late WebRTC capability update failed",e);}}async recoverLocalIrohRuntime(e){if(this.disposed)return false;let t=this.host.wasmClient;if(!t||typeof t.init_iroh!="function")return false;try{let n=`iroh_secret_key_${f$3(this.host.options)}`,i=this.resolveIrohPersistenceMode(),o=await this.resolveIrohSecretKeyBytes(n,i);c$1("[Client][CONNECT] recovering local Iroh runtime",{reason:e,hadLocalNodeId:!!this.host.localNodeId,nodeInitialized:!!this.host.node?.initialized,persistenceMode:i,hasSecretKey:!!o});let s=await E(t.init_iroh(o),2e4);return this.disposed||typeof s!="string"||!s?!1:(this.host.setLocalNodeId(s),this.host.setNode({initialized:!0,localNodeId:s}),i==="persistent"&&!this.host.options.secretKey&&await this.persistCurrentIrohSecret(n,o,s),!0)}catch(n){return c$1("[Client][CONNECT] local Iroh runtime recovery failed",{reason:e,error:n instanceof Error?n.message:String(n)}),false}}usesNativeIpcRuntimeWithoutWasmFallback(){return Ki(this.host.getRuntimeCapabilities())}nativeWasmInitForbiddenError(e){let t=this.host.getRuntimeCapabilities(),n=`[Client][NATIVE-GUARD] Refusing WASM runtime init during ${e}. This OpenRTC client is using the native IPC runtime with WASM fallback disabled; desktop/Tauri must initialize Iroh through the Rust backend only.`;return console.error(n,{capabilities:t}),new Error(n)}async resolveIrohSecretKeyBytes(e,t){if(this.host.options.secretKey){let o=this.host.options.secretKey.match(/.{1,2}/g);return o?new Uint8Array(o.map(s=>parseInt(s,16))):void 0}if(t!=="persistent")return;let i=(await this.loadPersistedIrohSecretHex(e))?.match(/.{1,2}/g);return i?new Uint8Array(i.map(o=>parseInt(o,16))):void 0}async persistCurrentIrohSecret(e,t,n){let i=t??(typeof this.host.wasmClient?.iroh_secret_key=="function"?await this.host.wasmClient.iroh_secret_key().catch(()=>{}):void 0);if(i&&i.length>0){let o=Array.from(i).map(s=>Number(s).toString(16).padStart(2,"0")).join("");await this.persistIrohSecretHex(e,o),d$2(`[Client][INIT][IROH] persisted secret key bytes=${i.length} nodeId=${n}`);}else console.warn(`[Client][INIT][IROH] unable to persist secret key for nodeId=${n}`);}resolveIrohPersistenceMode(){return this.host.options.endpointIdPersistence??this.host.options.nodeIdPersistence??(typeof this.host.options.transports?.iroh=="object"?this.host.options.transports.iroh.persistenceMode:void 0)??"ephemeral"}getTauriInvoke(){if(typeof window>"u")return null;let e=window.__TAURI_INTERNALS__;return !e||typeof e.invoke!="function"?null:e.invoke.bind(e)}async loadPersistedIrohSecretHex(e){let t=a$3()?this.getTauriInvoke():null;if(t){let n=await t("openrtc_load_iroh_secret",{namespaceKey:e}).catch(()=>null);if(typeof n=="string"&&n.trim().length>0)return n.trim()}if(typeof sessionStorage<"u"){let n=sessionStorage.getItem(e);if(n)return n}if(typeof localStorage<"u"){let n=localStorage.getItem(e);if(n)return typeof sessionStorage<"u"&&sessionStorage.setItem(e,n),localStorage.removeItem(e),n}return null}async persistIrohSecretHex(e,t){let n=a$3()?this.getTauriInvoke():null;if(n){await n("openrtc_save_iroh_secret",{namespaceKey:e,secretHex:t}),typeof localStorage<"u"&&localStorage.removeItem(e);return}typeof sessionStorage<"u"&&sessionStorage.setItem(e,t),typeof localStorage<"u"&&localStorage.removeItem(e);}async getTurnCredentialsForTransportConfig(){return typeof this.host.options.turnCredentialsProvider=="function"?await this.host.options.turnCredentialsProvider()??null:await this.host.getTurnCredentials()??null}async configureWebRtcIceServers(){let e=this.host.options.transports?.webrtc;if(!!e&&(e.useTurn===true||e.privacyMode===true||this.host.options.strictMode===true))try{let n=await this.getTurnCredentialsForTransportConfig();if(this.disposed)return;if(n&&n.iceServers){let i=Array.isArray(n.iceServers)?n.iceServers:[n.iceServers];e?.privacyMode||this.host.options.strictMode?(i=ls(i)??[],d$2(`[Client] Strict / Privacy Mode: Filtered STUN servers. Remaining=${i.length}`)):d$2(`[Client] Automatically fetched ${i.length} TURN servers.`),this.host.options.transports||(this.host.options.transports={}),this.host.options.transports.webrtc||(this.host.options.transports.webrtc={});let o=this.host.options.transports.webrtc||i$1;o.iceServers||(o.iceServers=[]),(this.host.options.strictMode||o.privacyMode)&&(o.iceServers=ls(o.iceServers)??[]),o.iceServers.push(...i);}}catch(n){console.warn("[Client] Failed to auto-fetch TURN credentials:",n);}if(!this.host.options.strictMode&&!e?.privacyMode){if(this.disposed)return;let n=this.host.options.transports?.webrtc;n&&n.useDefaultIceServers!==false&&(!n.iceServers||Array.isArray(n.iceServers)&&n.iceServers.length===0)&&(d$2("[Client] No ICE servers provided. Using default public STUN servers."),n.iceServers=[...h$2]);}}};var Nn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Runtime connection service is disposed")}async connectRaw(e,t=2e4){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let n=await this.deps.ensureWasmManagedTransport(e,null,{timeoutMs:t});return this.assertActive(),{connectionId:n.connectionId,localNodeId:this.ctx.localNodeId??"",remoteNodeId:n.remoteNodeId??n.deviceId??""}}async startAutoConnect(e){if(this.disposed||(await this.deps.ensureSignalingReadyForDiscovery("watch"),this.disposed))return;let t=this.deps.getCurrentUserId();if(!t)throw new Error("startAutoConnect requires an authenticated user");let n=e||await this.deps.getLocalDeviceId()||this.deps.getFallbackDeviceId();if(!this.disposed){if(!n)throw new Error("startAutoConnect requires a local device identity");this.deps.startAutoConnect(t,n);}}async isConnected(e){if(this.disposed||(await this.deps.ensureWasmRuntimeForP2P(),this.disposed)||!e||!e.trim())return false;let t=this.ctx.wasmClient;if(t&&typeof t.is_connected=="function"){let i=await t.is_connected(e);if(this.disposed)return false;if(i)return true}let n=await this.deps.isConnected(e);return this.disposed?false:!!n}async disconnectNode(e){if(this.disposed||!e||!e.trim())return;let t=Array.from(this.ctx.registry.values()).filter(n=>n.deviceId===e);await Promise.allSettled(t.map(n=>this.disconnectConnectionBestEffort(n))),!this.disposed&&await this.deps.disconnectNodeTransport(e);}disconnectNodeBestEffort(e){try{this.disconnectNode(e).catch(()=>{});}catch{}}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}};var Dn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Runtime identity service is disposed")}async getTicket(){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let e=await d$3(()=>this.ctx.wasmClient.endpoint_ticket(),{isActive:()=>!this.disposed});return this.assertActive(),e}async getNodeId(){return this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive(),this.ctx.localNodeId??""}async getNodeIdFromTicket(e){if(this.disposed)return null;let t=e.trim();if(!t)return null;let{irohTicket:n}=se(t),i=this.ctx.wasmClient;if(!i||typeof i.endpoint_id_from_ticket!="function")return null;try{let o=await i.endpoint_id_from_ticket(n);return this.disposed?null:o}catch{return null}}};var Mn=class{constructor(e,t){this.ctx=e;this.deps=t;this.loggedNativeDiscoveryWasmSkip=false;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Runtime readiness service is disposed")}async ensureWasmRuntimeForP2P(){if(this.assertActive(),!(this.ctx.wasmClient&&this.ctx.localNodeId)&&(await this.deps.init(),this.assertActive(),!this.ctx.wasmClient||!this.ctx.localNodeId))throw new Error("Node not initialized")}async ensureSignalingReadyForDiscovery(e){if(this.disposed||this.deps.usesTicketOnlySignalingMode())return;let t=this.deps.usesNativeIpcRuntimeWithoutWasmFallback();if(!this.deps.getWasmLoaded()&&t)this.loggedNativeDiscoveryWasmSkip||(this.loggedNativeDiscoveryWasmSkip=true,c$1(`[Client][NATIVE-GUARD] Discovery ${e} is using native IPC readiness; skipped WASM init.`));else if(!this.deps.getWasmLoaded()&&!(this.ctx.wasmClient&&this.ctx.localNodeId)&&(await this.deps.init(),this.disposed))return;try{await this.deps.ensureAuthenticated("discovery");}catch(n){console.warn(`[Client][AUTH] ensureAuthenticated failed for ${e}:`,n);}if(!this.disposed)try{this.ctx.wasmClient&&await this.deps.syncAuthTokenToWasm("auth-change");}catch(n){console.warn(`[Client][WASM-AUTH] Token sync failed for ${e}:`,n);}}};var Ic={scheduled:0,coalesced:0,ran:0,orphanTsConnection:0,orphanRustRecord:0,orphanTsConnectionHealed:0},En=class{constructor(e){this.deps=e;}usesTicketOnlySignalingMode(){return (this.deps.getOptions()?.signalingMode??"hosted")==="ticket-only"}usesDirectRoomBackend(){let e=this.deps.getOptions();return this.getRoomBackendTag().startsWith("space::")||(e.discoveryMode===void 0||e.discoveryMode==="space")&&typeof e.spaceKey=="string"&&e.spaceKey.trim().length>0}getRoomBackendTag(){return this.deps.getEffectiveRoomBackendTag()}requiresManagedTransportTrust(e){return !this.usesTicketOnlySignalingMode()&&!this.usesDirectRoomBackend()&&e!=="space"&&!!this.deps.getSignalingCurrentUser()?.id}getSignalingTelemetry(){return {transport:"runtime-bridge",wasmLoaded:this.deps.getWasmLoaded(),peerReconciliation:this.getPeerReconciliationStats()}}getPeerReconciliationStats(){return this.deps.getPeerReconciliationStats()??Ic}getProtocolCapabilities(){let e=Ce.getProtocolCapabilities(),t=this.deps.getRuntimeCapabilities(),n=this.deps.getOptions().transports,i=n?.iroh!==false,o=!!n?.webrtc,s=n?.ble===true||typeof n?.ble=="object"&&n.ble.enabled!==false,a=typeof n?.moq=="object"&&typeof n.moq.relayUrl=="string"&&n.moq.relayUrl.trim().length>0;for(let l of Object.values(e)){if(l.routeImplementation==="path-label"){l.configured=void 0;continue}l.configured=l.baseProtocol==="iroh"?i:l.baseProtocol==="webrtc"?o:a;}e.ble.configured=s;let c=(l,p,u)=>{e[l].configured=p,e[l].available=p&&u,p?u||(e[l].reason=`The running host did not report '${l}' as available.`):e[l].reason=`Protocol '${l}' is not enabled in ClientOptions.transports.`;};return c("iroh",i,t?.transport.irohQuic===true),c("webrtc",o,t?.transport.webRtcUpgrade===true||t?.transport.nativeWebRtc===true),c("moq",a,t?.transport.moq===true),e.ble.available=s&&t?.transport.ble===true,s?t?.transport.ble!==true&&(e.ble.reason="The running host did not report 'ble' as compiled and enabled."):e.ble.reason="Protocol 'ble' is not enabled in ClientOptions.transports.",e}async getRuntimeStatus(){let e="unknown";return typeof window<"u"&&(e=window.__TAURI__?"tauri":"browser"),{runtime:e,wasmLoaded:this.deps.getWasmLoaded(),localNodeId:this.deps.getLocalNodeId()||void 0,userId:this.deps.getSignalingCurrentUser()?.id??void 0}}};function ps(r){let{host:e}=r;return new kn({get options(){return e.getOptions()},get wasmClient(){return e.getWasmClient()},get node(){return e.getNode()},get localNodeId(){return e.getLocalNodeId()},get deviceId(){return e.getDeviceId()},setWasmClient:t=>e.setWasmClient(t),setSignalingWasmClient:t=>e.setSignalingWasmClient(t),setNode:t=>e.setNode(t),setLocalNodeId:t=>e.setLocalNodeId(t),setDeviceId:t=>e.setDeviceId(t),setEffectiveRoomBackendTag:t=>e.setEffectiveRoomBackendTag(t),usesTicketOnlySignalingMode:()=>r.getStatus().usesTicketOnlySignalingMode(),ensureAuthenticated:t=>e.ensureAuthenticated(t),syncAuthTokenToWasm:(t,n)=>e.syncAuthTokenToWasm(t,n),installAuthTokenSync:()=>e.installAuthTokenSync(),installAppLifecycleListeners:()=>r.getAppLifecycle().installListeners(),initMoQ:()=>e.initMoQ(),isWebRTCTransportEnabled:()=>e.isWebRTCTransportEnabled(),getLocalDeviceId:()=>e.getLocalDeviceId(),getTurnCredentials:()=>e.getTurnCredentials(),getRuntimeCapabilities:()=>e.getRuntimeCapabilities(),broadcastTransportCapabilityUpdate:t=>e.broadcastTransportCapabilityUpdate(t),registerDisposer:t=>e.registerDisposer(t)})}function us(r){let{host:e}=r;return new Nn(e.getContext(),{ensureWasmRuntimeForP2P:()=>r.getReadiness().ensureWasmRuntimeForP2P(),ensureSignalingReadyForDiscovery:t=>r.getReadiness().ensureSignalingReadyForDiscovery(t),ensureWasmManagedTransport:(t,n,i)=>r.getManagedDialer().ensureWasmManagedTransport(t,n,i),getCurrentUserId:()=>e.getCurrentUserId(),getLocalDeviceId:()=>e.getLocalDeviceId(),getFallbackDeviceId:()=>e.getDeviceId(),startAutoConnect:(t,n)=>e.startAutoConnect(t,n),isConnected:t=>e.isConnected(t),disconnectNodeTransport:t=>e.disconnectNodeTransport(t)})}function gs(r){return new Rn(r.getContext(),{getDeterministicConnectionId:e=>r.getDeterministicConnectionId(e),getApprovedScope:e=>r.getApprovedScope(e),getLocalDeviceId:()=>r.getLocalDeviceId(),getFallbackLocalDeviceId:()=>r.getDeviceId()??r.getOptions().localDeviceId??null,rememberRouteRepairTokenForNode:(e,t,n)=>r.rememberRouteRepairTokenForNode(e,t,n),getRouteRepairTokenForNode:e=>r.getRouteRepairTokenForNode?.(e),getRouteRepairTokenPayloadForNode:e=>r.getRouteRepairTokenPayloadForNode?.(e)})}function hs(r){return new Dn(r.host.getContext(),{ensureWasmRuntimeForP2P:()=>r.getReadiness().ensureWasmRuntimeForP2P()})}function ms(r){let{host:e}=r;return new Mn(e.getContext(),{init:()=>r.getBootstrap().init(),usesTicketOnlySignalingMode:()=>r.getStatus().usesTicketOnlySignalingMode(),usesNativeIpcRuntimeWithoutWasmFallback:()=>Ki(e.getRuntimeCapabilities()),getWasmLoaded:()=>r.getBootstrapWasmLoaded(),ensureAuthenticated:t=>e.ensureAuthenticated(t),syncAuthTokenToWasm:t=>e.syncAuthTokenToWasm(t)})}function fs(r){let{host:e}=r;return new En({getEffectiveRoomBackendTag:()=>e.getEffectiveRoomBackendTag(),getLocalNodeId:()=>e.getLocalNodeId(),getOptions:()=>e.getOptions(),getPeerReconciliationStats:()=>e.getPeerReconciliationStats(),getRuntimeCapabilities:()=>e.getRuntimeCapabilities(),getSignalingCurrentUser:()=>({id:e.getCurrentUserId()}),getWasmLoaded:()=>r.getBootstrapWasmLoaded()})}function ys(r){return new In(r.getContext())}function vs(r){return new zi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getWasmClient:()=>r.wasmClient,setWasmClient:e=>{r.wasmClient=e;},getNode:()=>r.node,setNode:e=>{r.node=e;},getLocalNodeId:()=>r.localNodeId,setLocalNodeId:e=>{r.localNodeId=e;},getDeviceId:()=>r.deviceId,setDeviceId:e=>{r.deviceId=e;},setEffectiveRoomBackendTag:e=>{r.setEffectiveRoomBackendTag(e);},getEffectiveRoomBackendTag:()=>r.getEffectiveRoomBackendTag(),getPeerReconciliationStats:()=>r.getExistingPeerReconciliationStats(),getCurrentUserId:()=>r.signalingBackendController.getCurrentUser()?.id??null,getRuntimeCapabilities:()=>r.signalingBackendController.getRuntimeCapabilities(),getLocalDeviceId:()=>r.signalingBackendController.getLocalDeviceId(),getTurnCredentials:()=>r.signalingBackendController.getTurnCredentials(),setSignalingWasmClient:e=>r.signalingBackendController.setWasmClient(e),startAutoConnect:(e,t)=>r.signalingBackendController.startAutoConnect(e,t),isConnected:e=>r.signalingBackendController.isConnected(e),disconnectNodeTransport:e=>r.transportHealth.disconnectNodeTransport(e),getDeterministicConnectionId:e=>r.peerIdentity.getDeterministicConnectionId(e),getApprovedScope:e=>r.sessionTokens.getApprovedScope(e),rememberRouteRepairTokenForNode:(e,t,n)=>r.sessionTokens.rememberRouteRepairTokenForNode(e,t,n),getRouteRepairTokenForNode:e=>r.sessionTokens.getRouteRepairTokenForNode(e),getRouteRepairTokenPayloadForNode:e=>r.sessionTokens.getRouteRepairTokenPayloadForNode(e),ensureAuthenticated:e=>r.auth.ensureAuthenticated(e),syncAuthTokenToWasm:(e,t)=>r.auth.syncAuthTokenToWasm(e,t),installAuthTokenSync:()=>r.auth.installAuthTokenSync(),initMoQ:()=>r.moqServices.init(),isWebRTCTransportEnabled:()=>k(r.options),broadcastTransportCapabilityUpdate:e=>r.transportHandshake.broadcastTransportCapabilityUpdate(e),registerDisposer:e=>r.lifecycleScope.register(e)})}var zi=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getBootstrap:()=>this.bootstrap,getBootstrapWasmLoaded:()=>this._bootstrap?.wasmLoaded??false,getManagedDialer:()=>this.managedDialer,getReadiness:()=>this.readiness,getStatus:()=>this.status,getAppLifecycle:()=>this.appLifecycle}}get bootstrap(){return this._bootstrap??(this._bootstrap=ps(this.factoryHost))}get connections(){return this._connections??(this._connections=us(this.factoryHost))}get managedDialer(){return this._managedDialer??(this._managedDialer=gs(this.host))}get identity(){return this._identity??(this._identity=hs(this.factoryHost))}get readiness(){return this._readiness??(this._readiness=ms(this.factoryHost))}get status(){return this._status??(this._status=fs(this.factoryHost))}get appLifecycle(){return this._appLifecycle??(this._appLifecycle=ys(this.host))}};var xn=class{constructor(e,t){this.ctx=e;this.deps=t;this.connectionKeyAgreementById=new Map;this.connectionKeyAgreementRemotePublicById=new Map;this.negotiatedByConnectionId=new Map;this.negotiatedByPeerId=new Map;this.negotiatedFingerprintByCrypto=new WeakMap;this.waiters=[];this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}getApplicationCrypto(e){return e?this.deps.getConfiguredApplicationCrypto()??this.negotiatedByConnectionId.get(e.id):this.deps.getConfiguredApplicationCrypto()}getNegotiatedForPeer(e){let t=typeof e=="string"?e.trim():"";if(!t)return;let n=Array.from(this.ctx.registry.values()).reverse().find(l=>!l.isClosed&&(l.id===t||l.remoteNodeId===t));if(n)return this.negotiatedByConnectionId.get(n.id);let i=this.deps.getKnownDeviceNodeId(t),o=[this.deps.getPeerState(t),i?this.deps.getPeerState(i):void 0].filter(l=>!!l);for(let l of o){let p=l.connectionId?.trim();if(p)return this.negotiatedByConnectionId.get(p);for(let u of [...l.connectionIds??[]].reverse()){let g=u?.trim();if(!g)continue;let y=this.negotiatedByConnectionId.get(g);if(y)return y}}let a=Array.from(this.ctx.registry.values()).filter(l=>{let p=this.deps.getKnownDeviceIdForNode(l.remoteNodeId);return l.id===t||l.remoteNodeId===t||l.deviceId===t||i&&l.remoteNodeId===i||p===t}).filter(l=>!l.isClosed).reverse(),c=a.find(l=>l.id===t||l.remoteNodeId===t)??a.find(l=>!!i&&l.remoteNodeId===i)??a[0];return c?this.negotiatedByConnectionId.get(c.id):this.negotiatedByPeerId.get(t)}resolveForPeer(e,t){let n=this.deps.getConfiguredApplicationCrypto();if(n)return n;if(t)return this.negotiatedByConnectionId.get(t.id);if(e)return this.getNegotiatedForPeer(e)}waitForPeer(e,t=1e4){let n=this.resolveForPeer(e);return n||!e||t<=0||this.disposed?Promise.resolve(n):new Promise(i=>{let o={peerId:e,resolve:i,timer:setTimeout(()=>{this.waiters=this.waiters.filter(s=>s!==o),i(void 0);},t)};this.waiters.push(o);})}dispose(){if(this.disposed)return;this.disposed=true;let e=this.waiters.splice(0);for(let t of e)clearTimeout(t.timer),t.resolve(void 0);this.connectionKeyAgreementById.clear(),this.connectionKeyAgreementRemotePublicById.clear(),this.negotiatedByConnectionId.clear(),this.negotiatedByPeerId.clear();}clearConnection(e){let t=this.negotiatedByConnectionId.get(e),n=this.wasmClient;try{n?.clearConnectionApplicationCryptoKey?.(e);}catch(i){console.warn("[Client][KEY-AGREEMENT] Failed to retire native application crypto",{connectionId:e,error:i});}if(this.connectionKeyAgreementById.delete(e),this.connectionKeyAgreementRemotePublicById.delete(e),this.negotiatedByConnectionId.delete(e),!(!t||Array.from(this.negotiatedByConnectionId.values()).includes(t)))for(let[i,o]of this.negotiatedByPeerId)o===t&&this.negotiatedByPeerId.delete(i);}notifyWaiters(){if(this.waiters.length===0)return;let e=[];for(let t of this.waiters){let n=this.resolveForPeer(t.peerId);if(!n){e.push(t);continue}clearTimeout(t.timer),t.resolve(n);}this.waiters=e;}resolveStreamTools(e,t){let n=this.resolveForPeer(e,t);return n&&c$1("[Client][KEY-AGREEMENT] Resolved application stream crypto",{peerId:e??null,connectionId:t?.id??null,keyFingerprint:this.negotiatedFingerprintByCrypto.get(n)??"configured"}),n?n$1(n):void 0}shouldNegotiateKeyAgreement(){if(this.deps.getConfiguredApplicationCrypto())return false;if(this.deps.getAutomaticApplicationKeyAgreement()===false)throw new Error("[OpenRTC] automaticApplicationKeyAgreement cannot be disabled; configure applicationCrypto only for explicit pre-shared-key mode");return true}async ensureConnectionKeyAgreementState(e){let t=this.connectionKeyAgreementById.get(e.id);if(t)return t;let n=Wo();return this.connectionKeyAgreementById.set(e.id,n),n}async handleKeyAgreement(e,t){if(!this.shouldNegotiateKeyAgreement())return {remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null};await this.ensureConnectionKeyAgreementState(e);let n=Uo(t.applicationKeyAgreement),i=t.capabilities?.applicationKeyAgreement===true||!!n;if(!n||!i||!this.ctx.localNodeId){if((typeof e.getControlFrameMode=="function"?e.getControlFrameMode():"typed")==="native-main"&&!i&&!n)return {remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null};throw new Error("Peer does not support mandatory application key agreement")}let o=this.connectionKeyAgreementById.get(e.id);if(!o)return {remotePublicChanged:false,cryptoReady:false,replyAction:null,replyClaimId:null};let s=t.applicationKeyAgreement?.publicKey?.trim()??"",a=Ye(n),c=this.connectionKeyAgreementRemotePublicById.get(e.id)??null,l=!!s&&c!==s;e.markApplicationKeyAgreementObserved();let p=this.negotiatedByConnectionId.get(e.id);if(p&&s&&c===s){e.setApplicationCrypto(p);let S=this.ctx.registry.get(e.id);S&&S!==e&&!S.isClosed&&S.setApplicationCrypto(p),this.deps.notifyApplicationRouteReady(e,`key-agreement:${t.action??"hello"}:unchanged`),c$1("[Client][KEY-AGREEMENT] Reused unchanged application crypto",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t.action??"hello"});let I=this.claimReplyAction(e.id,t.action,a);return {remotePublicChanged:false,cryptoReady:true,replyAction:I?.action??null,replyClaimId:I?.claimId??null}}let u=Oo(o.secretKey,n,this.ctx.localNodeId,e.remoteNodeId);s&&this.connectionKeyAgreementRemotePublicById.set(e.id,s);let g=m$1(u,{requireEncrypted:true,replayProtection:true}),y=Ye(u);this.negotiatedFingerprintByCrypto.set(g,y),this.index(e,g),e.setApplicationCrypto(g);let m=this.ctx.registry.get(e.id);m&&m!==e&&!m.isClosed&&typeof m.setApplicationCrypto=="function"&&m.setApplicationCrypto(g),await this.syncKeyToNative(e.id,u),this.notifyWaiters(),this.deps.notifyApplicationRouteReady(e,`key-agreement:${t.action??"hello"}`),c$1("[Client][KEY-AGREEMENT] Application crypto ready",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t.action??"hello",remoteSupports:i,remotePublicChanged:l,keyFingerprint:y,localPublicFingerprint:Ye(o.publicKey),remotePublicFingerprint:Ye(n)});let v=this.claimReplyAction(e.id,t.action,a);return {remotePublicChanged:l,cryptoReady:true,replyAction:v?.action??null,replyClaimId:v?.claimId??null}}claimReplyAction(e,t,n){return !n||t==="ack"?null:{action:t==="response"?"ack":"response",claimId:n}}releaseReplyClaim(e,t,n){}index(e,t){this.negotiatedByConnectionId.set(e.id,t);let n=new Set([e.id,e.remoteNodeId,e.deviceId,this.deps.getKnownDeviceIdForNode(e.remoteNodeId)??""]);for(let i of n){let o=typeof i=="string"?i.trim():"";o&&this.negotiatedByPeerId.set(o,t);}}getForConnectionOrPeer(e,t){return this.negotiatedByConnectionId.get(e)??this.negotiatedByPeerId.get(t)}indexPeer(e,t){let n=typeof e=="string"?e.trim():"";n&&this.negotiatedByPeerId.set(n,t);}reindexDevice(e){let t=typeof e.nodeId=="string"?e.nodeId.trim():"";if(!t||!e.deviceId)return;let n=this.getNegotiatedForPeer(t);n&&this.negotiatedByPeerId.set(e.deviceId,n);}async syncRequiredToNative(e){let t=this.wasmClient;!t||typeof t.setConnectionApplicationCryptoRequired!="function"||await t.setConnectionApplicationCryptoRequired(e);}async syncKeyToNative(e,t){let n=this.wasmClient;if(!(!n||typeof n.setConnectionApplicationCryptoKey!="function")){await this.syncRequiredToNative(e);try{await n.setConnectionApplicationCryptoKey(e,Array.from(t));}catch(i){let o=this.ctx.registry.get(e);throw o&&typeof o.requireApplicationCrypto=="function"&&o.requireApplicationCrypto(),console.error("[Client][KEY-AGREEMENT] Failed to sync derived key to native runtime",{connectionId:e,error:i}),i}}}markRequired(e){typeof e.requireApplicationCrypto=="function"&&e.requireApplicationCrypto(),this.syncRequiredToNative(e.id).catch(t=>{console.warn("[Client][KEY-AGREEMENT] Failed to sync required-crypto flag to native runtime",{connectionId:e.id,error:t});});}hydrateAdoptedConnection(e,t){if(e.isClosed||this.resolveForPeer(e.remoteNodeId,e))return false;let n=this.getNegotiatedForPeer(e.remoteNodeId);return n?(this.negotiatedByConnectionId.set(e.id,n),e.setApplicationCrypto(n),this.notifyWaiters(),this.deps.notifyApplicationRouteReady(e,t),c$1("[Client][HANDSHAKE] hydrated adopted connection application crypto from peer index",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t}),true):false}openWebRTCExplicitTransferPayload(e,t){let n=this.resolveForPeer(t?.remoteNodeId,t);return n?n$1(n).openFrame(e):e}protectDirectMoQPayload(e,t,n){return this.resolveForPeer(t,n)?.protectPayload(3,e)??e}openDirectMoQPayload(e,t,n){let i=this.resolveForPeer(t,n);if(!i||!l$1(e))return {payload:null,encrypted:false,proofEligible:false};let o=i.openPayload(3,e);return o?{payload:o,encrypted:true,proofEligible:true}:{payload:i.openPayload(0,e),encrypted:true,proofEligible:false}}get wasmClient(){return this.ctx.wasmClient}};var Pc=15e3,_c=2,wc=150,Ln=class{constructor(e,t){this.ctx=e;this.deps=t;this.pendingTrustApprovals=new Map;this.pendingTrustApprovalScopes=new Map;this.rejectionCooldowns=new Map;this.approvedNodes=new Set;this.approvedConnectionIds=new Set;this.approvedScopesByConnectionId=new Map;this.routeRepairTokenByNodeId=new Map;this.routeRepairTokenPayloadByNodeId=new Map;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){if(this.disposed)return;this.disposed=true,this.deps.retirePendingReciprocalAdmissions("session-token-service-dispose"),this.deps.clearManagedPresenceTicket(),this.clearInMemoryState();let e=this.wasmClient;e&&typeof e.clear_session_tokens=="function"&&e.clear_session_tokens();}async getEndpointTicketWithToken(e,t=0){if(this.disposed)throw new Error("Session token service is disposed");await this.deps.ensureWasmRuntimeForP2P();let n=this.wasmClient;if(n&&typeof n.endpoint_ticket_with_token=="function"){let o=n.endpoint_ticket_with_token.bind(n);return await d$3(()=>o(e,t),{isActive:()=>!this.disposed})}if(e.trim()==="user-device")throw new Error("Managed user-device admission requires Rust/WASM endpoint_ticket_with_token support.");let i=await this.deps.getTicket();return this.buildCompoundTicketWithToken(i,e,t)}buildCompoundTicketWithToken(e,t,n=0){if(this.disposed)throw new Error("Session token service is disposed");let i=dr(),o=t.trim()==="user-device"?void 0:Date.now()+9e5,s=this.wasmClient;return s&&typeof s.register_session_token=="function"&&(typeof o=="number"&&typeof s.register_session_token_with_expiry_ms=="function"?s.register_session_token_with_expiry_ms(i,t,n,o):s.register_session_token(i,t,n)),Et(e,i,t,n,o)}registerSessionToken(e,t,n){if(this.disposed)return;let i=this.wasmClient;i&&typeof i.register_session_token=="function"&&i.register_session_token(e,t,n);}revokeSessionToken(e){if(this.disposed)return;o("Client.revokeSessionToken",{tokenLength:e.length}),this.deps.retirePendingReciprocalAdmissions("session-token-revoke");let t=this.wasmClient;if(t&&typeof t.revoke_session_token=="function"){let n=t.revoke_session_token(e),i=Array.isArray(n)?n.filter(o=>typeof o=="string"&&!!o.trim()):[];for(let o of i){let s=this.ctx.registry.get(o);this.clearConnectionApproval(o),s&&(this.approvedNodes.delete(s.remoteNodeId),this.disconnectConnectionBestEffort(s));}}}async revokeTokensByScope(e){if(this.disposed)return [];o("Client.revokeTokensByScope",{grantScope:e}),this.deps.retirePendingReciprocalAdmissions(`session-token-scope-revoke:${e}`);let t=e.trim(),n=Array.from(this.approvedScopesByConnectionId.entries()).filter(([,l])=>l===t).map(([l])=>l),i=n.map(l=>this.ctx.registry.get(l)).filter(l=>!!l);if(await this.deps.ensureWasmRuntimeForP2P(),this.disposed)return [];let o$1=this.wasmClient,s=o$1&&typeof o$1.revoke_tokens_by_scope=="function"?await o$1.revoke_tokens_by_scope(e):[],a=Array.from(new Set([...Array.isArray(s)?s:[],...n]));if(a.length===0)return [];for(let l of a)this.clearConnectionApproval(l);let c=Array.from(new Set([...i,...a.map(l=>this.ctx.registry.get(l)).filter(l=>!!l)]));return await Promise.allSettled(c.map(l=>this.disconnectConnectionBestEffort(l))),a}async clearSessionTokens(){if(o("Client.clearSessionTokens",{}),this.deps.retirePendingReciprocalAdmissions("session-token-clear"),this.disposed){this.clearInMemoryState();return}if(await this.deps.ensureWasmRuntimeForP2P(),this.deps.clearManagedPresenceTicket(),this.disposed){this.clearInMemoryState();return}this.clearInMemoryState();let e=this.wasmClient;e&&typeof e.clear_session_tokens=="function"&&e.clear_session_tokens();}async validateIncomingSessionToken(e,t,n){if(this.disposed)return {ok:false,reason:"session-token-service-disposed"};let i=this.wasmClient;if(!i||typeof i.validate_session_token!="function")return e.trim()?{ok:false,reason:"session-token-validator-unavailable"}:{ok:true};try{let o="";return t&&n&&typeof i.validate_session_token_for_connection_with_payload=="function"?o=await i.validate_session_token_for_connection_with_payload(e,t,n):t&&typeof i.validate_session_token_for_connection=="function"?o=await i.validate_session_token_for_connection(e,t):o=i.validate_session_token(e),{ok:!0,scope:o||void 0}}catch(o){return {ok:false,reason:o?.message||`${o}`}}}async validateIncomingSessionTokenWithRetry(e,t,n){if(this.disposed)return {ok:false,reason:"session-token-service-disposed"};let i=await this.validateIncomingSessionToken(e,t,n?.tokenPayload);if(i.ok||!e||!(i.reason??"").toLowerCase().includes("unknown session token"))return i;for(let s=1;s<=_c;s+=1){if(await u(wc*s),this.disposed)return {ok:false,reason:"session-token-service-disposed"};if(i=await this.validateIncomingSessionToken(e,t,n?.tokenPayload),i.ok)return c$1("[Client][SESSION-TOKEN] validation recovered after retry",{source:n?.source??"unknown",remoteNodeId:n?.remoteNodeId??null,connectionId:t??null,attempt:s}),i}return i}rememberPendingTrustApproval(e,t){if(this.disposed||!e)return;this.pendingTrustApprovals.set(e,Date.now());let n=typeof t=="string"?t.trim():"";n?this.pendingTrustApprovalScopes.set(e,n):this.pendingTrustApprovalScopes.delete(e);}consumePendingTrustApproval(e){if(this.disposed)return {approved:false};let t=this.pendingTrustApprovals.get(e);if(!t)return {approved:false};let n=this.pendingTrustApprovalScopes.get(e)??null;return this.pendingTrustApprovals.delete(e),this.pendingTrustApprovalScopes.delete(e),Date.now()-t>Pc?{approved:false}:{approved:true,scope:n}}applyTrustApproval(e,t,n="session-token"){if(this.disposed||!e||e.isClosed)return;let o=(typeof t=="string"?t.trim():"")||this.approvedScopesByConnectionId.get(e.id)||"";this.rememberPendingTrustApproval(e.id,o),this.rejectionCooldowns.delete(e.remoteNodeId),this.deps.clearTrustFailureCooldown(e.remoteNodeId),this.approvedNodes.add(e.remoteNodeId),this.approvedConnectionIds.add(e.id),o&&this.approvedScopesByConnectionId.set(e.id,o);let s=this.deps.sessionTokenScopeAllowsDeviceBinding(o),a=s?this.deps.getKnownDeviceIdForNode(e.remoteNodeId):null,c=this.deps.initializeConnectionTrust(e,a);c.required=false,c.verified=true,c.failed=false,c.failureReason=void 0,c.issuedChallenge=null,s?c.verifiedDeviceId=c.verifiedDeviceId??c.expectedDeviceId??a??null:(c.verifiedDeviceId=null,c.expectedDeviceId=null),this.deps.applyConnectionTrustProjection(e);let l=s?c.verifiedDeviceId??c.expectedDeviceId??a??null:null;l&&this.deps.bindConnectionDeviceIdInRust(e,l),o&&this.deps.addPeerScope(e.id,o),c$1("[Client][AUTH] session-token approval applied to connection trust",{connectionId:e.id,remoteNodeId:e.remoteNodeId,scope:t??null,source:n}),this.deps.isWebRTCTransportEnabled()&&e.remoteSupportsWebRTC&&e.requestWebRTCUpgrade("session-token-trust-applied");}clearConnectionApproval(e){this.disposed||(this.approvedConnectionIds.delete(e),this.approvedScopesByConnectionId.delete(e),this.pendingTrustApprovals.delete(e),this.pendingTrustApprovalScopes.delete(e));}approveNode(e){this.disposed||this.approvedNodes.add(e);}approveConnection(e){this.disposed||this.approvedConnectionIds.add(e);}isApproved(e,t){return this.approvedConnectionIds.has(e)||this.approvedNodes.has(t)}isApprovedNode(e){return this.approvedNodes.has(e)}isApprovedConnection(e){return this.approvedConnectionIds.has(e)}getApprovedNodes(){return this.approvedNodes}getApprovedConnectionIds(){return this.approvedConnectionIds}clearRejectionCooldown(e){this.rejectionCooldowns.delete(e);}getRejectionCooldown(e){return this.rejectionCooldowns.get(e)}setRejectionCooldown(e,t){this.disposed||this.rejectionCooldowns.set(e,t);}getApprovedScope(e){return this.approvedScopesByConnectionId.get(e)??null}setApprovedScope(e,t){this.disposed||this.approvedScopesByConnectionId.set(e,t);}rememberRouteRepairTokenForNode(e,t,n){this.disposed||(this.routeRepairTokenByNodeId.set(e,t),this.routeRepairTokenPayloadByNodeId.set(e,n));}async rememberRouteRepairTokenFromTicket(e){if(this.disposed)return false;let t=e.trim();if(!t)return false;let{irohTicket:n,tokenSuffix:i}=se(t);if(!i)return false;let o=ue(n,i),s=typeof o?.t=="string"?o.t.trim():"",a=this.wasmClient;if(!s||typeof a?.endpoint_id_from_ticket!="function")return false;let c=String(await a.endpoint_id_from_ticket(n)).trim();return !c||this.disposed?false:(this.rememberRouteRepairTokenForNode(c,s,i),true)}getRouteRepairTokenForNode(e){return this.routeRepairTokenByNodeId.get(e)}getRouteRepairTokenPayloadForNode(e){return this.routeRepairTokenPayloadByNodeId.get(e)}clearInMemoryState(){this.routeRepairTokenByNodeId.clear(),this.routeRepairTokenPayloadByNodeId.clear(),this.pendingTrustApprovals.clear(),this.pendingTrustApprovalScopes.clear(),this.rejectionCooldowns.clear(),this.approvedNodes.clear(),this.approvedConnectionIds.clear(),this.approvedScopesByConnectionId.clear();}get wasmClient(){return this.ctx.wasmClient}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}};function Cs(r){return new Qi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),getTicket:()=>r.runtimeIdentity.getTicket(),clearManagedPresenceTicketIfExists:()=>r.accessServices.clearManagedPresenceTicketIfExists(),retirePendingReciprocalAdmissionsIfExists:e=>r.retirePendingReciprocalAdmissionsIfExists(e),clearTrustFailureCooldown:e=>{r.connectionTrust.clearFailureCooldown(e);},sessionTokenScopeAllowsDeviceBinding:e=>r.connectionTrust.sessionTokenScopeAllowsDeviceBinding(e),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),initializeConnectionTrust:(e,t)=>r.connectionTrust.initialize(e,t),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),bindConnectionDeviceIdInRust:(e,t)=>r.connectionDeviceBinder.bindConnectionDeviceIdInRust(e,t),addPeerScope:(e,t)=>{r.peerServices.addPeerScope(e,t);},isWebRTCTransportEnabled:()=>k(r.options),getConfiguredApplicationCrypto:()=>r.options?.applicationCrypto,getAutomaticApplicationKeyAgreement:()=>r.options?.automaticApplicationKeyAgreement,getKnownDeviceNodeId:e=>r.deviceDirectory.getKnownDeviceNodeId(e),getPeerState:e=>r.peerServices.getPeerState(e),notifyApplicationRouteReady:(e,t)=>r.transportUpgrade.notifyApplicationRouteReady(e,t)})}var Qi=class{constructor(e){this.host=e;}get sessionTokens(){return this._sessionTokens||(this._sessionTokens=new Ln(this.host.getContext(),{ensureWasmRuntimeForP2P:()=>this.host.ensureWasmRuntimeForP2P(),getTicket:()=>this.host.getTicket(),clearManagedPresenceTicket:()=>this.host.clearManagedPresenceTicketIfExists(),retirePendingReciprocalAdmissions:e=>this.host.retirePendingReciprocalAdmissionsIfExists(e),clearTrustFailureCooldown:e=>this.host.clearTrustFailureCooldown(e),sessionTokenScopeAllowsDeviceBinding:e=>this.host.sessionTokenScopeAllowsDeviceBinding(e),getKnownDeviceIdForNode:e=>this.host.getKnownDeviceIdForNode(e),initializeConnectionTrust:(e,t)=>this.host.initializeConnectionTrust(e,t),applyConnectionTrustProjection:e=>this.host.applyConnectionTrustProjection(e),bindConnectionDeviceIdInRust:(e,t)=>this.host.bindConnectionDeviceIdInRust(e,t),addPeerScope:(e,t)=>this.host.addPeerScope(e,t),isWebRTCTransportEnabled:()=>this.host.isWebRTCTransportEnabled()})),this._sessionTokens}get applicationCrypto(){return this._applicationCrypto||(this._applicationCrypto=new xn(this.host.getContext(),{getConfiguredApplicationCrypto:()=>this.host.getConfiguredApplicationCrypto(),getAutomaticApplicationKeyAgreement:()=>this.host.getAutomaticApplicationKeyAgreement(),getKnownDeviceNodeId:e=>this.host.getKnownDeviceNodeId(e),getKnownDeviceIdForNode:e=>this.host.getKnownDeviceIdForNode(e),getPeerState:e=>this.host.getPeerState(e),notifyApplicationRouteReady:(e,t)=>this.host.notifyApplicationRouteReady(e,t)})),this._applicationCrypto}resolveExistingApplicationCryptoForPeer(e,t){return this._applicationCrypto?.resolveForPeer(e,t)}getApplicationCrypto(e){return this.host.getConfiguredApplicationCrypto()||!e?this.host.getConfiguredApplicationCrypto():this.applicationCrypto.getApplicationCrypto(e)}resolveApplicationCryptoForPeer(e,t){return this.host.getConfiguredApplicationCrypto()||!e&&!t?this.host.getConfiguredApplicationCrypto():this.applicationCrypto.resolveForPeer(e,t)}clearApplicationCryptoForConnection(e){this._applicationCrypto?.clearConnection(e);}releaseApplicationKeyAgreementReply(e,t,n){this._applicationCrypto?.releaseReplyClaim(e,t,n);}waitForApplicationCryptoForPeer(e,t=0){return this.host.getConfiguredApplicationCrypto()||!e||t<=0?Promise.resolve(this.host.getConfiguredApplicationCrypto()):this.applicationCrypto.waitForPeer(e,t)}};var Fn=class{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}buildApplicationIncomingStreamEvent(e){if(this.disposed)return e;if((e.protocolHint==="explicit"||!!e.channel?.channelId)&&!this.deps.isManagedApplicationStreamAuthorized(e.remoteNodeId))return this.deps.logIncomingDiagnostic("session-token:drop-unadmitted-application-stream",{remoteNodeId:e.remoteNodeId||"unknown",traceId:e.traceId||null,protocolHint:e.protocolHint??null,channelId:e.channel?.channelId??null}),{...e,invalid:true};if(this.shouldTreatIncomingStreamAsTransportOnly(e))return e;let n=this.deps.resolveApplicationCryptoStreamTools(e.remoteNodeId);if(!n||e.invalid||e.protocolHint==="explicit"||e.protocolHint==="native-main")return e;try{if(e.type==="uni"){let i=e.stream;return !i||typeof i.getReader!="function"?e:i.applicationCryptoWrapped===!0?{...e,applicationCrypto:n}:{...e,stream:n.wrapReadable(i),applicationCrypto:n}}if(e.type==="bi"&&y(e.stream)){let i=e.stream;return i?.applicationCryptoWrapped===!0?{...e,applicationCrypto:n}:e.protocolHint==="control"?{...e,applicationCrypto:n}:{...e,stream:{...i,send:n.wrapWritable(i.send),recv:n.wrapReadable(i.recv)},applicationCrypto:n}}}catch(i){this.deps.logIncomingDiagnostic("application-crypto:wrap-listener-stream-failed",{remoteNodeId:e.remoteNodeId||"unknown",traceId:e.traceId||null,protocolHint:e.protocolHint??null,error:i});}return e}shouldTreatIncomingStreamAsTransportOnly(e){if(this.disposed||e.type!=="bi")return false;let t=e.channel?.channelId;return t?this.deps.isTransportOnlyChannel(t):e.protocolHint!=="explicit"?false:this.deps.usesTicketOnlySignalingMode()?true:this.deps.hasTransportOnlyConnectionForRemoteNode(e.remoteNodeId)}dispatchSyntheticExplicitIncomingStream(e,t){if(this.disposed)return;if(!this.deps.isManagedApplicationStreamAuthorized(e.remoteNodeId)){this.deps.logIncomingDiagnostic("session-token:drop-unadmitted-webrtc-explicit-stream",{connectionId:e.id,remoteNodeId:e.remoteNodeId});return}c$1("[Client][WebRTC][transfer] Dispatching synthetic explicit stream from WebRTC datachannel",{connectionId:e.id,remoteNodeId:e.remoteNodeId,payloadBytes:t.byteLength});let n={send:new WritableStream({write(){}}),recv:new ReadableStream({start(a){a.enqueue(t),a.close();}}),endpoint_id:e.remoteNodeId},i=this.deps.getConnectionChannelId(e.id),o={type:"bi",stream:n,remoteNodeId:e.remoteNodeId,protocolHint:"explicit",traceId:`webrtc-explicit-${Date.now()}`,channel:i?{channelId:i}:null};if(this.deps.dispatchIncomingChannelListeners(o)||this.disposed)return;this.deps.dispatchIncomingGenericListeners(o)||this.handleSyntheticExplicitFallbackInBackground(e,o);}handleSyntheticExplicitFallbackInBackground(e,t){let n=i=>{this.disposed||c$1("[Client][INCOMING] Failed to process synthetic explicit stream",{connectionId:e.id,remoteNodeId:e.remoteNodeId,error:i});};try{Promise.resolve(this.deps.handleUnhandledIncomingStreamEvent(t)).catch(n);}catch(i){n(i);}}};var Bn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}assertActive(){if(this.disposed)throw new Error("Application stream controller is disposed")}async closeWritableBestEffort(e){if(e)try{let t=e.getWriter?.();if(!t)return;try{await t.close();}catch{}finally{try{t.releaseLock();}catch{}}}catch{}}async openBi(e){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let t=this.ctx.wasmClient;c$1("[Client][OPEN-BI] Opening bidirectional application stream",{peerId:e,hasOpenPeerBi:typeof t.open_peer_bi=="function"});let n=typeof t.open_peer_bi=="function"?await t.open_peer_bi(e,5e3):await t.open_bi(e);this.disposed&&(await B$2(n,"application-stream-controller-disposed-after-open-bi"),this.assertActive()),c$1("[Client][OPEN-BI] Bidirectional application stream opened",{peerId:e,endpointId:n?.endpoint_id??n?.endpointId??null,applicationCryptoWrapped:n?.applicationCryptoWrapped===true});let i=this.deps.getApplicationCryptoForPeer(e),o=n?.applicationCryptoWrapped===true;if(i&&!o){let s=n$1(i);return {readable:s.wrapReadable(n.recv),writable:s.wrapWritable(n.send)}}return {readable:n.recv,writable:n.send}}async openUni(e){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let t=this.deps.getApplicationCryptoForPeer(e),n=(a,c)=>!t||c?a:n$1(t).wrapWritable(a),i=this.ctx.wasmClient;if(typeof i.open_peer_uni=="function"){let a=await i.open_peer_uni(e,5e3),c=a?.writable??a;return this.disposed&&(await this.closeWritableBestEffort(c),this.assertActive()),n(c,a?.applicationCryptoWrapped===true)}let o=await i.open_uni(e),s=o?.writable??o;return this.disposed&&(await this.closeWritableBestEffort(s),this.assertActive()),n(s,o?.applicationCryptoWrapped===true)}async sendFrame(e,t){this.assertActive(),await this.deps.ensureWasmRuntimeForP2P(),this.assertActive();let n=this.ctx.wasmClient;if(typeof n.send_peer_application_frame=="function"){await n.send_peer_application_frame(e,t,5e3),this.assertActive();return}let i=await this.openBi(e),o=i.writable.getWriter();try{await o.write(t),await o.close();}finally{try{o.releaseLock();}catch{}try{await i.readable.cancel("one-shot application frame sent");}catch{}}}};function ut(r){try{let e=r?.type;return typeof e=="string"?e:"unknown"}catch{return "unknown"}}function je(r){try{let e=r?.endpointId;if(typeof e=="string"&&e.trim().length>0)return e}catch{}try{let e=r?.endpoint_id;if(typeof e=="string"&&e.trim().length>0)return e}catch{}return "unknown"}function $i(r){try{let e=r?.transportStableId??r?.transport_stable_id;if(Number.isSafeInteger(e)&&Number(e)>0)return Number(e)}catch{}return null}function bs(r){try{let e=r?.protocolHint;if(e==="control"||e==="explicit"||e==="native-main")return e}catch{}return null}function Ss(r){try{if(!r||!("channel"in r))return {present:!1,channel:null};let e=r.channel;if(e==null)return {present:!0,channel:null};if(typeof e!="object")return {present:!1,channel:null};let t=typeof e.channelId=="string"?e.channelId.trim():"";if(!t)return {present:!1,channel:null};let n=e.metadata&&typeof e.metadata=="object"&&!Array.isArray(e.metadata)?e.metadata:null;return {present:!0,channel:{channelId:t,metadata:n}}}catch{return {present:false,channel:null}}}var Ue=class Ue{constructor(e){this.wasmClient=e;this.clients=new Set;this.listenLoopTask=null;this.activeDispatches=new Set;}addClient(e){this.clients.has(e)||(this.clients.add(e),this.ensureListening());}removeClient(e){this.clients.delete(e);}dispatchIncomingAsync(e,t){let n=je(e),i=performance.now(),o=this.dispatchIncoming(e).then(()=>{let s=performance.now()-i;s>50&&console.warn(`[PERFORMANCE] handleIncomingStream loop took abnormally long: ${Math.round(s)}ms`,{endpointId:n,type:t});}).catch(s=>{console.error("[Client][INCOMING] Failed to handle incoming stream via shared hub",{remoteNodeId:n,type:t,error:s instanceof Error?s.message:String(s)});}).finally(()=>{this.activeDispatches.delete(o);});this.activeDispatches.add(o);}ensureListening(){this.listenLoopTask||(this.listenLoopTask=this.listenLoop().finally(()=>{this.listenLoopTask=null,this.clients.size>0&&this.ensureListening();}));}getPrimaryClient(){let e=this.clients.values().next();return e.done?null:e.value}getChannelTargetClients(e){return Array.from(this.clients).reverse().filter(t=>t.hasIncomingChannelListener(e))}async dispatchIncoming(e){let t=this.getPrimaryClient();if(!t)return;let n=Array.from(this.clients).some(a=>a.shouldInspectIncomingChannelEnvelope()),i=await t.normalizeIncomingStreamEvent(e,{inspectChannelEnvelope:n}),o=i.channel?.channelId?.trim();if(o&&t.isInternalSessionChannel(o)){await t.handleUnhandledIncomingStreamEvent(i);return}if(o){for(let a of this.getChannelTargetClients(o))if(a.dispatchIncomingChannelListeners(i))return}let s=this.getPrimaryClient();if(s){if(i.protocolHint==="native-main"){await s.handleUnhandledIncomingStreamEvent(i);return}s.dispatchIncomingGenericListeners(i)||await s.handleUnhandledIncomingStreamEvent(i);}}async listenLoop(){let e=0;for(;;){if(this.clients.size===0)return;let t=null;try{let i=(await this.wasmClient.incoming_streams()).getReader();for(t=i,e=0,he()&&nn()&&c$1("[Client][INCOMING][MOBILE] shared-hub reader acquired",{sharedHubClients:this.clients.size});this.clients.size>0;){let{done:o,value:s}=await i.read();if(o)throw new Error("incoming stream reader closed unexpectedly");if(!s)continue;let a=ut(s);a!=="uni"&&c$1("[Client][INCOMING] Received stream from WASM node",{type:a,endpointId:je(s),sharedHubClients:this.clients.size}),this.dispatchIncomingAsync(s,a);}}catch(n){if(this.clients.size===0)return;e+=1;let i=x$1(e,Ue.RETRY_MIN_DELAY_MS,Ue.RETRY_MAX_DELAY_MS);console.warn("[Client][INCOMING] Shared listen loop restarting after stream failure",{attempt:e,delayMs:i,mobile:he(),error:n}),await u(i);}finally{if(t)try{t.releaseLock(),he()&&nn()&&c$1("[Client][INCOMING][MOBILE] shared-hub reader released",{sharedHubClients:this.clients.size});}catch{}}}}};Ue.RETRY_MIN_DELAY_MS=250,Ue.RETRY_MAX_DELAY_MS=2e3;var Wn=Ue;var gt=class gt{constructor(e,t){this.ctx=e;this.deps=t;this.listening=false;this.presenceStarted=false;this.listenLoopTask=null;this.hubClient={hasIncomingChannelListener:n=>this.deps.hasIncomingChannelListener(n),hasAnyIncomingChannelListeners:()=>this.deps.hasAnyIncomingChannelListeners(),shouldInspectIncomingChannelEnvelope:()=>this.deps.shouldInspectIncomingChannelEnvelope(),isInternalSessionChannel:n=>this.deps.isInternalSessionChannel(n),normalizeIncomingStreamEvent:(n,i)=>this.deps.normalizeIncomingStreamEvent(n,i),dispatchIncomingChannelListeners:n=>this.deps.dispatchIncomingChannelListeners(n),dispatchIncomingGenericListeners:n=>this.deps.dispatchIncomingGenericListeners(n),handleUnhandledIncomingStreamEvent:n=>this.deps.handleUnhandledIncomingStreamEvent(n)},this.ctx.registerDisposer(()=>this.stop());}async start(e={}){if(this.listening)return;await this.deps.ensureWasmRuntimeForP2P();let t=false;this.markListening(false);try{let n=this.getSharedIncomingStreamHub();n?(n.addClient(this.hubClient),t=!0):this.listenLoopTask||(this.listenLoopTask=this.listenLoop().finally(()=>{this.listenLoopTask=null;})),e.startPresence!==!1&&(await this.deps.startPresenceForListen(),this.presenceStarted=!0);}catch(n){throw this.markStopped(),this.presenceStarted=false,t&&this.getSharedIncomingStreamHub()?.removeClient(this.hubClient),n}}stop(){let e=this.listening;if(this.markStopped(),e)for(let t of Array.from(this.ctx.registry.values()))t.isClosed||this.disconnectBestEffort(t);this.getSharedIncomingStreamHub()?.removeClient(this.hubClient),e&&this.presenceStarted&&this.deps.setOfflinePresence(),this.presenceStarted=false;}prepareForSignOut(){this.markStopped(),this.presenceStarted=false;}isListening(){return this.listening}markListening(e=true){this.listening=true,this.presenceStarted=e;}markStopped(){this.listening=false;}getSharedIncomingStreamHub(){let e=this.ctx.wasmClient;if(!e||typeof e.incoming_streams!="function")return null;let t=e,n=gt.incomingStreamHubs.get(t);return n||(n=new Wn(e),gt.incomingStreamHubs.set(t,n)),n}async listenLoop(){await this.deps.getIncomingStreamRouter().listenLoop({isListening:()=>this.listening,getWasmClient:()=>this.ctx.wasmClient,handleIncomingStream:e=>this.handleIncomingStream(e),shouldVerboseIncomingDiagnostics:()=>this.deps.shouldVerboseIncomingDiagnostics(),getLocalNodeId:()=>this.ctx.localNodeId||null,retryMinDelayMs:this.deps.retryMinDelayMs,retryMaxDelayMs:this.deps.retryMaxDelayMs});}async handleIncomingStream(e){return this.deps.handleIncomingStream(e)}shouldInspectIncomingChannelEnvelope(){return this.deps.shouldInspectIncomingChannelEnvelope()}normalizeIncomingStreamEvent(e,t={}){return this.deps.normalizeIncomingStreamEvent(e,t)}dispatchIncomingChannelListeners(e){return this.deps.dispatchIncomingChannelListeners(e)}dispatchIncomingGenericListeners(e){return this.deps.dispatchIncomingGenericListeners(e)}handleUnhandledIncomingStreamEvent(e){return this.deps.handleUnhandledIncomingStreamEvent(e)}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}};gt.incomingStreamHubs=new WeakMap;var On=gt;var Hn=class{constructor(e){this.deps=e;this.traceSequence=0;}getRuntimeSafetyProfile(){return this.deps.getRuntimeSafetyProfileOverride()??nt(this.deps.getOptions()??{})}shouldVerboseIncomingDiagnostics(){return this.getRuntimeSafetyProfile().diagnosticsMode}shouldInspectIncomingChannelEnvelope(){return this.getRuntimeSafetyProfile().skipIncomingChannelEnvelopeInspection?false:this.deps.hasAnyIncomingChannelListeners()||this.deps.requiresIncomingChannelEnvelopeInspection()}nextIncomingTraceId(e,t){Number.isFinite(this.traceSequence)||(this.traceSequence=0),this.traceSequence+=1;let n=t&&t.length>0?t.slice(0,8):"unknown";return `${e}-${n}-${this.traceSequence.toString(36)}`}logIncomingDiagnostic(e,t){this.shouldVerboseIncomingDiagnostics()&&c$1(`[Client][INCOMING][MOBILE] ${e}`,t);}safeReleaseReaderLock(e,t,n,i=(o,s)=>this.logIncomingDiagnostic(o,s)){try{e.releaseLock(),i("releaseLock:ok",{context:t,traceId:n||null});}catch(o){console.warn("[Client][INCOMING] releaseLock failed",{context:t,traceId:n||null,error:o});}}async cancelUnhandledIncomingUniStream(e,t,n=(i,o)=>this.logIncomingDiagnostic(i,o)){if(!(!e||typeof e!="object")){if(this.shouldVerboseIncomingDiagnostics()){n("uni:drop-unhandled",{remoteNodeId:t||"unknown"});return}try{let i=e;if(typeof i.cancel=="function")return;if(typeof i.getReader=="function"){let o=i.getReader();try{await o.read().catch(()=>{});}finally{try{o.releaseLock();}catch{}}d$2("[Client][INCOMING] Released unhandled uni stream reader",{remoteNodeId:t});}}catch(i){console.warn("[Client][INCOMING] Failed to cancel unhandled uni stream",{remoteNodeId:t,error:i});}}}shouldSkipIncomingStreamProbe(){return this.getRuntimeSafetyProfile().skipIncomingBiProbe===true}};var Un=class{constructor(e,t){this.config=e;this.deps=t;}async normalize(e,t){return this.deps.router.normalizeIncomingStreamEvent(e,t,this.normalizationDeps())}async extractIncomingChannelEnvelope(e,t,n){return this.deps.router.extractIncomingChannelEnvelope(e,t,this.channelInspectionDeps(),n)}async classifyBiIncomingStream(e,t){return this.deps.router.classifyBiIncomingStream(e,this.channelInspectionDeps(),t)}async maybeOpenEncryptedExplicitBiStream(e,t,n){return this.deps.router.maybeOpenEncryptedExplicitBiStream(e,this.cryptoProbeConfig(),this.cryptoProbeDeps(),t,n)}maybeWrapIncomingBiStreamWithApplicationCrypto(e,t,n){return this.deps.router.maybeWrapIncomingBiStreamWithApplicationCrypto(e,this.cryptoProbeDeps(),t,n)}async maybeOpenEncryptedControlBiStream(e,t,n){return this.deps.router.maybeOpenEncryptedControlBiStream(e,this.cryptoProbeConfig(),this.cryptoProbeDeps(),t,n)}async detectNativeMainStream(e,t,n){return this.deps.router.detectNativeMainStream(e,t,{nativeMainProtocolByte:this.config.nativeMainProtocolByte,explicitProtocolByte:this.config.explicitProtocolByte,label:this.config.nativeMainLabel,maxLabelBytes:this.config.nativeMainMaxLabelBytes},this.channelInspectionDeps(),n)}channelInspectionDeps(){return {logIncomingDiagnostic:(e,t)=>this.deps.logIncomingDiagnostic(e,t),releaseReaderLock:(e,t,n)=>this.deps.releaseReaderLock(e,t,n)}}cryptoProbeConfig(){return {explicitProtocolByte:this.config.explicitProtocolByte,maxEncryptedFrameBytes:this.config.maxEncryptedFrameBytes,probeDeadlineMs:this.config.probeDeadlineMs}}cryptoProbeDeps(){return {...this.channelInspectionDeps(),resolveApplicationCryptoForPeer:e=>this.deps.resolveApplicationCryptoForPeer(e),waitForApplicationCryptoForPeer:e=>this.deps.waitForApplicationCryptoForPeer(e,this.config.explicitApplicationCryptoWaitMs),resolveApplicationCryptoStreamTools:e=>this.deps.resolveApplicationCryptoStreamTools(e)}}normalizationDeps(){return {...this.cryptoProbeDeps(),nextIncomingTraceId:(e,t)=>this.deps.nextIncomingTraceId(e,t),normalizeAuthoritativeIncomingProtocolHint:(e,t,n)=>Qt(e),shouldStripIncomingMainLabel:()=>Ir(this.deps.shouldSkipIncomingStreamProbe()),shouldSkipIncomingBiProbeForRemoteNode:e=>this.deps.shouldSkipIncomingBiProbeForRemoteNode(e),inferTicketFlowBiProtocolHint:e=>this.deps.inferTicketFlowBiProtocolHint(e),shouldSkipIncomingStreamProbe:()=>this.deps.shouldSkipIncomingStreamProbe(),isTransportOnlyChannel:e=>this.deps.isTransportOnlyChannel(e),detectNativeMainStream:(e,t,n)=>this.detectNativeMainStream(e,t,n),extractIncomingChannelEnvelope:(e,t,n)=>this.extractIncomingChannelEnvelope(e,t,n),classifyBiIncomingStream:(e,t)=>this.classifyBiIncomingStream(e,t),maybeWrapIncomingBiStreamWithApplicationCrypto:(e,t,n)=>this.maybeWrapIncomingBiStreamWithApplicationCrypto(e,t,n),maybeOpenEncryptedExplicitBiStream:(e,t,n)=>this.maybeOpenEncryptedExplicitBiStream(e,t,n),maybeOpenEncryptedControlBiStream:(e,t,n)=>this.maybeOpenEncryptedControlBiStream(e,t,n)}}};var ht=class extends Error{},jn=class{maybeWrapIncomingBiStreamWithApplicationCrypto(e,t,n,i){if(!y(e)||e?.applicationCryptoWrapped===true)return e;let o=t.resolveApplicationCryptoStreamTools(n);if(!o)return e;try{return {...e,send:o.wrapWritable(e.send),recv:o.wrapReadable(e.recv),applicationCryptoWrapped:!0}}catch(s){return t.logIncomingDiagnostic("application-crypto:early-wrap-incoming-bi-failed",{remoteNodeId:n||"unknown",traceId:i||null,error:s}),e}}async maybeOpenEncryptedExplicitBiStream(e,t,n,i,o){let s=n.resolveApplicationCryptoForPeer(o);if(!y(e))return e;let a;try{a=e.recv.getReader();}catch{return e}let c=(S,I,k=null)=>C$1(a,S,{context:I,traceId:i,pendingRead:k,release:T=>n.releaseReaderLock(a,`${I}:${T}`,i),log:(T,D)=>n.logIncomingDiagnostic(T,D)}),l=S=>A(e,S),p=[],u=new Uint8Array(0),g=null,y$1=Date.now()+t.probeDeadlineMs,m=async()=>{let S=await D$1(a,y$1);return S.status==="timeout"?(g=S.pendingRead??null,false):S.status==="done"?false:(S.value&&S.value.byteLength>0&&(p.push(S.value),u=w$1(p)),true)},v=()=>g?(n.logIncomingDiagnostic("explicit-crypto:probe-deadline",{traceId:i||null,endpointId:o||"unknown",bufferedBytes:u.byteLength}),l(c(u,"explicit-crypto:probe-deadline",g))):null;try{for(;u.byteLength<5&&await m(););let S=v();if(S)return S;if(u.byteLength<5||u[0]!==t.explicitProtocolByte)return l(c(u,"explicit-crypto:not-probeable"));let I=new DataView(u.buffer,u.byteOffset+1,u.byteLength-1).getUint32(0,!1);if(I===0||I>t.maxEncryptedFrameBytes){let E=u.slice(1);return this.looksLikeApplicationCryptoEnvelope(E)?(s||(n.logIncomingDiagnostic("explicit-crypto:await-key",{traceId:i||null,endpointId:o||"unknown"}),s=await n.waitForApplicationCryptoForPeer(o)),s?(n.logIncomingDiagnostic("explicit-crypto:unframed-encrypted-body",{traceId:i||null,endpointId:o||"unknown"}),l(this.unframedEncryptedExplicitReadable(a,E,s,t.explicitProtocolByte,n,i))):this.rejectEncryptedStreamWithoutCrypto(a,n,i,o,"explicit-crypto:unframed-encrypted-body-missing-key")):l(c(u,"explicit-crypto:not-encrypted-length"))}let k=5+I;for(;u.byteLength<k&&await m(););let T=v();if(T)return T;if(u.byteLength<k)return l(c(u,"explicit-crypto:truncated-probe"));let D=u.slice(5,k);if(!l$1(D))return l(c(u,"explicit-crypto:legacy-plaintext"));if(s||(n.logIncomingDiagnostic("explicit-crypto:await-key",{traceId:i||null,endpointId:o||"unknown"}),s=await n.waitForApplicationCryptoForPeer(o)),!s)return n.logIncomingDiagnostic("explicit-crypto:encrypted-body-missing-key",{traceId:i||null,endpointId:o||"unknown"}),this.rejectEncryptedStreamWithoutCrypto(a,n,i,o,"explicit-crypto:encrypted-body-missing-key");let _=c(u.slice(1),"explicit-crypto:encrypted-body");return l(this.encryptedExplicitReadable(_,s,t.explicitProtocolByte,n,i))}catch(S){if(S instanceof ht)throw S;return n.logIncomingDiagnostic("explicit-crypto:probe-error",{traceId:i||null,error:S?.message||String(S)}),l(c(u,"explicit-crypto:probe-error"))}}async maybeOpenEncryptedControlBiStream(e,t,n,i,o){if(!y(e)||e?.applicationCryptoWrapped===true)return e;let s;try{s=e.recv.getReader();}catch{return e}let a=(v,S,I=null)=>C$1(s,v,{context:S,traceId:i,pendingRead:I,release:k=>n.releaseReaderLock(s,`${S}:${k}`,i),log:(k,T)=>n.logIncomingDiagnostic(k,T)}),c=v=>A(e,v),l=[],p=new Uint8Array(0),u=null,g=Date.now()+t.probeDeadlineMs,y$1=async()=>{let v=await D$1(s,g);return v.status==="timeout"?(u=v.pendingRead??null,false):v.status==="done"?false:(v.value&&v.value.byteLength>0&&(l.push(v.value),p=w$1(l)),true)},m=()=>u?(n.logIncomingDiagnostic("control-crypto:probe-deadline",{traceId:i||null,endpointId:o||"unknown",bufferedBytes:p.byteLength}),c(a(p,"control-crypto:probe-deadline",u))):null;try{for(;p.byteLength<4&&await y$1(););let v=m();if(v)return v;if(p.byteLength<4)return c(a(p,"control-crypto:not-probeable"));let S=new DataView(p.buffer,p.byteOffset,p.byteLength).getUint32(0,!1);if(S===0||S>t.maxEncryptedFrameBytes)return c(a(p,"control-crypto:plaintext-length"));let I=4+Math.min(S,7);for(;p.byteLength<I&&await y$1(););let k=m();if(k)return k;if(p.byteLength<I)return c(a(p,"control-crypto:truncated-probe"));let T=p.slice(4,I);if(!this.looksLikeApplicationCryptoEnvelope(T))return c(a(p,"control-crypto:plaintext-frame"));let D=n.resolveApplicationCryptoForPeer(o);if(D||(n.logIncomingDiagnostic("control-crypto:await-key",{traceId:i||null,endpointId:o||"unknown"}),D=await n.waitForApplicationCryptoForPeer(o)),!D)return n.logIncomingDiagnostic("control-crypto:encrypted-body-missing-key",{traceId:i||null,endpointId:o||"unknown"}),this.rejectEncryptedStreamWithoutCrypto(s,n,i,o,"control-crypto:encrypted-body-missing-key");n.logIncomingDiagnostic("control-crypto:encrypted-frame",{traceId:i||null,endpointId:o||"unknown",frameLength:S});let _=n$1(D);return {...e,send:_.wrapWritable(e.send),recv:_.wrapReadable(a(p,"control-crypto:encrypted-frame")),applicationCryptoWrapped:!0}}catch(v){if(v instanceof ht)throw v;return n.logIncomingDiagnostic("control-crypto:probe-error",{traceId:i||null,endpointId:o||"unknown",error:v?.message||String(v)}),c(a(p,"control-crypto:probe-error"))}}encryptedExplicitReadable(e,t,n,i,o){let a=n$1(t).wrapReadable(e).getReader(),c=false;return new ReadableStream({async pull(l){if(!c){c=true,l.enqueue(new Uint8Array([n]));return}try{let{done:p,value:u}=await a.read();if(p){l.close(),a.releaseLock();return}u&&l.enqueue(u);}catch(p){l.error(p);try{a.releaseLock();}catch{}}},async cancel(l){try{await a.cancel(l);}catch{}try{a.releaseLock();}catch{}i.logIncomingDiagnostic("explicit-crypto:cancel",{traceId:o||null});}})}unframedEncryptedExplicitReadable(e,t,n,i,o,s){let a=false,c=false;return new ReadableStream({async pull(l){if(!a){a=true,l.enqueue(new Uint8Array([i]));return}if(c){l.close();return}c=true;let p=[t];try{for(;;){let{done:y,value:m}=await e.read();if(y)break;m&&m.byteLength>0&&p.push(new Uint8Array(m));}let u=w$1(p),g=n.openPayload(3,u);if(!g)throw new Error("[OpenRTC] encrypted explicit body failed authentication");l.enqueue(g),l.close();}catch(u){l.error(u);}finally{try{e.releaseLock();}catch{}}},async cancel(l){try{await e.cancel(l);}catch{}try{e.releaseLock();}catch{}o.logIncomingDiagnostic("explicit-crypto:unframed-cancel",{traceId:s||null});}})}looksLikeApplicationCryptoEnvelope(e){return e.byteLength>=7&&e[0]===79&&e[1]===82&&e[2]===84&&e[3]===67&&e[4]===69&&e[5]===49}async rejectEncryptedStreamWithoutCrypto(e,t,n,i,o){let s=new ht(`[OpenRTC] rejected encrypted stream without negotiated application crypto (${o})`);try{await e.cancel(s);}catch{}throw t.releaseReaderLock(e,o,n),t.logIncomingDiagnostic("application-crypto:stream-rejected",{traceId:n||null,endpointId:i||"unknown",context:o}),s}};var Ge=class{async extractIncomingUniChannelEnvelope(e,t,n,i){let o={send:new WritableStream,recv:e,endpoint_id:t},s=await this.extractIncomingChannelEnvelope(o,t,n,i);return {stream:s.stream.recv,channel:s.channel}}async extractIncomingChannelEnvelope(e,t,n,i){if(!y(e))return {stream:e,channel:null};let o;try{o=e.recv.getReader(),n.logIncomingDiagnostic("channel-envelope:reader-acquired",{traceId:i||null,remoteNodeId:t||"unknown"});}catch(A){return console.warn("[Client][CHANNEL] Incoming stream recv reader unavailable; skipping channel envelope inspection",{remoteNodeId:t,traceId:i||null,error:A}),{stream:e,channel:null}}let s=(A,j)=>C$1(o,A,{context:j,traceId:i,release:q=>n.releaseReaderLock(o,`${j}:${q}`,i),log:(q,F)=>n.logIncomingDiagnostic(q,F)}),a=A$1=>A(e,A$1),c=[],l=0;try{for(;l<6;){let{done:A,value:j}=await o.read();if(A)break;if(!j||j.byteLength===0)continue;let q=new Uint8Array(j);c.push(q),l+=q.byteLength;}}catch(A){return console.warn("[Client][CHANNEL] Failed reading incoming channel envelope prefix",{remoteNodeId:t,traceId:i||null,error:A}),n.releaseReaderLock(o,"extractIncomingChannelEnvelope:read-prefix-failed",i),{stream:e,channel:null}}let p=w$1(c);if(p.byteLength<6||p[0]!==127||p[1]!==1)return c$1("[Client][CHANNEL] Incoming stream did not start with channel envelope",{remoteNodeId:t,traceId:i||null,bufferedBytes:p.byteLength,firstBytes:Array.from(p.slice(0,Math.min(p.byteLength,8))).map(A=>A.toString(16).padStart(2,"0")).join(" ")}),{stream:a(s(p,"extractIncomingChannelEnvelope:not-envelope")),channel:null};let u=new DataView(p.buffer,p.byteOffset,p.byteLength),g=u.getUint16(2,false),y$1=u.getUint16(4,false),m=6+g+y$1,v=p;if(v.byteLength<m)try{for(;v.byteLength<m;){let{done:A,value:j}=await o.read();if(A)break;!j||j.byteLength===0||(v=w$1([v,new Uint8Array(j)]));}}catch(A){console.warn("[Client][CHANNEL] Failed extending incoming channel envelope read",{remoteNodeId:t,error:A});}if(v.byteLength<m||g===0)return {stream:a(s(v,"extractIncomingChannelEnvelope:truncated-envelope")),channel:null};let S=6,I=S+g,k=I+y$1,T=new TextDecoder,D=T.decode(v.slice(S,I)).trim(),_=null;if(y$1>0)try{let A=JSON.parse(T.decode(v.slice(I,k)));A&&typeof A=="object"&&!Array.isArray(A)&&(_=A);}catch(A){console.warn("[Client][CHANNEL] Failed to parse incoming channel metadata",{remoteNodeId:t,channelId:D,error:A});}if(!D)return {stream:a(s(v,"extractIncomingChannelEnvelope:empty-channel-id")),channel:null};let E=a(s(v.slice(m),"extractIncomingChannelEnvelope:channel-envelope-consumed"));return c$1("[Client][CHANNEL] Incoming channel envelope consumed",{remoteNodeId:t,traceId:i||null,channelId:D,metadata:_?Object.keys(_):[],bufferedBytes:v.byteLength,remainingBytes:Math.max(0,v.byteLength-m)}),{stream:E,channel:{channelId:D,metadata:_}}}async classifyBiIncomingStream(e,t,n,i){if(!y(e))return {stream:e,protocolHint:"unknown"};let o;try{o=e.recv.getReader();}catch{return {stream:e,protocolHint:"unknown"}}let s;try{s=await o.read();}catch{return n.releaseReaderLock(o,"classifyBiIncomingStream:read-failed",i),{stream:e,protocolHint:"unknown"}}if(s.done||!s.value||s.value.byteLength===0)return n.releaseReaderLock(o,"classifyBiIncomingStream:empty-first-read",i),c$1("[Client][INCOMING] classifyBiIncomingStream: empty read",{traceId:i||null,done:s.done,hasValue:!!s.value,byteLength:s.value?.byteLength}),{stream:e,protocolHint:"unknown"};let a=new Uint8Array(s.value),c=a[0];c$1("[Client][INCOMING] classifyBiIncomingStream: first byte",{traceId:i||null,firstByte:"0x"+c.toString(16),EXPLICIT_PROTOCOL_BYTE:"0x"+t.toString(16),isExplicit:c===t,chunkLength:a.length});let l=A(e,C$1(o,a,{context:"classifyBiIncomingStream:first-chunk",traceId:i,release:p=>n.releaseReaderLock(o,`classifyBiIncomingStream:first-chunk:${p}`,i),log:(p,u)=>n.logIncomingDiagnostic(p,u)}));return c===t?{stream:l,protocolHint:"explicit"}:{stream:l,protocolHint:"control"}}async detectNativeMainStream(e,t,n,i,o){if(!y(e))return {handled:false,stream:e,protocolHint:"unknown"};let s;try{s=e.recv.getReader();}catch(D){return console.warn("[Client][NATIVE-MAIN] Incoming stream recv reader unavailable",{remoteNodeId:t,traceId:o||null,error:D}),{handled:false,stream:e,protocolHint:"control"}}let a=(D,_)=>C$1(s,D,{context:_,traceId:o,release:E=>i.releaseReaderLock(s,`${_}:${E}`,o),log:(E,A)=>i.logIncomingDiagnostic(E,A)}),c=D=>A(e,D),l=[],p=0,u=5,g=false;try{for(;p<u;){let{done:D,value:_}=await s.read();if(D){g=!0;break}!_||_.byteLength===0||(l.push(new Uint8Array(_)),p+=_.byteLength);}}catch(D){return console.warn("[Client][NATIVE-MAIN] Failed reading incoming prefix",{remoteNodeId:t,traceId:o||null,error:D}),i.releaseReaderLock(s,"detectNativeMainStream:read-prefix-failed",o),{handled:false,stream:e,protocolHint:"control"}}let y$1=w$1(l);if(y$1.byteLength<u||y$1[0]!==n.nativeMainProtocolByte)return {handled:false,stream:c(a(y$1,"detectNativeMainStream:not-native-main")),protocolHint:y$1[0]===n.explicitProtocolByte?"explicit":"control"};let m=new DataView(y$1.buffer,y$1.byteOffset,y$1.byteLength).getUint32(1,false);if(m===0||m>n.maxLabelBytes)return {handled:false,stream:c(a(y$1,"detectNativeMainStream:invalid-label-length")),protocolHint:"control"};let v=5+m,S=y$1;if(S.byteLength<v&&!g){let D=[S],_=S.byteLength;try{for(;_<v;){let{done:E,value:A}=await s.read();if(E){g=!0;break}if(!A||A.byteLength===0)continue;let j=new Uint8Array(A);D.push(j),_+=j.byteLength;}}catch(E){console.warn("[Client][NATIVE-MAIN] Failed extending prefix read",{remoteNodeId:t,error:E});}S=w$1(D);}if(S.byteLength<v)return {handled:false,stream:c(a(S,"detectNativeMainStream:truncated-label")),protocolHint:"control"};let I=S.slice(5,v),k=new TextDecoder().decode(I);if(k!==n.label)return {handled:false,stream:c(a(S,"detectNativeMainStream:label-mismatch")),protocolHint:"control"};let T=c(a(S.slice(v),"detectNativeMainStream:label-consumed"));return c$1("[Client][NATIVE-MAIN] Detected desktop native main stream",{remoteNodeId:t,traceId:o||null,label:k}),{handled:true,stream:T,protocolHint:"native-main"}}};var Gn=class{constructor(){this.transfers=new Map;}clear(){this.transfers.clear();}maybeHandle(e,t,n){if(t.byteLength<25||t[0]!==n.explicitProtocolByte)return false;let i=t.slice(1,17),o=Array.from(i).map(g=>g.toString(16).padStart(2,"0")).join(""),s=`${e.id}:${o}`,a=new DataView(t.buffer,t.byteOffset,t.byteLength),c=a.getUint32(17,false),l=a.getUint32(21,false);if(c===4294967295){if(t.byteLength<29)return true;let g=a.getUint32(25,false),y=29,m=y+g;if(m>t.byteLength)return true;let v=n.openWebRTCExplicitTransferPayload(t.slice(y,m),e);return v?(this.transfers.set(s,{headerBytes:v,chunks:new Map,total:0,received:0}),c$1("[Client][WebRTC][transfer] Incoming WebRTC explicit transfer header received",{connectionId:e.id,remoteNodeId:e.remoteNodeId,transferIdKey:o,headerBytes:g}),true):(this.transfers.delete(s),true)}let p=this.transfers.get(s);if(!p)return true;if(p.total===0)p.total=l;else if(p.total!==l)return this.transfers.delete(s),true;if(p.chunks.has(c))return true;let u=n.openWebRTCExplicitTransferPayload(t.slice(25),e);if(!u)return this.transfers.delete(s),true;if(p.chunks.set(c,u),p.received+=1,p.total>0&&p.received>=p.total){let g=this.reassemble(p,n.explicitProtocolByte);this.transfers.delete(s),g&&(c$1("[Client][WebRTC][transfer] Incoming WebRTC transfer assembled in browser",{connectionId:e.id,remoteNodeId:e.remoteNodeId,transferIdKey:o,chunks:p.total,payloadBytes:g.byteLength}),n.dispatchSyntheticExplicitIncomingStream(e,g));}return true}reassemble(e,t){let n=[],i=0;for(let a=0;a<e.total;a+=1){let c=e.chunks.get(a);if(!c)return null;n.push(c),i+=c.byteLength;}let o=new Uint8Array(5+e.headerBytes.byteLength+i);o[0]=t,new DataView(o.buffer).setUint32(1,e.headerBytes.byteLength,false),o.set(e.headerBytes,5);let s=5+e.headerBytes.byteLength;for(let a of n)o.set(a,s),s+=a.byteLength;return o}};var qn=class{constructor(){this.protocolInspector=new Ge;}async normalize(e,t,n){let i=n.resolveApplicationCryptoStreamTools(t.endpointId),o=!!i,s=i?i.wrapReadable(e):e,a=t.authoritativeChannel;if(!a&&t.inspectChannelEnvelope){let c=await this.protocolInspector.extractIncomingUniChannelEnvelope(s,t.endpointId,n,t.traceId);s=c.stream,a=c.channel;}return o&&Object.defineProperty(s,"applicationCryptoWrapped",{configurable:true,value:true}),{stream:s,channel:a}}};var Kn=class{constructor(e){this.deps=e;this.messageListeners=[];this.roomRequestListeners=[];this.streamListeners=[];this.channelStreamListeners=new Map;this.registeredChannels=new Map;this.protocolInspector=new Ge;this.cryptoProbe=new jn;this.uniStreamNormalizer=new qn;this.webRTCExplicitTransferAssembler=new Gn;this.disposed=false;this.deps?.registerDisposer(()=>this.dispose());for(let t of this.deps?.defaultChannels??[])this.registerChannel(t);}dispose(){this.disposed||(this.disposed=true,this.messageListeners=[],this.roomRequestListeners=[],this.streamListeners=[],this.channelStreamListeners.clear(),this.registeredChannels.clear(),this.webRTCExplicitTransferAssembler.clear());}get webrtcIncomingExplicitTransfers(){return this.webRTCExplicitTransferAssembler.transfers}set webrtcIncomingExplicitTransfers(e){this.webRTCExplicitTransferAssembler.transfers=e;}onMessage(e){return this.disposed?()=>{}:(this.messageListeners.push(e),()=>{this.messageListeners=this.messageListeners.filter(t=>t!==e);})}dispatchMessage(e,t){if(!this.disposed)for(let n of [...this.messageListeners])try{n(e,t);}catch(i){console.warn("[Client] message listener failed",i);}}onIncomingStream(e){return this.disposed?()=>{}:(this.streamListeners.push(e),()=>{this.streamListeners=this.streamListeners.filter(t=>t!==e);})}hasIncomingStreamListeners(){return this.streamListeners.length>0}getRegisteredChannel(e){let t=typeof e=="string"?e.trim():"";return t?this.registeredChannels.get(t)??null:null}registerChannel(e){if(this.disposed)return;let t=e.id.trim();if(!t)throw new Error("Channel registration requires a non-empty channel id.");this.registeredChannels.set(t,{...e,id:t});}unregisterChannel(e){let t=e.trim();t&&(this.registeredChannels.delete(t),this.channelStreamListeners.delete(t));}listChannels(){return Array.from(this.registeredChannels.values())}onIncomingChannelStream(e,t){if(this.disposed)return ()=>{};let n=e.trim();if(!n)throw new Error("Channel stream listener requires a non-empty channel id.");let i=this.channelStreamListeners.get(n)??new Set;return i.add(t),this.channelStreamListeners.set(n,i),()=>{let o=this.channelStreamListeners.get(n);o&&(o.delete(t),o.size===0&&this.channelStreamListeners.delete(n));}}hasIncomingChannelListener(e){let t=e.trim();return t?(this.channelStreamListeners.get(t)?.size??0)>0:false}hasAnyIncomingChannelListeners(){for(let e of this.channelStreamListeners.values())if(e.size>0)return true;return false}requiresIncomingChannelEnvelopeInspection(){for(let e of this.registeredChannels.values())if(e.kind==="system"&&e.routing==="session-default")return true;return false}isInternalSessionChannel(e){let t=this.getRegisteredChannel(e);return t?.kind==="system"&&t.routing==="session-default"}dispatchIncomingChannelListeners(e){let t=e.channel?.channelId?.trim();if(!t)return false;let n=this.channelStreamListeners.get(t);if(!n)return false;for(let i of [...n])try{if(i(e)===!0)return !0}catch(o){console.warn("[Client] incoming channel stream listener failed",o);}return false}dispatchIncomingGenericListeners(e){for(let t of [...this.streamListeners])try{if(t(e)===!0)return !0}catch(n){console.warn("[Client] incoming stream listener failed",n);}return false}onRoomJoinRequest(e){return this.disposed?()=>{}:(this.roomRequestListeners.push(e),()=>{this.roomRequestListeners=this.roomRequestListeners.filter(t=>t!==e);})}async listenLoop(e){let t=0;for(;e.isListening();){let n=e.getWasmClient();if(!n||typeof n.incoming_streams!="function"){console.warn("[Client][INCOMING] incoming_streams is unavailable; stopping listen loop");return}let i=null;try{i=(await n.incoming_streams()).getReader();let s=i;for(t=0,e.shouldVerboseIncomingDiagnostics()&&c$1("[Client][INCOMING][MOBILE] direct listen reader acquired",{localNodeId:e.getLocalNodeId()});e.isListening();){let{done:a,value:c}=await s.read();if(a)throw new Error("incoming stream reader closed unexpectedly");if(!c)continue;let l=ut(c);l!=="uni"&&c$1("[Client][INCOMING] Received stream from WASM node",{type:l,endpointId:je(c)});try{await e.handleIncomingStream(c);}catch(p){let u=c,g=ut(u),y=je(u);console.error("[Client][INCOMING] Failed to handle incoming stream",{remoteNodeId:y,type:g,error:p});}}}catch(o){if(!e.isListening())break;t+=1;let s=x$1(t,e.retryMinDelayMs,e.retryMaxDelayMs);console.warn("[Client][INCOMING] Listen loop restarting after stream failure",{attempt:t,delayMs:s,mobile:he(),error:o}),await u(s);}finally{if(i)try{i.releaseLock(),e.shouldVerboseIncomingDiagnostics()&&c$1("[Client][INCOMING][MOBILE] direct listen reader released",{localNodeId:e.getLocalNodeId()});}catch{}}}}async handleIncomingStream(e,t){let n=await t.normalizeIncomingStreamEvent(e,{inspectChannelEnvelope:t.shouldInspectIncomingChannelEnvelope()}),i=t.buildApplicationIncomingStreamEvent(n);if(!n.invalid&&i.invalid)return;if(this.isInternalSessionChannel(i.channel?.channelId)){await t.handleUnhandledIncomingStreamEvent(i);return}if(this.dispatchIncomingChannelListeners(i))return;if(n.protocolHint==="native-main"){await t.handleUnhandledIncomingStreamEvent(n);return}this.dispatchIncomingGenericListeners(i)||await t.handleUnhandledIncomingStreamEvent(n);}async normalizeIncomingStreamEvent(e,t,n){let i="bi",o=e,s="",a=null,c=null,l=null,p={present:false,channel:null},u=false;try{u="type"in e;}catch{u=false;}if(u){i=ut(e);try{o=e.stream;}catch{o=null;}let S=je(e);s=S==="unknown"?"":S,a=$i(e),l=bs(e),p=Ss(e);}else {try{s=e.endpoint_id??"";}catch{s="";}a=$i(e);}let g=n.nextIncomingTraceId("incoming",s);l=n.normalizeAuthoritativeIncomingProtocolHint(l,s,g);let y$1=p.present&&p.channel!==null;n.logIncomingDiagnostic("normalize:start",{traceId:g,hasType:u,type:i,endpointId:s||"unknown",inspectChannelEnvelope:!!t?.inspectChannelEnvelope,authoritativeProtocolHint:l??null,authoritativeChannel:y$1}),i!=="uni"&&c$1("[Client][INCOMING] handleIncomingStream called",{hasType:u,type:i,endpointId:s});let m="unknown",v=l===null&&!!t?.inspectChannelEnvelope;if(i==="bi"){let S=z(o,s,a);if(!S||!y(S)){let T=false,D=false;try{T=!!o?.send;}catch{}try{D=!!o?.recv;}catch{}return console.error("[Client][INCOMING] Invalid bidirectional stream payload",{remoteNodeId:s,...a?{transportStableId:a}:{},hasSend:T,hasRecv:D}),{type:"bi",stream:o,remoteNodeId:s,...a?{transportStableId:a}:{},traceId:g,protocolHint:"unknown",channel:null,applicationCrypto:n.resolveApplicationCryptoStreamTools(s),invalid:true}}o=S,a=S.transport_stable_id??a;let I=false;if(l===null&&!y$1&&n.shouldStripIncomingMainLabel()){let T=await n.detectNativeMainStream(o,s,g);o=T.stream,I=true,m=T.protocolHint;}else l==="native-main"&&(m="native-main");if(m!=="native-main"){if(y$1)c=p.channel;else if(v){let _=await n.extractIncomingChannelEnvelope(o,s,g);o=_.stream,c=_.channel;}if(!(l==="explicit"||l==="control"||l==="native-main")&&!n.isTransportOnlyChannel(c?.channelId)&&(l!==null||y$1||c)&&(o=n.maybeWrapIncomingBiStreamWithApplicationCrypto(o,s,g)),l!==null)m=l,n.logIncomingDiagnostic("bi:use-authoritative-metadata",{traceId:g,endpointId:s||"unknown",protocolHint:m,hasChannelEnvelope:!!c});else if(n.shouldSkipIncomingBiProbeForRemoteNode(s)){let _=n.inferTicketFlowBiProtocolHint(s);if(m=_.protocolHint,n.logIncomingDiagnostic("bi:skip-probe-ticket-flow",{traceId:g,endpointId:s||"unknown",inferredProtocolHint:m,hasExistingConnection:_.hasExistingConnection,hasMagicLinkScope:_.hasMagicLinkScope}),!c&&!I&&n.shouldStripIncomingMainLabel()){let E=await n.detectNativeMainStream(o,s,g);o=E.stream,m=E.protocolHint;}}else {let _=await n.classifyBiIncomingStream(o,g);if(o=_.stream,m=_.protocolHint,m!=="explicit"&&!I&&n.shouldStripIncomingMainLabel()){let E=await n.detectNativeMainStream(o,s,g);o=E.stream,m=E.protocolHint;}}}let k=!n.shouldSkipIncomingStreamProbe()&&!n.isTransportOnlyChannel(c?.channelId);if(k&&m==="explicit"&&o?.applicationCryptoWrapped!==true)o=await n.maybeOpenEncryptedExplicitBiStream(o,g,s);else if(k&&m==="control"&&o?.applicationCryptoWrapped!==true&&(o=await n.maybeOpenEncryptedControlBiStream(o,g,s),o?.applicationCryptoWrapped===true)){let T=await n.classifyBiIncomingStream(o,g);o=T.stream,m=T.protocolHint,n.logIncomingDiagnostic("bi:reclassify-decrypted-stream",{traceId:g,endpointId:s||"unknown",protocolHint:m});}if(!c&&v&&o?.applicationCryptoWrapped===true){let T=await n.extractIncomingChannelEnvelope(o,s,g);o=T.stream,c=T.channel;}}else if(i==="uni"&&o&&typeof o.getReader=="function"){let S=await this.uniStreamNormalizer.normalize(o,{endpointId:s,traceId:g,inspectChannelEnvelope:v,authoritativeChannel:y$1?p.channel:null},n);o=S.stream,c=S.channel;}return n.logIncomingDiagnostic("normalize:done",{traceId:g,endpointId:s||"unknown",type:i,protocolHint:m,hasChannelEnvelope:!!c}),{type:i,stream:o,remoteNodeId:s,...a?{transportStableId:a}:{},traceId:g,protocolHint:m,channel:c,applicationCrypto:n.resolveApplicationCryptoStreamTools(s)}}async extractIncomingChannelEnvelope(e,t,n,i){return this.protocolInspector.extractIncomingChannelEnvelope(e,t,n,i)}async classifyBiIncomingStream(e,t,n){let i=this.deps?.explicitProtocolByte??0;return this.protocolInspector.classifyBiIncomingStream(e,i,t,n)}maybeWrapIncomingBiStreamWithApplicationCrypto(e,t,n,i){return this.cryptoProbe.maybeWrapIncomingBiStreamWithApplicationCrypto(e,t,n,i)}async maybeOpenEncryptedExplicitBiStream(e,t,n,i,o){return this.cryptoProbe.maybeOpenEncryptedExplicitBiStream(e,t,n,i,o)}async maybeOpenEncryptedControlBiStream(e,t,n,i,o){return this.cryptoProbe.maybeOpenEncryptedControlBiStream(e,t,n,i,o)}async detectNativeMainStream(e,t,n,i,o){return this.protocolInspector.detectNativeMainStream(e,t,n,i,o)}maybeHandleWebRTCExplicitFileEnvelope(e,t){return this.disposed||!this.deps?false:this.webRTCExplicitTransferAssembler.maybeHandle(e,t,this.deps)}};function Ps(r){let{host:e}=r;return new Kn({explicitProtocolByte:2,defaultChannels:ar,registerDisposer:t=>e.registerDisposer(t),openWebRTCExplicitTransferPayload:(t,n)=>e.openWebRTCExplicitTransferPayload(t,n),dispatchSyntheticExplicitIncomingStream:(t,n)=>r.getApplicationIncoming().dispatchSyntheticExplicitIncomingStream(t,n)})}function _s(r){let{host:e}=r,t=e.getPresenceForIncomingListen();return new On(e.getContext(),{ensureWasmRuntimeForP2P:()=>e.ensureWasmRuntimeForP2P(),startPresenceForListen:()=>t.startPresenceLoopForListen(),setOfflinePresence:()=>{t.setOffline();},shouldInspectIncomingChannelEnvelope:()=>r.getDiagnostics().shouldInspectIncomingChannelEnvelope(),handleIncomingStream:n=>r.getRouter().handleIncomingStream(n,{shouldInspectIncomingChannelEnvelope:()=>r.getDiagnostics().shouldInspectIncomingChannelEnvelope(),normalizeIncomingStreamEvent:(i,o)=>r.getNormalizer().normalize(i,o),buildApplicationIncomingStreamEvent:i=>r.getApplicationIncoming().buildApplicationIncomingStreamEvent(i),handleUnhandledIncomingStreamEvent:i=>e.handleUnhandledIncomingStreamEvent(i)}),hasIncomingChannelListener:n=>r.getRouter().hasIncomingChannelListener(n),hasAnyIncomingChannelListeners:()=>r.getRouter().hasAnyIncomingChannelListeners(),isInternalSessionChannel:n=>r.getRouter().isInternalSessionChannel(n),normalizeIncomingStreamEvent:(n,i)=>r.getNormalizer().normalize(n,i),dispatchIncomingChannelListeners:n=>r.getRouter().dispatchIncomingChannelListeners(n),dispatchIncomingGenericListeners:n=>r.getRouter().dispatchIncomingGenericListeners(n),handleUnhandledIncomingStreamEvent:n=>e.handleUnhandledIncomingStreamEvent(n),shouldVerboseIncomingDiagnostics:()=>r.getDiagnostics().shouldVerboseIncomingDiagnostics(),getIncomingStreamRouter:()=>r.getRouter(),retryMinDelayMs:er,retryMaxDelayMs:tr})}function ws(r,e){return new Hn({getOptions:()=>r.getOptions(),getRuntimeSafetyProfileOverride:()=>r.getRuntimeSafetyProfile(),hasAnyIncomingChannelListeners:()=>e().hasAnyIncomingChannelListeners(),requiresIncomingChannelEnvelopeInspection:()=>e().requiresIncomingChannelEnvelopeInspection()})}function Ts(r){let{host:e}=r;return new Un({explicitProtocolByte:2,maxEncryptedFrameBytes:16777216,probeDeadlineMs:zo,nativeMainProtocolByte:Nt,nativeMainLabel:Dt,nativeMainMaxLabelBytes:Mt,explicitApplicationCryptoWaitMs:1500},{router:r.getRouter(),nextIncomingTraceId:(t,n)=>r.getDiagnostics().nextIncomingTraceId(t,n),logIncomingDiagnostic:(t,n)=>r.getDiagnostics().logIncomingDiagnostic(t,n),releaseReaderLock:(t,n,i)=>r.getDiagnostics().safeReleaseReaderLock(t,n,i),shouldSkipIncomingStreamProbe:()=>r.getDiagnostics().shouldSkipIncomingStreamProbe(),shouldSkipIncomingBiProbeForRemoteNode:t=>e.shouldSkipIncomingBiProbeForRemoteNode(t),inferTicketFlowBiProtocolHint:t=>e.inferTicketFlowBiProtocolHint(t),isTransportOnlyChannel:t=>e.isTransportOnlyChannel(t),resolveApplicationCryptoForPeer:t=>e.resolveApplicationCryptoForPeer(t),waitForApplicationCryptoForPeer:(t,n)=>e.waitForApplicationCryptoForPeer(t,n),resolveApplicationCryptoStreamTools:t=>e.resolveApplicationCryptoStreamTools(t)})}function As(r){let{host:e}=r;return new Fn({registerDisposer:t=>e.registerDisposer(t),resolveApplicationCryptoStreamTools:t=>e.resolveApplicationCryptoStreamTools(t),logIncomingDiagnostic:(t,n)=>r.getDiagnostics().logIncomingDiagnostic(t,n),isTransportOnlyChannel:t=>e.isTransportOnlyChannel(t),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),hasTransportOnlyConnectionForRemoteNode:t=>e.hasTransportOnlyConnectionForRemoteNode(t),isManagedApplicationStreamAuthorized:t=>e.isManagedApplicationStreamAuthorized(t),getConnectionChannelId:t=>e.getConnectionChannelId(t),dispatchIncomingChannelListeners:t=>r.getRouter().dispatchIncomingChannelListeners(t),dispatchIncomingGenericListeners:t=>r.getRouter().dispatchIncomingGenericListeners(t),handleUnhandledIncomingStreamEvent:t=>e.handleUnhandledIncomingStreamEvent(t)})}function ks(r){return new Bn(r.getContext(),{ensureWasmRuntimeForP2P:()=>r.ensureWasmRuntimeForP2P(),getApplicationCryptoForPeer:e=>r.resolveApplicationCryptoForPeer(e)})}function Ns(r){return new Yi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getRuntimeSafetyProfile:()=>r.runtimeSafetyProfile,registerDisposer:e=>r.lifecycleScope.register(e),ensureWasmRuntimeForP2P:()=>r.runtimeReadiness.ensureWasmRuntimeForP2P(),getPresenceForIncomingListen:()=>r.presence,openWebRTCExplicitTransferPayload:(e,t)=>r.applicationCrypto.openWebRTCExplicitTransferPayload(e,t),dispatchSyntheticExplicitIncomingStream:(e,t)=>r.applicationIncomingStreams.dispatchSyntheticExplicitIncomingStream(e,t),handleUnhandledIncomingStreamEvent:e=>r.incomingConnectionAcceptor.handleUnhandledIncomingStreamEvent(e),shouldSkipIncomingBiProbeForRemoteNode:e=>r.transportHealth.shouldSkipIncomingBiProbeForRemoteNode(e),inferTicketFlowBiProtocolHint:e=>r.peerIdentity.inferTicketFlowBiProtocolHint(e),isTransportOnlyChannel:e=>r.connectionChannelPolicy.isTransportOnlyChannel(e),hasTransportOnlyConnectionForRemoteNode:e=>r.transportHealth.hasTransportOnlyConnectionForRemoteNode(e),isManagedApplicationStreamAuthorized:e=>{if(!(r.runtimeStatus.usesTicketOnlySignalingMode()||r.runtimeStatus.requiresManagedTransportTrust(r.discoveryMode)))return true;let n=e?.trim();return n?r.sessionTokens.isApproved(r.peerIdentity.getDeterministicConnectionId(n),n):false},getConnectionChannelId:e=>r.connectionChannelPolicy.getConnectionChannelId(e),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),resolveApplicationCryptoForPeer:e=>r.applicationCrypto.resolveForPeer(e),waitForApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.waitForPeer(e,t),resolveApplicationCryptoStreamTools:e=>r.applicationCrypto.resolveStreamTools(e)})}var Yi=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getRouter:()=>this.router,getDiagnostics:()=>this.diagnostics,getNormalizer:()=>this.normalizer,getApplicationIncoming:()=>this.applicationIncoming}}get router(){return this._router??(this._router=Ps(this.factoryHost))}get listen(){return this._listen??(this._listen=_s(this.factoryHost))}get diagnostics(){return this._diagnostics??(this._diagnostics=ws(this.host,()=>this.router))}get normalizer(){if(this._normalizer||(this._normalizer=Ts(this.factoryHost)),!this._generationFencedNormalizer){let e=this._normalizer;this._generationFencedNormalizer=new Proxy(e,{get:(t,n)=>{if(n==="normalize")return async(o,s)=>(await this.assertCurrentIncomingTransport(o),e.normalize(o,s));let i=Reflect.get(e,n,e);return typeof i=="function"?i.bind(e):i}});}return this._generationFencedNormalizer}async assertCurrentIncomingTransport(e){let t=e,n;try{n=t.type;}catch{return}if(n!=="bi"&&n!=="uni")return;let i,o;try{i=t.endpointId??t.endpoint_id,o=t.transportStableId??t.transport_stable_id;}catch{throw new Error("Rejected incoming WASM stream with unreadable transport generation")}if(typeof i!="string"||i.trim().length===0||!Number.isSafeInteger(o)||Number(o)<=0)throw new Error("Rejected incoming WASM stream without a valid transport generation");let s=this.host.getContext().wasmClient;if(!s||typeof s.is_current_transport_stable_id!="function")throw new Error("Rejected incoming WASM stream because generation validation is unavailable");if(!await s.is_current_transport_stable_id(i.trim(),BigInt(Number(o))))throw new Error("Rejected incoming WASM stream from a retired transport generation")}get applicationIncoming(){return this._applicationIncoming??(this._applicationIncoming=As(this.factoryHost))}get applicationStreams(){return this._applicationStreams??(this._applicationStreams=ks(this.host))}prepareListenForSignOut(){this._listen?.prepareForSignOut();}stopListenIfExists(){this._listen?.stop();}};function zn(r,e,t,n){if(!r||r.isClosed)return false;if(!(typeof r.isApplicationCryptoRequired=="function"?r.isApplicationCryptoRequired():false))return true;let o=n??r.remoteNodeId??t??r.deviceId;return !!e(o,r)}function Ji(r){return !r||r.isClosed?false:typeof r.isWebRtcApplicationRouteReady=="function"?r.isWebRtcApplicationRouteReady():false}var Qn=class{constructor(e,t){this.ctx=e;this.deps=t;this.recoveryInFlight=new Set;this.failedConnectionIds=new Set;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true,this.recoveryInFlight.clear(),this.failedConnectionIds.clear();}hasApplicationRouteForPeer(e,t){let n=this.deps.getConnectionForPeer(e,t);return zn(n,this.deps.resolveApplicationCryptoForPeer,e,t)}hasApplicationRouteForConnection(e){return zn(e,this.deps.resolveApplicationCryptoForPeer,e?.id,e?.remoteNodeId)}notifyApplicationRouteReady(e,t){this.disposed||e.isClosed||!this.hasApplicationRouteForConnection(e)||(this.failedConnectionIds.delete(e.id),c$1("[Client][HANDSHAKE] application route ready",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t}),this.deps.hasRustPeerLifecycleProjection()?this.schedulePeerReconciliationBestEffort("application-route-ready"):this.deps.applyConnectionTrustProjection(e),this.deps.isConnectionAnnounced(e.id)||this.deps.announceConnectionWhenStable(e));}async waitForApplicationRouteForConnection(e,t,n){let i=Date.now()+t;for(;!e.isClosed;){if(this.disposed)return false;if(this.hasApplicationRouteForConnection(e))return true;if(Date.now()>=i)return false;await u(n);}return false}async waitForReciprocalKeyAgreementObservation(e,t,n){let i=Date.now()+n;for(;!e.isClosed;){if(this.disposed||this.ctx.registry.get(e.id)!==e)return false;if(e.getApplicationKeyAgreementObservationEpoch()>t)return true;if(Date.now()>=i)return false;await u(Math.min(50,Math.max(1,n)));}return false}isWebRtcApplicationRouteReadyForConnection(e){return Ji(e)}async sendApplicationRouteHandshakeAttempt(e,t,n,i,o,s="capability-update"){if(!this.disposed){c$1("[Client][HANDSHAKE] refreshing application route handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,action:s,attempt:n+1,maxAttempts:i,preferNativeSignalRoute:o});try{o?await this.deps.sendTransportHandshake(e,s,null,{preferNativeSignalRoute:!0}):await this.deps.sendTransportHandshake(e,s);}catch(a){if(this.disposed)return;console.warn("[Client][HANDSHAKE] application route handshake send failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,action:s,attempt:n+1,error:a});}}}async refreshApplicationRouteHandshake(e,t,n={}){if(this.disposed||e.isClosed||!this.deps.shouldNegotiateApplicationKeyAgreement())return;let i=this.deps.resolveApplicationCryptoForPeer(e.remoteNodeId,e);i&&e.setApplicationCrypto(i);let o=this.hasApplicationRouteForConnection(e);if(o&&!n.forceReciprocal){this.notifyApplicationRouteReady(e,t);return}if(o&&n.forceReciprocal){let c=Math.min(3,this.deps.maxRecoveryAttempts);for(let l=0;l<c;l+=1){let p=e.getApplicationKeyAgreementObservationEpoch();if(await this.sendApplicationRouteHandshakeAttempt(e,t,l,c,true,"response"),await this.waitForReciprocalKeyAgreementObservation(e,p,this.deps.attemptWaitMs)){this.notifyApplicationRouteReady(e,`${t}:reciprocal-confirmed`);return}if(this.disposed||e.isClosed||this.ctx.registry.get(e.id)!==e)return;let u$1=this.deps.backoffMs[Math.min(l,this.deps.backoffMs.length-1)]??0;u$1>0&&await u(u$1);}throw this.failedConnectionIds.add(e.id),this.schedulePeerReconciliationBestEffort("application-route-reciprocal-handshake-exhausted"),new Error(`[Client][HANDSHAKE] reciprocal application key agreement timed out for ${e.id}`)}if(this.recoveryInFlight.has(e.id))return;this.failedConnectionIds.delete(e.id);let s=this.deps.getConnectionControlFrameMode(e),a=t==="connect-existing"?"hello":"capability-update";if(await this.sendApplicationRouteHandshakeAttempt(e,t,0,this.deps.maxRecoveryAttempts,false,a),!this.disposed){if(await this.waitForApplicationRouteForConnection(e,this.deps.attemptWaitMs,50)){this.notifyApplicationRouteReady(e,t);return}if(!this.disposed){if(this.deps.hydrateAdoptedConnectionApplicationCrypto(e,t)){this.failedConnectionIds.delete(e.id);return}if(s==="native-main"&&!e.isClosed&&!this.hasApplicationRouteForConnection(e)){if(await this.sendApplicationRouteHandshakeAttempt(e,t,1,this.deps.maxRecoveryAttempts,true,a),this.disposed)return;if(await this.waitForApplicationRouteForConnection(e,this.deps.attemptWaitMs,50)){this.notifyApplicationRouteReady(e,t);return}if(this.disposed)return;if(this.deps.hydrateAdoptedConnectionApplicationCrypto(e,t)){this.failedConnectionIds.delete(e.id);return}}e.isClosed||this.hasApplicationRouteForConnection(e)||this.driveApplicationRouteRecoveryInBackground(e,t);}}}handleApplicationRouteMissing(e,t){if(this.disposed)return;let n=this.ctx.registry.get(e);!n||n.isClosed||n.id!==t.connectionId||n.remoteNodeId===t.remoteNodeId&&(c$1("[Client][HANDSHAKE] WebRTC route proof is waiting on application crypto; refreshing handshake",{connectionId:e,remoteNodeId:t.remoteNodeId,reason:t.reason,negotiationId:t.negotiationId??null}),this.refreshApplicationRouteAfterProofInBackground(n,t));}refreshApplicationRouteAfterProofInBackground(e,t){let n=i=>{this.disposed||console.warn("[Client][HANDSHAKE] application route refresh after WebRTC proof failed",{connectionId:t.connectionId,remoteNodeId:t.remoteNodeId,reason:t.reason,error:i});};try{Promise.resolve(this.refreshApplicationRouteHandshake(e,t.reason)).catch(n);}catch(i){n(i);}}async driveApplicationRouteRecovery(e,t){if(this.disposed||this.recoveryInFlight.has(e.id))return;this.recoveryInFlight.add(e.id);let n=this.deps.getConnectionControlFrameMode(e),i=this.deps.maxRecoveryAttempts;try{for(let o=2;o<i;o+=1){if(this.disposed||e.isClosed)return;if(this.hasApplicationRouteForConnection(e)){this.notifyApplicationRouteReady(e,t);return}let s=this.deps.backoffMs[Math.min(o,this.deps.backoffMs.length-1)];if(s>0){if(await u(s),this.disposed)return;if(e.isClosed||this.hasApplicationRouteForConnection(e)){e.isClosed||this.notifyApplicationRouteReady(e,t);return}}let a=n==="native-main"&&o%2===1;if(await this.sendApplicationRouteHandshakeAttempt(e,t,o,i,a),this.disposed)return;if(await this.waitForApplicationRouteForConnection(e,this.deps.attemptWaitMs,50)){this.notifyApplicationRouteReady(e,t);return}if(this.disposed)return;if(this.deps.hydrateAdoptedConnectionApplicationCrypto(e,t)){this.failedConnectionIds.delete(e.id);return}}if(e.isClosed||this.hasApplicationRouteForConnection(e)){e.isClosed||this.notifyApplicationRouteReady(e,t);return}this.failedConnectionIds.add(e.id),console.warn("[Client][HANDSHAKE] application route recovery exhausted; marking route failed",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,controlFrameMode:n,attempts:i}),this.schedulePeerReconciliationBestEffort("application-route-handshake-exhausted");}finally{this.recoveryInFlight.delete(e.id);}}clearFailure(e){let t=typeof e=="string"?e.trim():"";t&&this.failedConnectionIds.delete(t);}hasFailure(e){let t=typeof e=="string"?e.trim():"";return !!t&&this.failedConnectionIds.has(t)}driveApplicationRouteRecoveryInBackground(e,t){if(!this.disposed)try{Promise.resolve(this.driveApplicationRouteRecovery(e,t)).catch(()=>{});}catch{}}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};var $n=class{constructor(e,t){this.ctx=e;this.deps=t;}getDeterministicConnectionId(e){return this.ctx.localNodeId?this.ctx.localNodeId<=e?`${this.ctx.localNodeId}-${e}`:`${e}-${this.ctx.localNodeId}`:`native-main-${e}`}getNativeMainConnectionId(e){return this.getDeterministicConnectionId(e)}findManualDisconnectProjectionForNativeNode(e){let t=typeof e=="string"?e.trim().toLowerCase():"";if(!t)return null;let n=this.getNativeMainConnectionId(e).trim().toLowerCase(),i=o=>{if(!o)return false;let s=String(o.status??"").toLowerCase(),a=String(o.error??"").toLowerCase();return (s==="closed"||s==="disconnected"||s==="failed")&&a.includes("manual disconnect")};for(let o of [e,n]){let s=this.deps.getPeerState(o);if(i(s))return s}return this.deps.listPeerStates().find(o=>{if(!i(o))return false;let s=String(o.nodeId??"").trim().toLowerCase(),a=String(o.connectionId??"").trim().toLowerCase(),c=Array.isArray(o.connectionIds)?o.connectionIds.map(l=>String(l??"").trim().toLowerCase()):[];return s===t||a===n||a.endsWith(`-${t}`)||c.includes(n)||c.some(l=>l.endsWith(`-${t}`))})??null}hasKnownConnectionForRemoteNode(e){let t=typeof e=="string"?e.trim():"";if(!t)return false;if(this.ctx.registry.has(this.getDeterministicConnectionId(t)))return true;for(let n of this.ctx.registry.values()){let i=n;if(i.id===t||i.remoteNodeId===t||i.deviceId===t)return true}return false}inferTicketFlowBiProtocolHint(e){let t=typeof e=="string"?e.trim():"",n=this.hasKnownConnectionForRemoteNode(t),i=false;try{let o=this.deps.getPeerState(t);i=Array.isArray(o?.scopes)&&o.scopes.includes("magic-link");}catch{i=false;}return {protocolHint:this.deps.hasAnyIncomingChannelListeners()||this.deps.hasIncomingStreamListeners()||i?"explicit":"control",hasExistingConnection:n,hasMagicLinkScope:i}}};var Vn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}hasTransportOnlyConnectionForRemoteNode(e){if(this.disposed)return false;let t=typeof e=="string"?e.trim():"";if(!t)return false;for(let n of this.ctx.registry.values())if(n.remoteNodeId===t&&this.deps.isTransportOnlyConnectionId(n.id))return true;return false}shouldSkipIncomingBiProbeForRemoteNode(e){return this.disposed||!this.deps.getRuntimeSafetyProfile().skipIncomingBiProbe?false:this.deps.usesTicketOnlySignalingMode()?true:this.hasTransportOnlyConnectionForRemoteNode(e)}async disconnectNodeTransport(e){if(this.disposed||!e||!e.trim())return;let t=this.ctx.wasmClient;if(t&&typeof t.disconnect=="function")try{await t.disconnect(e);}catch{}this.disposed||this.deps.notifyDisconnectRequested(e);}async isCoreConnectionHealthy(e){if(this.disposed||!e)return false;let t=this.ctx.wasmClient;if(t&&typeof t.is_connected=="function")try{let n=!!await t.is_connected(e);return this.disposed?!1:n}catch{}try{let n=await this.deps.isConnected(e);return this.disposed?!1:n}catch{return false}}handleConnectionTransportStatus(e,t,n){this.disposed||this.reportConnectionTransportStatus(e,t,n);}handleCurrentConnectionTransportStatus(e,t,n){return this.disposed?Promise.resolve(false):this.reportCurrentConnectionTransportStatus(e,t,n).then(i=>i!==null)}async reportCurrentConnectionTransportStatus(e,t,n){if(this.disposed||!this.matchesCurrentConnectionIdentityRoute(e,t,n))return null;let i=await this.readCurrentGenerationSnapshot(e.id);return !i||!this.matchesCurrentConnectionIdentityRoute(e,t,n)?null:this.reportConnectionTransportStatus(e.id,t,n,i.transportStableId,i.transportGeneration,i.routeGeneration)}handleConnectionApplicationRouteReady(e,t){this.disposed||this.reportConnectionApplicationRouteReady(e,t);}handleCurrentConnectionApplicationRouteReady(e,t){this.disposed||this.reportCurrentConnectionApplicationRouteReady(e,t);}async reportConnectionTransportStatus(e,t,n,i,o,s,a=true){if(this.disposed||!this.matchesCurrentConnectionRoute(e,t,n))return null;let c=await this.readCurrentGenerationObservation(e,i,o,s);if(!c||!this.matchesCurrentConnectionRoute(e,t,n))return null;let l=this.ctx.wasmClient;if(!l||typeof l.report_transport_status!="function")return null;try{let p=await l.report_transport_status(e,t,n??null,BigInt(c.transportStableId),BigInt(c.transportGeneration),BigInt(c.routeGeneration));return this.disposed||p==null?null:(a&&this.deps.hasRustPeerLifecycleProjection()&&this.schedulePeerReconciliationBestEffort("transport-status-report"),this.generationObservationFromSnapshot(p))}catch(p){return this.disposed||c$1("[Client] Failed to report active transport to Rust",{connectionId:e,activeTransport:t,parallelTransport:n??null,error:p}),null}}async reportConnectionApplicationRouteReady(e,t){if(this.disposed)return;let n=await this.reportConnectionTransportStatus(e,t.activeTransport,t.parallelTransport??null,t.transportStableId,t.transportGeneration,t.routeGeneration,false);n&&await this.settleConnectionApplicationRoute(e,t.activeTransport,t.parallelTransport??null,n);}async reportCurrentConnectionApplicationRouteReady(e,t){if(this.disposed||!this.matchesCurrentConnectionIdentityRoute(e,t.activeTransport,t.parallelTransport))return false;let n=null;for(let i=0;i<2&&!n;i+=1){let o=await this.readCurrentGenerationSnapshot(e.id);if(!o||!this.matchesCurrentConnectionIdentityRoute(e,t.activeTransport,t.parallelTransport))return false;n=await this.reportConnectionTransportStatus(e.id,t.activeTransport,t.parallelTransport??null,o.transportStableId,o.transportGeneration,o.routeGeneration,false),!n&&i===0&&await Promise.resolve();}return !n||!this.matchesCurrentConnectionIdentityRoute(e,t.activeTransport,t.parallelTransport)?false:this.settleConnectionApplicationRoute(e.id,t.activeTransport,t.parallelTransport??null,n)}async settleConnectionApplicationRoute(e,t,n,i){if(this.disposed||!this.matchesCurrentConnectionRoute(e,t,n))return false;let o=this.ctx.wasmClient;if(!o||typeof o.report_managed_connection_settled!="function")return false;try{let s=await o.report_managed_connection_settled(e,!0,null,BigInt(i.transportStableId),BigInt(i.transportGeneration),BigInt(i.routeGeneration));return this.disposed||s==null||!this.matchesCurrentConnectionRoute(e,t,n)?!1:(this.deps.hasRustPeerLifecycleProjection()&&this.schedulePeerReconciliationBestEffort("application-route-ready"),!0)}catch(s){return this.disposed||c$1("[Client] Failed to settle proven application route in Rust",{connectionId:e,activeTransport:t,parallelTransport:n,error:s}),false}}async readCurrentGenerationObservation(e,t,n,i){if(!Number.isSafeInteger(t)||Number(t)<=0||!Number.isSafeInteger(n)||Number(n)<=0||!Number.isSafeInteger(i)||Number(i)<0)return null;let o=await this.readCurrentGenerationSnapshot(e);return !o||t!==o.transportStableId||n!==o.transportGeneration||i!==o.routeGeneration?null:o}async readCurrentGenerationSnapshot(e){let t=this.ctx.wasmClient;if(!t||typeof t.connection_state!="function")return null;try{let n=await t.connection_state(e);if(this.disposed||!n||typeof n!="object")return null;let i=n,o=typeof i.activeTransportStableId=="number"?i.activeTransportStableId:i.active_transport_stable_id,s=typeof i.transportGeneration=="number"?i.transportGeneration:i.transport_generation,a=typeof i.routeGeneration=="number"?i.routeGeneration:i.route_generation;return !Number.isSafeInteger(o)||Number(o)<=0||!Number.isSafeInteger(s)||Number(s)<=0||!Number.isSafeInteger(a)||Number(a)<0?null:{transportStableId:Number(o),transportGeneration:Number(s),routeGeneration:Number(a)}}catch{return null}}generationObservationFromSnapshot(e){if(!e||typeof e!="object")return null;let t=e,n=t.activeTransportStableId??t.active_transport_stable_id,i=t.transportGeneration??t.transport_generation,o=t.routeGeneration??t.route_generation;return !Number.isSafeInteger(n)||Number(n)<=0||!Number.isSafeInteger(i)||Number(i)<=0||!Number.isSafeInteger(o)||Number(o)<0?null:{transportStableId:Number(n),transportGeneration:Number(i),routeGeneration:Number(o)}}matchesCurrentConnectionRoute(e,t,n){let i=this.ctx.registry.get(e);if(!i||i.isClosed||typeof i.getTransportStatus!="function")return false;let o=i.getTransportStatus();return o.activeTransport===t&&(o.parallelTransport??null)===(n??null)}matchesCurrentConnectionIdentityRoute(e,t,n){return this.ctx.registry.get(e.id)===e&&this.matchesCurrentConnectionRoute(e.id,t,n)}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};var Ac=[...c];function Ds({transportPriority:r,rankRoutes:e,disableIrohFallback:t,runtimeSafetyProfile:n,isMoQReady:i,isMoQDataReady:o,isMoQApplicationRouteProven:s,requestMoQApplicationRouteProof:a,clearMoQApplicationRouteProof:c,sendMoQ:l,sendIrohApplicationFrame:p}){let u=r||Ac;return {priorities:u,rankRoutes:e?g=>e(u,g):void 0,disableIrohFallback:t||false,isMoQReady:i,isMoQDataReady:o,isMoQApplicationRouteProven:s,requestMoQApplicationRouteProof:a,clearMoQApplicationRouteProof:c,sendMoQ:l,sendIrohApplicationFrame:p,runtimeFlow:n.flow,readerCloseStrategy:n.readerCloseStrategy}}var Yn=class{constructor(e){this.deps=e;}create(e){let t=this.deps.getOptions();return Ds({transportPriority:t?.transportPriority,rankRoutes:(n,i)=>this.deps.rankRoutes(n,i),disableIrohFallback:t?.disableIrohFallback,runtimeSafetyProfile:this.deps.getRuntimeSafetyProfile(),isMoQReady:()=>this.deps.isMoQReady(),isMoQDataReady:()=>this.deps.isMoQDataReady(e),isMoQApplicationRouteProven:()=>this.deps.isMoQApplicationRouteProven(e),requestMoQApplicationRouteProof:()=>this.deps.requestMoQApplicationRouteProof(e),clearMoQApplicationRouteProof:()=>this.deps.clearMoQApplicationRouteProof(e),sendMoQ:(n,i)=>this.deps.sendMoQ(e,n,i),sendIrohApplicationFrame:n=>this.deps.sendIrohApplicationFrame(e,n)})}};var Jn=class{constructor(e){this.deps=e;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}getConnectionControlFrameMode(e){return typeof e.getControlFrameMode=="function"?e.getControlFrameMode():"typed"}async sendConnectionControlEnvelope(e,t,n={}){if(this.disposed)return;if(this.getConnectionControlFrameMode(e)==="native-main"){if(n.preferNativeSignalRoute&&(typeof e.sendNativeControlEnvelope=="function"?await e.sendNativeControlEnvelope(t):false))return;try{await e.sendRawIrohFrame(me(Ae(t)));return}catch(o){if(typeof e.sendNativeControlEnvelope=="function"?await e.sendNativeControlEnvelope(t):false)return;throw o}}if(typeof e.sendControl=="function"){await e.sendControl(t);return}await e.send(t);}async sendTransportHandshake(e,t,n,i={}){if(this.disposed)return;let o=this.deps.shouldNegotiateApplicationKeyAgreement()?await this.deps.ensureConnectionKeyAgreementState(e):null;if(this.disposed)return;let s={webrtc:this.deps.isWebRTCTransportEnabled(),moq:this.deps.isMoQReady(),ble:this.deps.isBleTransportEnabled(),...o?{applicationKeyAgreement:true}:{}},a=t==="hello"?this.deps.getPendingSessionToken(e.remoteNodeId):void 0,c=t==="hello"?this.deps.getPendingSessionTokenPayload(e.remoteNodeId):void 0;c$1("[Client][HANDSHAKE] sending",{action:t,connectionId:e.id,remoteNodeId:e.remoteNodeId,channelId:this.deps.getConnectionChannelId(e.id)??null,capabilities:s,hasSessionToken:!!a,hasSessionTokenPayload:!!c,hasChallengeToSign:!!n});let l={type:"handshake",action:t,capabilities:s,moq:s.moq,channelId:this.deps.getConnectionChannelId(e.id)??void 0,...a?{sessionToken:a}:{},...a&&c?{sessionTokenPayload:c}:{},...o?{applicationKeyAgreement:Ho(o.publicKey)}:{}},p=await this.deps.buildLocalTransportTrustPayload(e,n);if(!this.disposed){if(c$1("[Client][HANDSHAKE] local trust payload status",{action:t,connectionId:e.id,remoteNodeId:e.remoteNodeId,hasTransportTrustPayload:!!p,hasChallengeInPayload:!!p?.challenge}),!p){if(this.deps.requiresManagedTransportTrust()){let u=this.deps.initializeConnectionTrust(e);u.failed=true,u.failureReason="local-trusted-identity-unavailable",console.warn("[Client][TRUST] Unable to attach local transport trust payload for managed trust handshake",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t});}await this.sendConnectionControlEnvelope(e,l,i),o&&this.deps.markConnectionApplicationCryptoRequired(e);return}await this.sendConnectionControlEnvelope(e,{...l,transportTrust:p},i),o&&this.deps.markConnectionApplicationCryptoRequired(e),c$1("[Client][HANDSHAKE] sent OK",{action:t,connectionId:e.id,remoteNodeId:e.remoteNodeId});}}async sendTransportHandshakeWithRecovery(e,t,n,i){for(let o=0;o<this.deps.maxRecoveryAttempts;o+=1){if(this.disposed)return;if(e.isClosed)throw new Error("[Client][HANDSHAKE] connection closed before handshake recovery completed");let s=this.getConnectionControlFrameMode(e)==="native-main"&&o%2===1;try{await this.sendTransportHandshake(e,t,n,{preferNativeSignalRoute:s}),t==="ack"&&!s&&this.getConnectionControlFrameMode(e)==="native-main"&&await this.sendTransportHandshake(e,t,n,{preferNativeSignalRoute:!0});return}catch(a){let c=o>=this.deps.maxRecoveryAttempts-1;if(console.warn("[Client][HANDSHAKE] control handshake send failed; retrying if budget remains",{connectionId:e.id,remoteNodeId:e.remoteNodeId,action:t,reason:i,attempt:o+1,maxAttempts:this.deps.maxRecoveryAttempts,preferNativeSignalRoute:s,finalAttempt:c,error:a}),c)throw a;let l=this.deps.recoveryBackoffMs[Math.min(o,this.deps.recoveryBackoffMs.length-1)]??0;if(l>0&&(await u(l),this.disposed))return}}}async broadcastTransportCapabilityUpdate(e){if(this.disposed)return;if(this.deps.isWebRTCTransportEnabled()){let o=this.deps.getRTCConfig();for(let s of this.deps.getConnections()){if(this.disposed)return;s.updateRTCConfig(o);}}if(this.disposed)return;let t=Array.from(this.deps.getConnections()).filter(o=>!o.isClosed).map(async o=>{await this.sendTransportHandshake(o,"capability-update");}),i=(await Promise.allSettled(t)).filter(o=>o.status==="rejected");i.length>0&&c$1("[Client] Some transport capability updates failed",{reason:e,failures:i.length});}requestProtectedWebRTCUpgradeIfInitiator(e,t){if(this.disposed)return;let n=this.deps.isSessionTokenApproved(e.id,e.remoteNodeId),i=this.deps.getLocalNodeId();!this.deps.usesTicketOnlySignalingMode()&&!n||!this.deps.isWebRTCTransportEnabled()||!i||!e.remoteNodeId||i.localeCompare(e.remoteNodeId)<=0||e.requestWebRTCUpgrade(t);}};function kc(r){let e=r.transports?.ble;return e===true||!!e&&typeof e=="object"&&e.enabled!==false}function Ms(r,e){return kc(r)&&e?.transport.ble===true}function xs(r){let{host:e}=r;return new Qn(e.getContext(),{getConnectionForPeer:(t,n)=>e.getConnectionForPeer(t,n)??null,resolveApplicationCryptoForPeer:(t,n)=>e.resolveApplicationCryptoForPeer(t,n),shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),hydrateAdoptedConnectionApplicationCrypto:(t,n)=>e.hydrateAdoptedConnectionApplicationCrypto(t,n),sendTransportHandshake:(t,n,i,o)=>r.getHandshake().sendTransportHandshake(t,n,i,o),getConnectionControlFrameMode:t=>r.getHandshake().getConnectionControlFrameMode(t),applyConnectionTrustProjection:t=>e.applyConnectionTrustProjection(t),announceConnectionWhenStable:t=>e.announceConnectionWhenStable(t),isConnectionAnnounced:t=>e.isConnectionAnnounced(t),hasRustPeerLifecycleProjection:()=>e.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:t=>e.schedulePeerReconciliation(t),maxRecoveryAttempts:15,attemptWaitMs:1e3,backoffMs:_i})}function Ls(r){let{host:e}=r;return new Jn({shouldNegotiateApplicationKeyAgreement:()=>e.shouldNegotiateApplicationKeyAgreement(),ensureConnectionKeyAgreementState:t=>e.ensureConnectionKeyAgreementState(t),isWebRTCTransportEnabled:()=>k(e.getOptions()),isMoQReady:()=>e.isMoQReady(),isBleTransportEnabled:()=>Ms(e.getOptions(),e.getRuntimeCapabilities()),getConnectionChannelId:t=>e.getConnectionChannelId(t),getPendingSessionToken:t=>e.getPendingSessionToken(t),getPendingSessionTokenPayload:t=>e.getPendingSessionTokenPayload(t),buildLocalTransportTrustPayload:(t,n)=>e.buildLocalTransportTrustPayload(t,n),requiresManagedTransportTrust:()=>e.requiresManagedTransportTrust(e.getDiscoveryMode()),initializeConnectionTrust:t=>e.initializeConnectionTrust(t),markConnectionApplicationCryptoRequired:t=>e.markConnectionApplicationCryptoRequired(t),getRTCConfig:()=>r.getRTCConfig(),getConnections:()=>e.getConnections(),usesTicketOnlySignalingMode:()=>e.usesTicketOnlySignalingMode(),isSessionTokenApproved:(t,n)=>e.isSessionTokenApproved(t,n),getLocalNodeId:()=>e.getLocalNodeId()||null,maxRecoveryAttempts:15,recoveryBackoffMs:_i,registerDisposer:t=>e.registerDisposer(t)})}function Fs(r){return new Vn(r.getContext(),{getRuntimeSafetyProfile:()=>r.getRuntimeSafetyProfile(),usesTicketOnlySignalingMode:()=>r.usesTicketOnlySignalingMode(),isTransportOnlyConnectionId:e=>r.isTransportOnlyConnectionId(e),notifyDisconnectRequested:e=>r.notifyDisconnectRequested(e),isConnected:e=>r.isBackendConnected(e),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:e=>r.schedulePeerReconciliation(e)})}function Bs(r){return new Yn({getOptions:()=>r.getOptions(),getRuntimeSafetyProfile:()=>r.getRuntimeSafetyProfile(),rankRoutes:(e,t)=>{let n=r.getWasmClient(),i=n?.rankRoutes??n?.rank_routes;if(typeof i!="function")return [...t];try{let o=i.call(n,e,t);return Array.isArray(o)?o:[...t]}catch(o){return c$1("[OpenRTC][route-policy] Rust ranking unavailable; preserving candidate order",{error:o instanceof Error?o.message:String(o)}),[...t]}},isMoQReady:()=>r.isMoQReady(),isMoQDataReady:e=>r.isMoQDataReady(e),isMoQApplicationRouteProven:e=>r.isMoQApplicationRouteProven(e),requestMoQApplicationRouteProof:e=>r.requestMoQApplicationRouteProof(e),clearMoQApplicationRouteProof:e=>r.clearMoQApplicationRouteProof(e),sendMoQ:(e,t,n)=>r.sendMoQData(e,t,n),sendIrohApplicationFrame:(e,t)=>r.sendIrohApplicationFrame(e,t)})}function Ws(r){return new $n(r.getContext(),{getPeerState:e=>r.getPeerState(e),listPeerStates:()=>r.listPeerStates(),hasAnyIncomingChannelListeners:()=>r.hasAnyIncomingChannelListeners(),hasIncomingStreamListeners:()=>r.hasIncomingStreamListeners()})}function Os(r){return new Xi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getRuntimeSafetyProfile:()=>r.runtimeSafetyProfile,getRuntimeCapabilities:()=>r.signalingBackendController.getRuntimeCapabilities(),getWasmClient:()=>r.wasmClient,registerDisposer:e=>r.lifecycleScope.register(e),getLocalNodeId:()=>r.localNodeId,getDiscoveryMode:()=>r.discoveryMode,hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),getPeerState:e=>r.peerServices.getPeerState(e),listPeerStates:()=>r.peerServices.listPeerStates(),getConnectionForPeer:(e,t)=>r.registry.getForPeer(e,t),getConnections:()=>r.registry.values(),getConnectionChannelId:e=>r.connectionChannelPolicy.getConnectionChannelId(e),isTransportOnlyConnectionId:e=>r.connectionChannelPolicy.isTransportOnlyConnectionId(e),getConnectionTrustState:e=>r.connectionTrust.getStateByConnectionId(e),buildLocalTransportTrustPayload:(e,t)=>r.connectionTrust.buildLocalTransportTrustPayload(e,t),initializeConnectionTrust:e=>r.connectionTrust.initialize(e),resolveApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.resolveForPeer(e,t),resolveExistingApplicationCryptoForPeer:(e,t)=>r.securityServices.resolveExistingApplicationCryptoForPeer(e,t),getConfiguredApplicationCrypto:()=>r.options?.applicationCrypto,shouldNegotiateApplicationKeyAgreement:()=>r.applicationCrypto.shouldNegotiateKeyAgreement(),hydrateAdoptedConnectionApplicationCrypto:(e,t)=>r.applicationCrypto.hydrateAdoptedConnection(e,t),ensureConnectionKeyAgreementState:e=>r.applicationCrypto.ensureConnectionKeyAgreementState(e),markConnectionApplicationCryptoRequired:e=>r.applicationCrypto.markRequired(e),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),announceConnectionWhenStable:e=>r.connectionLifecycle.announceConnectionWhenStable(e),isConnectionAnnounced:e=>r.connectionLifecycle.isConnectionAnnounced(e),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),isMoQReady:()=>r.moqServices.isReady(),isMoQDataReady:e=>r.moqServices.isDataReady(e),isMoQApplicationRouteProven:e=>r.moqServices.isApplicationRouteProven(e),requestMoQApplicationRouteProof:e=>r.moqServices.requestApplicationRouteProof(e),clearMoQApplicationRouteProof:e=>r.moqServices.clearApplicationRouteProof(e),sendMoQData:(e,t,n)=>r.moqServices.sendData(e,t,n),sendIrohApplicationFrame:(e,t)=>r.applicationStreams.sendFrame(e,t),getPendingSessionToken:e=>r.sessionTokens.getRouteRepairTokenForNode(e)??void 0,getPendingSessionTokenPayload:e=>r.sessionTokens.getRouteRepairTokenPayloadForNode(e)??void 0,requiresManagedTransportTrust:e=>r.runtimeStatus.requiresManagedTransportTrust(e??r.discoveryMode),isSessionTokenApproved:(e,t)=>r.sessionTokens.isApproved(e,t),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode(),notifyDisconnectRequested:e=>r.signalingBackendController.notifyDisconnectRequested(e),isBackendConnected:e=>r.signalingBackendController.isConnected(e),hasAnyIncomingChannelListeners:()=>r.incomingStreamRouter.hasAnyIncomingChannelListeners(),hasIncomingStreamListeners:()=>r.incomingStreamRouter.hasIncomingStreamListeners()})}var Xi=class{constructor(e){this.host=e;}get factoryHost(){return {host:this.host,getHandshake:()=>this.handshake,getRTCConfig:()=>this.getRTCConfig()}}get upgrade(){return this._upgrade??(this._upgrade=xs(this.factoryHost))}get handshake(){return this._handshake??(this._handshake=Ls(this.factoryHost))}get health(){return this._health??(this._health=Fs(this.host))}get contexts(){return this._contexts??(this._contexts=Bs(this.host))}get peerIdentity(){return this._peerIdentity??(this._peerIdentity=Ws(this.host))}getRTCConfig(){return l(this.host.getOptions(),e=>c$1(e))}hasApplicationRouteForConnectionSnapshot(e,t,n){return zn(e,(i,o)=>this.host.getConfiguredApplicationCrypto()??this.host.resolveExistingApplicationCryptoForPeer(i,o),t,n)}hasApplicationRouteForPeer(e,t){return this.hasApplicationRouteForConnectionSnapshot(this.host.getConnectionForPeer(e,t),e,t)}isWebRtcApplicationRouteReadyForConnectionSnapshot(e){return Ji(e)}hasApplicationRouteFailure(e){return this._upgrade?.hasFailure(e)??false}clearApplicationRouteFailure(e){this._upgrade?.clearFailure(e);}};var Xn=class{constructor(e){this.deps=e;this.channelIds=new Map;this.disposed=false;this.deps.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.channelIds.clear());}isChannelPromotionEligible(e){let t=this.deps.getRegisteredChannel(e);return t?t.promotionPolicy!=="never":true}isTransportOnlyChannel(e){return on(this.deps.getRegisteredChannel(e))}getConnectionChannelId(e){if(this.disposed)return null;let t=typeof e=="string"?e.trim():"";return t?this.channelIds.get(t)??null:null}isTransportOnlyConnectionId(e){return this.isTransportOnlyChannel(this.getConnectionChannelId(e))}allowsTransportOnlyStability(e){return this.deps.usesTicketOnlySignalingMode()||this.isTransportOnlyConnectionId(e.id)}resolvePromotionEligibility(e){if(this.disposed)return false;let t=this.getConnectionChannelId(e.connectionId);if(t)return this.isChannelPromotionEligible(t);let n=typeof e.nodeId=="string"?e.nodeId.trim():"";for(let i of this.deps.getConnections()){if(e.connectionId&&i.id===e.connectionId)return this.isChannelPromotionEligible(this.getConnectionChannelId(i.id));if(n&&i.remoteNodeId===n)return this.isChannelPromotionEligible(this.getConnectionChannelId(i.id))}return true}assign(e,t){if(this.disposed)return;let n=typeof t=="string"?t.trim():"";if(!n)return;this.channelIds.set(e.id,n);let i=this.deps.getConnectionTrustState(e.id);if(i&&!this.isChannelPromotionEligible(n)&&(i.required=false,i.verified=true,i.failed=false,i.failureReason=void 0,i.issuedChallenge=null,i.verifiedDeviceId||(i.verifiedDeviceId=i.expectedDeviceId||this.deps.getKnownDeviceIdByNodeId(e.remoteNodeId)||null)),this.deps.hasRustPeerLifecycleProjection())this.schedulePeerReconciliationBestEffort("session-token-trust-approved");else for(let o of this.deps.getConnections())if(o.id===e.id){this.deps.applyConnectionTrustProjection(o);break}}forget(e){if(this.disposed)return;let t=typeof e=="string"?e.trim():"";t&&this.channelIds.delete(t);}schedulePeerReconciliationBestEffort(e){if(!this.disposed)try{Promise.resolve(this.deps.schedulePeerReconciliation(e)).catch(()=>{});}catch{}}};var Zn=class{constructor(e,t){this.ctx=e;this.deps=t;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed=true;}bindConnectionDeviceIdInRust(e,t){if(this.disposed)return;let n=t.trim();if(!n)return;let i=this.deps.getSessionTokenApprovedScope(e.id);if(i&&!this.deps.sessionTokenScopeAllowsDeviceBinding(i)){c$1("[Client][BIND] skipped transient session device binding",{connectionId:e.id,remoteNodeId:e.remoteNodeId,scope:i});return}let o=this.ctx.wasmClient,s=!!o&&typeof o.bind_connection_device_id=="function";c$1("[Client][BIND] bindConnectionDeviceIdInRust entered",{connectionId:e.id,remoteNodeId:e.remoteNodeId,deviceId:n,hasWasmClient:!!o,hasMethod:s}),this.deps.rememberKnownDeviceForNode(e.remoteNodeId,n);let a=this.deps.getApplicationCryptoForConnectionOrPeer(e.id,e.remoteNodeId);if(a&&this.deps.indexApplicationCryptoForPeer(n,a),!!s)try{Promise.resolve(o.bind_connection_device_id(e.id,n)).then(()=>{this.disposed||c$1("[Client][BIND] bind_connection_device_id resolved",{connectionId:e.id,deviceId:n});}).catch(c=>{this.disposed||console.warn("[Client][TRUST] Failed to bind deviceId on Rust connection record",{connectionId:e.id,remoteNodeId:e.remoteNodeId,deviceId:n,error:c});});}catch(c){if(this.disposed)return;console.warn("[Client][TRUST] Failed to bind deviceId on Rust connection record",{connectionId:e.id,remoteNodeId:e.remoteNodeId,deviceId:n,error:c});}}async rejectConnectionInRust(e,t){if(this.disposed)return;let n=this.ctx.wasmClient;if(!(!n||typeof n.reject_connection_admission!="function"))try{await n.reject_connection_admission(e.id,t);}catch(i){if(this.disposed)return;console.warn("[Client][TRUST] Failed to reject connection on Rust admission authority",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t,error:i});}}retireSupersededConnections(e,t,n){if(this.disposed)return;let i=t.trim();if(i)for(let o of this.ctx.registry.values())o.id===e.id||o.isClosed||this.deps.getLogicalDeviceIdForConnection(o.id)===i&&(c$1("[Client][CONNECTION] Retiring superseded connection for logical device",{keptConnectionId:e.id,retiredConnectionId:o.id,logicalDeviceId:i,reason:n}),this.disconnectBestEffort(o));}disconnectBestEffort(e){try{Promise.resolve(e.disconnect()).catch(()=>{});}catch{}}};var ei=class{constructor(e,t){this.ctx=e;this.deps=t;this.states=new Map;this.failureCooldowns=new Map;this.disposed=false;this.ctx.registerDisposer(()=>this.dispose());}dispose(){this.disposed||(this.disposed=true,this.states.clear(),this.failureCooldowns.clear());}initialize(e,t){if(this.disposed)return {required:false,verified:false,failed:true,failureReason:"connection-trust-manager-disposed",expectedDeviceId:t??null,verifiedDeviceId:null,issuedChallenge:null};let n=this.states.get(e.id);if(n)return t&&!n.expectedDeviceId&&(n.expectedDeviceId=t),n;let i=this.deps.resolvePromotionEligibility({connectionId:e.id,nodeId:e.remoteNodeId,deviceId:t??void 0}),o=this.deps.consumePendingSessionTokenTrustApproval(e.id),s=this.deps.getSessionTokenApprovedScope(e.id),a=o.scope??s,c=o.approved||!!s,l=this.deps.getKnownDeviceIdForNode(e.remoteNodeId),p=!c&&i&&this.deps.requiresManagedTransportTrust(),u={required:p,verified:!p,failed:false,expectedDeviceId:t||l||null,verifiedDeviceId:p?null:t||l||null,issuedChallenge:p?f$2():null};return this.states.set(e.id,u),a&&this.deps.addPeerScope(e.id,a),u}sessionTokenScopeAllowsDeviceBinding(e){let t=typeof e=="string"?e.trim():"";return t==="user-device"||t==="persistent"||t==="trusted-device"||t.startsWith("trusted-device:")}resolveExpectedDeviceIdForSessionTokenScope(e,t,n,i){let o=typeof e=="string"?e.trim():"";if(!o)return null;if(!n)return o;let s=new Set,a=c=>{let l=typeof c=="string"?c.trim():"";l&&s.add(l);};if(a(t),i){a(this.deps.getSessionTokenApprovedScope(i.id));for(let c of this.deps.getPeerScopes(i.id))a(c);for(let c of this.deps.getPeerScopes(i.remoteNodeId))a(c);}return Array.from(s).some(c=>this.sessionTokenScopeAllowsDeviceBinding(c))?o:null}getState(e){if(this.disposed)return null;let t=typeof e.connectionId=="string"?e.connectionId.trim():"";if(t)return this.states.get(t)??null;for(let[n,i]of this.states.entries())if(i.verifiedDeviceId&&(i.verifiedDeviceId===e.deviceId||i.verifiedDeviceId===e.deviceIdHint)||i.expectedDeviceId&&(i.expectedDeviceId===e.deviceId||i.expectedDeviceId===e.deviceIdHint))return this.states.get(n)??null;return null}getProjection(e){if(this.disposed)return null;let t=this.getState(e);if(!t)return null;let n=t.verified&&!t.failed,i=typeof e.connectionId=="string"&&e.connectionId.trim()||Array.from(this.states.entries()).find(([,a])=>a===t)?.[0]||"",o=i?this.deps.getSessionTokenApprovedScope(i):null,s=!o||this.sessionTokenScopeAllowsDeviceBinding(o);return n?{routable:true,protocolState:"routable",health:"healthy",deviceId:s?t.verifiedDeviceId??t.expectedDeviceId??e.deviceId??null:null}:t.required?{routable:false,protocolState:"unverified",health:t.failed?"stale":"unknown",error:t.failureReason??"trusted-device-proof-pending",deviceId:s?t.expectedDeviceId??e.deviceId??e.deviceIdHint??null:null}:null}async buildLocalTransportTrustPayload(e,t){if(this.disposed)return null;let n=await k$1().catch(()=>null),i=await this.deps.getLocalDeviceId().catch(()=>null)||this.ctx.deviceId||this.deps.getFallbackLocalDeviceId()||null;if(!n||!i)return null;let o=this.initialize(e),s={version:1,deviceId:i,identityFingerprint:n.fingerprint,challenge:o.issuedChallenge??void 0};if(t&&(s.signedChallenge=await n.signChallenge(t),s.signedChallengeFor=t,!await g$1(t,s.signedChallenge,h$1(n.publicKey))))throw new Error("local-transport-trust-signature-self-check-failed");return s}async verifyRemoteTransportTrust(e,t){if(this.disposed)return {verified:false,reason:"connection-trust-manager-disposed"};let n=this.initialize(e);if(!n.required)return {verified:true,deviceId:t?.deviceId??n.expectedDeviceId??null};if(!t)return {verified:false,reason:"missing-transport-trust-payload"};let i$1=typeof t.deviceId=="string"?t.deviceId.trim():"";if(!i$1)return {verified:false,reason:"missing-remote-device-id"};if(n.expectedDeviceId&&n.expectedDeviceId!==i$1)return {verified:false,reason:`expected-device-mismatch:${n.expectedDeviceId}:${i$1}`};let o=this.deps.getKnownDevice(i$1,e.remoteNodeId);if(!o){if(await this.deps.refreshKnownDeviceCache(),this.disposed)return {verified:false,reason:"connection-trust-manager-disposed"};o=this.deps.getKnownDevice(i$1,e.remoteNodeId);}if(!o)return {verified:false,reason:`unknown-trusted-device:${i$1}`};let s=i(o.metadata);if(!s)return {verified:false,reason:`missing-trusted-device-metadata:${i$1}`};if(t.identityFingerprint&&s.identityFingerprint!==t.identityFingerprint)return {verified:false,reason:`trusted-device-fingerprint-mismatch:${i$1}`};let a=n.issuedChallenge;return !a||!t.signedChallenge?{verified:false,reason:"missing-signed-transport-challenge"}:typeof t.signedChallengeFor!="string"?{verified:false,reason:"unbound-transport-trust-response"}:t.signedChallengeFor!==a?{verified:false,stale:true,reason:"stale-transport-trust-response"}:await g$1(a,t.signedChallenge,s.identityPublicKey)?{verified:true,deviceId:i$1}:{verified:false,reason:`invalid-transport-proof-bound:${i$1}`}}async enforceFailure(e,t){if(this.disposed)return;let n=this.initialize(e);n.failed=true,n.verified=false,n.failureReason=t,await this.deps.rejectConnectionInRust(e,t),!this.disposed&&(this.deps.applyConnectionTrustProjection(e),console.warn("[Client][TRUST] Disconnecting unverified connection",{connectionId:e.id,remoteNodeId:e.remoteNodeId,reason:t}),this.failureCooldowns.set(e.remoteNodeId,Date.now()),await Promise.allSettled([this.disconnectConnectionBestEffort(e),this.disconnectNodeBestEffort(e.remoteNodeId)]));}markVerified(e,t){if(this.disposed)return;this.failureCooldowns.delete(e.remoteNodeId);let n=this.deps.getSessionTokenApprovedScope(e.id),i=!n||this.sessionTokenScopeAllowsDeviceBinding(n),o=i?t:null,s=this.initialize(e,o);s.verified=true,s.failed=false,s.failureReason=void 0,i?(s.verifiedDeviceId=o||s.verifiedDeviceId||s.expectedDeviceId||null,o&&!s.expectedDeviceId&&(s.expectedDeviceId=o)):(s.verifiedDeviceId=null,s.expectedDeviceId=null),this.deps.applyConnectionTrustProjection(e);let a=s.verifiedDeviceId??s.expectedDeviceId??o??null;a&&(this.deps.bindConnectionDeviceIdInRust(e,a),this.deps.retireSupersededConnections(e,a,"trusted-device-replacement"));}clearForConnection(e){this.disposed||this.states.delete(e);}getStateByConnectionId(e){if(!this.disposed)return this.states.get(e)}getLogicalDeviceIdForConnection(e){let t=this.states.get(e);return t?.verifiedDeviceId??t?.expectedDeviceId??null}clearFailureCooldown(e){this.disposed||this.failureCooldowns.delete(e);}getFailureCooldown(e){if(!this.disposed)return this.failureCooldowns.get(e)}shouldSuppressConnectionRebuild(e,t,n,i=Date.now()){if(this.disposed)return {suppress:false,remainingMs:0};let o=this.failureCooldowns.get(e);return o===void 0||i-o>=t||n?{suppress:false,remainingMs:0}:{suppress:true,remainingMs:t-(i-o)}}logConnectionRebuildSuppressed(e,t){this.disposed||c$1("[Client][TRUST] Skipping connection rebuild for node in trust-failure cooldown",{remoteNodeId:e,cooldownRemainingMs:t});}disconnectConnectionBestEffort(e){try{return Promise.resolve(e.disconnect()).catch(()=>{})}catch{return Promise.resolve()}}disconnectNodeBestEffort(e){try{return Promise.resolve(this.deps.disconnectNode(e)).catch(()=>{})}catch{return Promise.resolve()}}};function Hs(r){return new Zi({getContext:()=>r.getClientContext(),getOptions:()=>r.options,getDeviceId:()=>r.deviceId,getDiscoveryMode:()=>r.discoveryMode,registerDisposer:e=>r.lifecycleScope.register(e),getRegisteredChannel:e=>r.incomingStreamRouter.getRegisteredChannel(e),getConnections:()=>r.registry.values(),requiresManagedTransportTrust:e=>r.runtimeStatus.requiresManagedTransportTrust(e??r.discoveryMode),consumePendingSessionTokenTrustApproval:e=>r.sessionTokens.consumePendingTrustApproval(e),getSessionTokenApprovedScope:e=>r.sessionTokens.getApprovedScope(e),addPeerScope:(e,t)=>r.peerServices.addPeerScope(e,t),getPeerScopes:e=>r.peerServices.getPeerScopes(e),getKnownDeviceIdForNode:e=>r.deviceDirectory.getKnownDeviceIdForNode(e),getKnownDevice:(e,t)=>r.deviceDirectory.getKnownDevice(e,t),refreshKnownDeviceCache:()=>r.deviceDirectory.refreshKnownDeviceCache(),getLocalDeviceId:()=>r.signalingBackendController.getLocalDeviceId(),applyConnectionTrustProjection:e=>r.peerProjection.applyConnectionTrustProjection(e),disconnectRuntimeNode:e=>r.runtimeConnections.disconnectNode(e),rememberKnownDeviceForNode:(e,t)=>r.deviceDirectory.rememberKnownDeviceForNode(e,t),getApplicationCryptoForConnectionOrPeer:(e,t)=>r.applicationCrypto.getForConnectionOrPeer(e,t),indexApplicationCryptoForPeer:(e,t)=>r.applicationCrypto.indexPeer(e,t),hasRustPeerLifecycleProjection:()=>r.hasRustPeerLifecycleProjection(),schedulePeerReconciliation:e=>r.peerProjection.schedule(e),usesTicketOnlySignalingMode:()=>r.runtimeStatus.usesTicketOnlySignalingMode()})}var Zi=class{constructor(e){this.host=e;}get trust(){return this._trust||(this._trust=new ei(this.host.getContext(),{requiresManagedTransportTrust:()=>this.host.requiresManagedTransportTrust(this.host.getDiscoveryMode()),resolvePromotionEligibility:e=>this.channelPolicy.resolvePromotionEligibility(e),consumePendingSessionTokenTrustApproval:e=>this.host.consumePendingSessionTokenTrustApproval(e),getSessionTokenApprovedScope:e=>this.host.getSessionTokenApprovedScope(e),addPeerScope:(e,t)=>this.host.addPeerScope(e,t),getPeerScopes:e=>this.host.getPeerScopes(e),getKnownDeviceIdForNode:e=>this.host.getKnownDeviceIdForNode(e),getKnownDevice:(e,t)=>this.host.getKnownDevice(e,t),refreshKnownDeviceCache:()=>this.host.refreshKnownDeviceCache(),getLocalDeviceId:()=>this.host.getLocalDeviceId(),getFallbackLocalDeviceId:()=>this.host.getDeviceId()??this.host.getOptions()?.localDeviceId??null,applyConnectionTrustProjection:e=>this.host.applyConnectionTrustProjection(e),bindConnectionDeviceIdInRust:(e,t)=>this.deviceBinder.bindConnectionDeviceIdInRust(e,t),rejectConnectionInRust:(e,t)=>this.deviceBinder.rejectConnectionInRust(e,t),retireSupersededConnections:(e,t,n)=>this.deviceBinder.retireSupersededConnections(e,t,n),disconnectNode:e=>this.host.disconnectRuntimeNode(e)})),this._trust}get deviceBinder(){return this._deviceBinder||(this._deviceBinder=new Zn(this.host.getContext(),{rememberKnownDeviceForNode:(e,t)=>this.host.rememberKnownDeviceForNode(e,t),getApplicationCryptoForConnectionOrPeer:(e,t)=>this.host.getApplicationCryptoForConnectionOrPeer(e,t),indexApplicationCryptoForPeer:(e,t)=>{this.host.indexApplicationCryptoForPeer(e,t);},getLogicalDeviceIdForConnection:e=>this.trust.getLogicalDeviceIdForConnection(e),getSessionTokenApprovedScope:e=>this.host.getSessionTokenApprovedScope(e),sessionTokenScopeAllowsDeviceBinding:e=>this.trust.sessionTokenScopeAllowsDeviceBinding(e)})),this._deviceBinder}get channelPolicy(){return this._channelPolicy||(this._channelPolicy=new Xn({registerDisposer:e=>this.host.registerDisposer(e),getRegisteredChannel:e=>this.host.getRegisteredChannel(e),getConnections:()=>this.host.getConnections(),getConnectionTrustState:e=>this.trust.getStateByConnectionId(e),getKnownDeviceIdByNodeId:e=>this.host.getKnownDeviceIdForNode(e),hasRustPeerLifecycleProjection:()=>this.host.hasRustPeerLifecycleProjection(),applyConnectionTrustProjection:e=>this.host.applyConnectionTrustProjection(e),schedulePeerReconciliation:e=>this.host.schedulePeerReconciliation(e),usesTicketOnlySignalingMode:()=>this.host.usesTicketOnlySignalingMode()})),this._channelPolicy}};var ti=class{constructor(e){this.host=e;this.kernelHandles=new $t;this.lifecycleScope=new Vt;}get wasmClient(){return this.kernelHandles.wasmClient}set wasmClient(e){this.kernelHandles.wasmClient=e;}get node(){return this.kernelHandles.node}set node(e){this.kernelHandles.node=e;}get localNodeId(){return this.kernelHandles.localNodeId}set localNodeId(e){this.kernelHandles.localNodeId=e;}get deviceId(){return this.kernelHandles.deviceId}set deviceId(e){this.kernelHandles.deviceId=e;}get runtimeServices(){return this._runtimeServices??(this._runtimeServices=vs(this))}get runtimeBootstrap(){return this.runtimeServices.bootstrap}get runtimeConnections(){return this.runtimeServices.connections}get managedTransportDialer(){return this.runtimeServices.managedDialer}get runtimeIdentity(){return this.runtimeServices.identity}get runtimeReadiness(){return this.runtimeServices.readiness}get runtimeStatus(){return this.runtimeServices.status}get connectionServices(){return this._connectionServices??(this._connectionServices=Nr(this))}get moqServices(){return this._moqServices??(this._moqServices=Fr(this))}get transportServices(){return this._transportServices??(this._transportServices=Os(this))}get trustServices(){return this._trustServices??(this._trustServices=Hs(this))}get registry(){return this.connectionServices.registry}get connectionDialer(){return this.connectionServices.dialer}get connectionMessageHandler(){return this.connectionServices.messageHandler}get incomingConnectionAcceptor(){return this.connectionServices.incomingAcceptor}get appLifecycle(){return this.runtimeServices.appLifecycle}get roomClientHost(){return this._roomClientHost??(this._roomClientHost=es(this))}get accessServices(){return this._accessServices??(this._accessServices=gr(this))}get auth(){return this.accessServices.auth}get signalingBackendController(){return this.accessServices.backend}get peerServices(){return this._peerServices??(this._peerServices=Zr(this))}get peerProjection(){return this.peerServices.projection}get connectionLifecycle(){return this.connectionServices.lifecycle}get streamServices(){return this._streamServices??(this._streamServices=Ns(this))}get incomingStreamRouter(){return this.streamServices.router}get incomingListen(){return this.streamServices.listen}get incomingDiagnostics(){return this.streamServices.diagnostics}get incomingStreamNormalizer(){return this.streamServices.normalizer}get applicationIncomingStreams(){return this.streamServices.applicationIncoming}get applicationStreams(){return this.streamServices.applicationStreams}get deviceDirectory(){return this.accessServices.devices}get connectionTrust(){return this.trustServices.trust}get connectionDeviceBinder(){return this.trustServices.deviceBinder}get connectionChannelPolicy(){return this.trustServices.channelPolicy}get nativeMainServices(){return this._nativeMainServices??(this._nativeMainServices=Wr(this))}get nativeMain(){return this.nativeMainServices.controller}get presence(){return this.accessServices.presence}retirePendingReciprocalAdmissionsIfExists(e){this._nativeMainServices?.controller.retirePendingReciprocalAdmissions(e);}get securityServices(){return this._securityServices??(this._securityServices=Cs(this))}get sessionTokens(){return this.securityServices.sessionTokens}get applicationCrypto(){return this.securityServices.applicationCrypto}get transportUpgrade(){return this.transportServices.upgrade}get transportHandshake(){return this.transportServices.handshake}get transportHealth(){return this.transportServices.health}get transportContexts(){return this.transportServices.contexts}get peerIdentity(){return this.transportServices.peerIdentity}get options(){return this.host.getOptions()}get runtimeSafetyProfile(){return this.host.getRuntimeSafetyProfile()}get discoveryMode(){return this.options.discoveryMode??"space"}get signaling(){return this.host.getSignaling()}get rooms(){return this.host.getRooms()}getRoomCreationMode(){return this.host.getRoomCreationMode()}getAppLimits(){return this.host.getAppLimits()}setSignaling(e){this.host.setSignaling(e);}setRooms(e){this.host.setRooms(e);}setAppLimits(e){this.host.setAppLimits(e);}setRoomCreationMode(e){this.host.setRoomCreationMode(e);}prepareStreamListenForSignOutIfExists(){this._streamServices?.prepareListenForSignOut();}getEffectiveRoomBackendTag(){return this.host.getEffectiveRoomBackendTag()}setEffectiveRoomBackendTag(e){this.host.setEffectiveRoomBackendTag(e);}getExistingPeerReconciliationStats(){return this._peerServices?.getProjectionStats()}hasRustPeerLifecycleProjection(){return Hi(this.signaling,this.wasmClient)}getClientContext(){return this._clientContext||(this._clientContext=cr({getRegistry:()=>this.registry,getWasmClient:()=>this.wasmClient,getNode:()=>this.node,getDiscoveryMode:()=>this.discoveryMode,getLocalNodeId:()=>this.localNodeId,getDeviceId:()=>this.deviceId,registerDisposer:e=>this.lifecycleScope.register(e)})),this._clientContext}getApplicationCrypto(e){return this.securityServices.getApplicationCrypto(e)}resolveApplicationCryptoForPeer(e,t){return this.securityServices.resolveApplicationCryptoForPeer(e,t)}clearApplicationCryptoForConnection(e){this._securityServices?.clearApplicationCryptoForConnection(e);}releaseApplicationKeyAgreementReply(e,t,n){this._securityServices?.releaseApplicationKeyAgreementReply(e,t,n);}waitForApplicationCryptoForPeer(e,t=0){return this.securityServices.waitForApplicationCryptoForPeer(e,t)}stopListenIfExists(){this._streamServices?.stopListenIfExists();}hasApplicationRouteForPeer(e,t){return this.transportServices.hasApplicationRouteForPeer(e,t)}ensureManagedApplicationRoute(e){return this.connectionServices.ensureManagedApplicationRoute(e)}};function eo(){return new Proxy({},{get(){}})}function Dc(){let r=globalThis,e=r.process?.env;return e?.NODE_ENV==="test"||e?.VITEST==="true"||typeof e?.VITEST_WORKER_ID=="string"||typeof r.__vitest_worker__<"u"||typeof r.__vitest_index__<"u"}function L(r){return r.services}var Us={localNodeId:{get(){return L(this).localNodeId},set(r){L(this).localNodeId=r;}},deviceId:{get(){return L(this).deviceId},set(r){L(this).deviceId=r;}},registry:{get(){return L(this).registry}},__registry:{get(){return L(this).registry}},runtimeBootstrap:{get(){return L(this).runtimeBootstrap}},runtimeConnections:{get(){return L(this).runtimeConnections}},runtimeIdentity:{get(){return L(this).runtimeIdentity}},runtimeReadiness:{get(){return L(this).runtimeReadiness}},runtimeStatus:{get(){return L(this).runtimeStatus}},connectionDialer:{get(){return L(this).connectionDialer}},connectionMessageHandler:{get(){return L(this).connectionMessageHandler},set(r){L(this).connectionServices._messageHandler=r;}},connectionLifecycle:{get(){return L(this).connectionLifecycle}},transportUpgrade:{get(){return L(this).transportUpgrade}},transportHandshake:{get(){return L(this).transportHandshake}},transportHealth:{get(){return L(this).transportHealth}},transportContexts:{get(){return L(this).transportContexts}},peerIdentity:{get(){return L(this).peerIdentity}},peerProjection:{get(){return L(this).peerProjection}},peerLifecycle:{get(){return L(this).peerServices.store},set(r){L(this).peerServices.store=r;}},peerLifecycleClient:{get(){return L(this).peerServices.client}},connectionTrust:{get(){return L(this).connectionTrust}},connectionDeviceBinder:{get(){return L(this).connectionDeviceBinder}},connectionChannelPolicy:{get(){return L(this).connectionChannelPolicy}},incomingListen:{get(){return L(this).incomingListen}},incomingStreamRouter:{get(){return L(this).incomingStreamRouter}},incomingDiagnostics:{get(){return L(this).incomingDiagnostics}},incomingStreamNormalizer:{get(){return L(this).incomingStreamNormalizer}},applicationIncomingStreams:{get(){return L(this).applicationIncomingStreams}},applicationCrypto:{get(){return L(this).applicationCrypto}},sessionTokens:{get(){return L(this).sessionTokens}},nativeMain:{get(){return L(this).nativeMain}},auth:{get(){return L(this).auth}},deviceDirectory:{get(){return L(this).deviceDirectory}},presence:{get(){return L(this).presence}},appLifecycle:{get(){return L(this).appLifecycle}},moqController:{get(){return L(this).moqServices.controller}},_runtimeBootstrap:{get(){return L(this)._runtimeServices?._bootstrap}},_auth:{get(){return L(this)._accessServices?._auth}},_presence:{get(){return L(this)._accessServices?._presence}},_peerProjection:{get(){return L(this)._peerServices?._projection},set(r){L(this).peerServices._projection=r;}},_peerLifecycleClient:{get(){return L(this)._peerServices?._client}},_incomingListen:{get(){return L(this)._streamServices?._listen}},_connectionDialer:{get(){return L(this)._connectionServices?._dialer}},_connectionMessageHandler:{get(){return L(this)._connectionServices?._messageHandler},set(r){L(this).connectionServices._messageHandler=r;}},_transportUpgrade:{get(){return L(this)._transportServices?._upgrade}},_applicationCrypto:{get(){return L(this)._securityServices?._applicationCrypto},set(r){L(this).securityServices._applicationCrypto=r;}},_transportContexts:{set(r){L(this).transportServices._contexts=r;}}};function js(r){if(Dc()){for(let e of Object.values(Us))e.configurable=true;Object.defineProperties(r.prototype,Us);}}var mt=class{constructor(e){this.appLimits={...g};this.roomCreationMode="client-open";let t=q(e);this.options=t.options,this.runtimeSafetyProfile=nt(this.options),this.effectiveRoomBackendTag=t.appTag,this.roomCreationMode=t.roomCreationMode,this.signaling=new Te(r(t),eo()),this._services=this.createServiceGraph(),this.rooms=new Le(this.services.roomClientHost,this.signaling),this.services.signalingBackendController;}get services(){return this._services??(this._services=this.createServiceGraph())}createServiceGraph(){let e=()=>({...this.options??{},apiKey:this.options?.apiKey??"test"});return new ti({getOptions:()=>this.options??e(),getRuntimeSafetyProfile:()=>this.runtimeSafetyProfile??nt(e()),getSignaling:()=>this.signaling??(this.signaling=new Te(r(e()),eo())),setSignaling:t=>{this.signaling=t;},getRooms:()=>this.rooms,setRooms:t=>{this.rooms=t;},getAppLimits:()=>this.appLimits??(this.appLimits={...g}),setAppLimits:t=>{this.appLimits=t;},getRoomCreationMode:()=>this.roomCreationMode??"client-open",setRoomCreationMode:t=>{this.roomCreationMode=t;},getEffectiveRoomBackendTag:()=>this.effectiveRoomBackendTag??"openrtc",setEffectiveRoomBackendTag:t=>{this.effectiveRoomBackendTag=t;}})}get wasmClient(){return this.services.wasmClient}set wasmClient(e){this.services.wasmClient=e;}get node(){return this.services.node}set node(e){this.services.node=e;}attachIncomingStreamSource(e,t){this.services.wasmClient=e,this.services.localNodeId=t;}getApplicationCrypto(e){return this.services.getApplicationCrypto(e)}resolveApplicationCryptoForPeer(e,t){return this.services.resolveApplicationCryptoForPeer(e,t)}releaseApplicationKeyAgreementReply(e,t,n){this.services.releaseApplicationKeyAgreementReply(e,t,n);}waitForApplicationCryptoForPeer(e,t=1500){return this.services.waitForApplicationCryptoForPeer(e,t)}destroy(){this.services.lifecycleScope.destroy();}dispose(){this.destroy();}get apiKey(){return this.options.apiKey}get discoveryMode(){return this.options.discoveryMode??"space"}usesDirectRoomBackend(){return this.services.runtimeStatus.usesDirectRoomBackend()}getRoomBackendTag(){return this.services.runtimeStatus.getRoomBackendTag()}async refreshHostedAppSettings(e=false){return this.services.signalingBackendController.refreshHostedAppSettings(e)}setSignalingBackend(e){this.services.signalingBackendController.setSignalingBackend(e);}get currentUser(){return this.services.signalingBackendController.getCurrentUser()??null}onAuthChange(e){return this.services.auth.onAuthChange(e)}async signInAnonymously(){return this.services.auth.signInAnonymously()}async signInWithPluto(){return this.services.auth.signInWithPluto()}async signOut(){return this.services.auth.signOut()}getSignalingTelemetry(){return this.services.runtimeStatus.getSignalingTelemetry()}getPeerReconciliationStats(){return this.services.runtimeStatus.getPeerReconciliationStats()}getProtocolCapabilities(){return this.services.runtimeStatus.getProtocolCapabilities()}async getRuntimeStatus(){return this.services.runtimeStatus.getRuntimeStatus()}async searchDevices(){return this.services.deviceDirectory.searchDevices()}async updateDevice(e,t){return this.services.deviceDirectory.updateDevice(e,t)}async deleteDevice(e){return this.services.deviceDirectory.deleteDevice(e)}async cleanupStaleDevices(){return this.services.deviceDirectory.cleanupStaleDevices()}onDevicesChange(e){return this.services.deviceDirectory.onDevicesChange(e)}async subscribeSessions(e,t){return this.services.deviceDirectory.subscribeSessions(e,t)}async startScanningLoop(e){return this.services.deviceDirectory.startScanningLoop(e)}async bootstrapRuntime(e){return this.services.runtimeBootstrap.bootstrapRuntime(e)}updateTransportConfig(e){s(this.options,e);}async init(){return this.services.runtimeBootstrap.init()}async ensureAuthenticated(e){return this.services.auth.ensureAuthenticated(e)}async refreshRuntimeAuthToken(e="runtime-start"){return this.services.auth.refreshRuntimeAuthToken(e)}get moqState(){return this.services.moqServices.state}get moq(){return this.services.moqServices.bundle}onMoQReady(e){return this.services.moqServices.onReady(e)}onMoQFailed(e){return this.services.moqServices.onFailed(e)}refreshTransportCapabilities(e="client-request"){return this.services.transportHandshake.broadcastTransportCapabilityUpdate(e)}onMoQObject(e){return this.services.moqServices.onObject(e)}subscribeMoQPeer(e){this.services.moqServices.enableForConnection(e);}subscribeMoQPeerNode(e,t){this.services.moqServices.subscribePeerNode(e,t);}async connect(e,t=2e4,n,i,o){return this.services.connectionDialer.connect(e,t,n,i,o)}async connectRaw(e,t=2e4){return this.services.runtimeConnections.connectRaw(e,t)}async startAutoConnect(e){return this.services.runtimeConnections.startAutoConnect(e)}async openBi(e){return this.services.applicationStreams.openBi(e)}async openUni(e){return this.services.applicationStreams.openUni(e)}getConnections(){return this.services.registry.all()}getApplicationReadyConnections(e={}){return this.services.registry.applicationReady(e)}getConnectionForPeer(e,t){return this.services.registry.getForPeer(e,t)}hasApplicationRouteForPeer(e,t){return this.services.hasApplicationRouteForPeer(e,t)}ensureManagedApplicationRoute(e){return this.services.ensureManagedApplicationRoute(e)}watchPeerStates(e){return this.services.peerServices.watchPeerStates(e)}getPeerState(e){return this.services.peerServices.getPeerState(e)}listConnectedPeers(){return this.services.peerServices.listConnectedPeers()}isPeerPromotionEligible(e){return this.services.peerServices.isPeerPromotionEligible(e)}addPeerScope(e,t="persistent"){return this.services.peerServices.addPeerScope(e,t)}releasePeerScope(e,t){return this.services.peerServices.releasePeerScope(e,t)}getPeerScopes(e){return this.services.peerServices.getPeerScopes(e)}isSamePeer(e,t){return this.services.peerServices.isSamePeer(e,t)}async refreshPeerSnapshot(){return this.services.peerProjection.schedule("refresh")}async connectPeer(e){return this.services.connectionDialer.connectPeer(e)}clearManualDisconnectProjection(e){this.services.peerServices.clearManualDisconnectProjection(e);}async disconnectPeer(e,t="persistent"){await this.services.peerServices.disconnectPeer(e,t);}async forceDisconnectPeer(e){await this.services.peerServices.forceDisconnectPeer(e);}async getPeerHealth(e){return this.services.peerServices.getPeerHealth(e)}async getTicket(){return this.services.runtimeIdentity.getTicket()}async getNodeId(){return this.services.runtimeIdentity.getNodeId()}async getNodeIdFromTicket(e){return this.services.runtimeIdentity.getNodeIdFromTicket(e)}async getEndpointTicketWithToken(e,t=0){return this.services.sessionTokens.getEndpointTicketWithToken(e,t)}buildCompoundTicketWithToken(e,t,n=0){return this.services.sessionTokens.buildCompoundTicketWithToken(e,t,n)}setManagedPresenceTicket(e){this.services.presence.setManagedPresenceTicket(e);}clearManagedPresenceTicket(){this.services.presence.clearManagedPresenceTicket();}registerSessionToken(e,t,n){this.services.sessionTokens.registerSessionToken(e,t,n);}revokeSessionToken(e){this.services.sessionTokens.revokeSessionToken(e);}async revokeTokensByScope(e){return this.services.sessionTokens.revokeTokensByScope(e)}async clearSessionTokens(){return this.services.sessionTokens.clearSessionTokens()}async startPresenceLoop(e){return this.services.presence.startPresenceLoop(e)}async setOffline(){return this.services.presence.setOffline()}async isConnected(e){return this.services.runtimeConnections.isConnected(e)}async disconnectNode(e){return this.services.runtimeConnections.disconnectNode(e)}async getLocalDeviceId(){return this.services.signalingBackendController.getLocalDeviceId()}async acceptNativeMessage(e,t,n){return this.services.nativeMain.acceptNativeMessage(e,t,n)}async startListening(e){return this.services.incomingListen.start(e)}stopListening(){this.services.stopListenIfExists();}forceReconnectSnapshot(){this.services.signalingBackendController.forceReconnectSnapshot();}wrapChannelWritable(e,t,n){return Ko(e,t,n)}async updatePresence(e=true,t=3e5,n,i){return this.services.presence.updatePresence(e,t,n,i)}onConnection(e){return this.services.connectionLifecycle.onConnection(e)}onDisconnection(e){return this.services.connectionLifecycle.onDisconnection(e)}onMessage(e){return this.services.incomingStreamRouter.onMessage(e)}onIncomingStream(e){return this.services.incomingStreamRouter.onIncomingStream(e)}registerChannel(e){this.services.incomingStreamRouter.registerChannel(e);}unregisterChannel(e){this.services.incomingStreamRouter.unregisterChannel(e);}listChannels(){return this.services.incomingStreamRouter.listChannels()}onIncomingChannelStream(e,t){return this.services.incomingStreamRouter.onIncomingChannelStream(e,t)}onRoomJoinRequest(e){return this.services.incomingStreamRouter.onRoomJoinRequest(e)}isMoQDataReady(e){return this.services.moqServices.isDataReady(e)}async sendMoQData(e,t,n={}){return this.services.moqServices.sendData(e,t,n)}};js(mt);var ft=class ft{constructor(e){this.locallyDeletedDeviceIds=new Set;this.deviceStatusRefreshWakeups=new Set;this.client=e.client,this.backend=e.backend,this.peerApi=e.peerApi,this.connectToDevice=e.connectToDevice,this.startManagedReconciliation=e.startManagedReconciliation,this.deviceStatusRefreshDebounceMs=e.deviceStatusRefreshDebounceMs;}deviceStatusSnapshotKey(e){return JSON.stringify([...e].map(t=>({deviceId:t.deviceId,deviceName:t.deviceName??null,platformType:t.platformType??null,online:!!t.online,presenceStatus:t.presenceStatus??null,presenceUpdatedAt:t.presenceUpdatedAt??null,presenceExpiresAt:t.presenceExpiresAt??null,connectable:t.connectable??null,connectionStatus:t.connectionStatus??null,settledReady:!!t.settledReady,readinessState:t.readinessState??null,readinessReason:t.readinessReason??null,peerHealth:t.peerHealth??null,peerId:t.peerId??null,promotionEligible:t.promotionEligible??true,connectionId:t.connectionId??null,deviceIdHint:t.deviceIdHint??null,nodeId:t.nodeId??null,ticket:t.ticket??null,activeTransportStableId:t.activeTransportStableId??null,transportGeneration:t.transportGeneration??null,routeGeneration:t.routeGeneration??null,activeTransport:t.activeTransport??null,parallelTransport:t.parallelTransport??null,latencyMs:t.latencyMs??null,latencyByTransport:t.latencyByTransport??null,scopes:[...t.scopes??[]].sort()})).sort((t,n)=>t.deviceId.localeCompare(n.deviceId)))}normalizeLookupKey(e){return typeof e=="string"?e.trim().toLowerCase():""}isLocallyDeletedDevice(e){let t=this.normalizeLookupKey(e);return !!t&&this.locallyDeletedDeviceIds.has(t)}filterLocallyDeletedDevices(e){return (e??[]).filter(t=>!this.isLocallyDeletedDevice(t.deviceId))}isDurableUserDevicePeer(e){return (e.scopes??[]).some(t=>t==="user-device")}matchItem(e,t){let n=this.normalizeLookupKey(t.deviceId),i=this.normalizeLookupKey(t.nodeId),o=this.normalizeLookupKey(t.connectionId),s=new Set([n,this.normalizeLookupKey(t.deviceIdHint),i,o,this.normalizeLookupKey(t.peerId)].filter(Boolean)),a=null,c=null;for(let l of e){let p=this.normalizeLookupKey(l.deviceId),u=this.normalizeLookupKey(l.deviceIdHint),g=this.normalizeLookupKey(l.nodeId),y=this.normalizeLookupKey(l.peerId),m=this.normalizeLookupKey(l.activeConnectionId??l.connectionId);if(![p,u,g,y,m].filter(Boolean).some(U=>s.has(U))||i&&g&&g!==i)continue;let S=i&&g===i?5:n&&p===n?4:n&&y===n?3:n&&u===n?2:o&&m===o?1:0,I=String(l.status??"").trim().toLowerCase(),k=I==="closed"||I==="disconnected"||I==="failed",D=(l.settledReady===true||l.routable===true||String(l.readinessState??l.protocolState??"").trim().toLowerCase()==="routable")&&!k?4:I==="connected"&&l.health==="healthy"?3:!k&&I==="connected"?2:k?0:1,_=l.replacementPending===true?0:1,E=l.transportGeneration??l.generation??0,A=l.routeGeneration??0,j=l.lastSeenAtMs??l.lastAuthoritativeEventAt??0,q=[S,D,_,E,A,j],F=c,W=F===null;if(F){for(let U=0;U<q.length;U+=1)if(q[U]!==F[U]){W=q[U]>F[U];break}}W&&(a=l,c=q);}return a}peerIsCompatibleWithSession(e,t){let n=this.normalizeLookupKey(t.nodeId),i=this.normalizeLookupKey(e.nodeId);if(n&&i&&n!==i)return false;let o=this.normalizeLookupKey(t.activeConnectionId),s=[e.connectionId,...e.connectionIds??[]].map(a=>this.normalizeLookupKey(a)).filter(Boolean);return !(o&&s.length>0&&!s.includes(o))}shouldIgnoreTerminalPeerForRoutableSession(e,t){if(!e||!t)return false;let n=String(e.status??"").trim().toLowerCase(),i=n==="closed"||n==="disconnected"||n==="failed",o=t.settledReady===true||String(t.readinessState??"").trim().toLowerCase()==="routable",s=this.isManualDisconnectPeer(e);return i&&!s&&o&&!!t.activeConnectionId}applyCompatibleOptionalTransportFacet(e$1,t,n){if(!t||!this.isRoutableDeviceStatus(e$1)||n&&!this.peerIsCompatibleWithSession(t,n))return e$1;let i=String(t.status??"").trim().toLowerCase();if(!(t.routable===true||t.protocolState==="routable")||i==="closed"||i==="disconnected"||i==="failed"||t.transportGeneration!==void 0&&e$1.transportGeneration!==void 0&&t.transportGeneration!==e$1.transportGeneration||t.routeGeneration!==void 0&&e$1.routeGeneration!==void 0&&t.routeGeneration!==e$1.routeGeneration)return e$1;let s=b$1(t.activeTransport),a=b$1(t.parallelTransport),c=[s,a].find(e);if(!c)return e$1;let l=[e$1.activeTransport,e$1.parallelTransport,s,a].map(b$1).find(c$2),p=s===c;return {...e$1,activeTransport:p?c:l??c,parallelTransport:p?l??null:c}}latencyForTransport(e,t){let n=b$1(e);return n==="webrtc-lan"?t.webrtcLan??null:n==="webrtc-turn"?t.webrtcTurn??null:n==="webrtc"?t.webrtc??null:n==="iroh-lan"?t.irohLan??null:n==="iroh-relay"?t.irohRelay??null:n==="iroh"||n==="iroh-quic"?t.iroh??null:n==="ble"?t.ble??null:n==="moq"?t.moq??null:null}applyLocalTransportLatency(e){if(!this.isRoutableDeviceStatus(e))return {...e,latencyMs:null,latencyByTransport:void 0};let t=this.client.getConnectionForPeer,i=(typeof t=="function"?t.call(this.client,e.connectionId,e.nodeId??e.peerId):null)?.getTransportLatencySnapshot()??{},o={...e.latencyByTransport??{},...Object.fromEntries(Object.entries(i).filter(([,l])=>l!=null))},s=Object.values(o).some(l=>l!=null)?o:void 0,c=(s?this.latencyForTransport(e.activeTransport,s)??this.latencyForTransport(e.parallelTransport,s):null)??e.latencyMs??null;return {...e,latencyMs:c,latencyByTransport:s}}isManualDisconnectPeer(e){let t=String(e?.error??"").trim().toLowerCase();return t.includes("manual disconnect")||e?.manualDisconnect===true&&t.length>0}buildFinalDeviceStatusSnapshots(e,t,n,i={}){let o=this.filterLocallyDeletedDevices(e).map(c=>{let l=this.matchItem(t,c),p=this.matchItem(n,c),u=(c.connectionStatus==="closed"||c.connectionStatus==="disconnected"||c.connectionStatus==="failed")&&String(c.readinessReason??"").trim().toLowerCase().includes("manual disconnect"),g=q$1({device:c,session:u?null:l,peer:null,isPromotionEligible:y=>this.client.isPeerPromotionEligible(y)});return u?g:this.applyCompatibleOptionalTransportFacet(g,p,l)}),s=new Set(o.map(c=>this.normalizeLookupKey(c.deviceId))),a=new Set(o.flatMap(c=>[c.deviceId,c.deviceIdHint,c.nodeId,c.peerId,c.connectionId].map(l=>this.normalizeLookupKey(l)).filter(Boolean)));for(let c of n){if(!this.isDurableUserDevicePeer(c))continue;let l=this.statusDeviceFromPeer(c),p=this.normalizeLookupKey(l?.deviceId),u=[c.deviceId,c.deviceIdHint,c.nodeId,c.peerId,c.connectionId].map(g=>this.normalizeLookupKey(g)).filter(Boolean);if(!(!l||!p||s.has(p)||u.some(g=>a.has(g))||this.isLocallyDeletedDevice(p))){s.add(p);for(let g of u)a.add(g);o.push(q$1({device:l,session:this.matchItem(t,l),peer:c,isPromotionEligible:g=>this.client.isPeerPromotionEligible(g)}));}}return o.map(c=>this.applyLocalTransportLatency(c))}applyTerminalPeerTransportState(e,t){if(this.isRoutableDeviceStatus(e))return e;let n=String(t?.status??"").trim().toLowerCase();return n!=="closed"&&n!=="disconnected"&&n!=="failed"?e:{...e,activeTransportStableId:null,activeTransport:void 0,parallelTransport:void 0}}statusDeviceFromPeer(e){let t=e.deviceId?.trim()||e.deviceIdHint?.trim(),n=String(e.status??"").trim().toLowerCase();return !t||n==="closed"||n==="disconnected"||n==="failed"?null:{deviceId:t,deviceName:e.deviceName?.trim()||"Unknown Device",online:e.online??true,ticket:e.ticket??"",nodeId:e.nodeId,platformType:e.platformType,presenceStatus:e.online===false?"offline":"online",connectable:!!e.ticket,connectionStatus:e.status,settledReady:e.routable===true||e.protocolState==="routable",readinessState:e.protocolState,peerHealth:e.health,peerId:e.peerId,scopes:[...e.scopes??[]],connectionId:e.connectionId,deviceIdHint:e.deviceIdHint,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}}runtimeDeviceToStatusSnapshot(e){return q$1({device:e})}isRoutableDeviceStatus(e){return e.settledReady===true||String(e.readinessState??"").trim().toLowerCase()==="routable"}mergeWatchedDevicesIntoStatusSnapshots(e,t){if(!e)return t;let n=new Map(t.map(c=>[c.deviceId,c])),i=this.filterLocallyDeletedDevices(e),o=new Set(i.map(c=>this.normalizeLookupKey(c.deviceId))),s=this.filterLocallyDeletedDevices(t.filter(c=>!o.has(this.normalizeLookupKey(c.deviceId))));return [...i.map(c=>{let l=this.runtimeDeviceToStatusSnapshot(c),p=n.get(c.deviceId);if(!p)return l;let{connectionStatus:u,settledReady:g,readinessState:y,readinessReason:m,peerHealth:v,peerId:S,promotionEligible:I,connectionId:k,activeTransportStableId:T,transportGeneration:D,routeGeneration:_,activeTransport:E,parallelTransport:A,presenceStatus:j,presenceUpdatedAt:q,presenceExpiresAt:F,connectable:W,...U}=p,{connectionStatus:Z,settledReady:ne,readinessState:Me,readinessReason:qe,peerHealth:ri,peerId:yt,promotionEligible:si,connectionId:Ke,activeTransportStableId:ai,transportGeneration:ze,routeGeneration:ci,activeTransport:li,parallelTransport:io,presenceStatus:N,presenceUpdatedAt:O,presenceExpiresAt:z,connectable:G,latencyMs:re,latencyByTransport:oo,deviceIdHint:Se,scopes:ro,...di}=l,so=p.presenceUpdatedAt,ao=O,Qe=N!==void 0&&ao!==void 0&&(so===void 0||ao>=so);return q$1({device:{...U,...di,connectionStatus:p.connectionStatus,settledReady:p.settledReady,readinessState:p.readinessState,readinessReason:p.readinessReason,peerHealth:p.peerHealth,peerId:p.peerId,promotionEligible:p.promotionEligible,connectionId:p.connectionId,activeTransportStableId:p.activeTransportStableId,transportGeneration:p.transportGeneration,routeGeneration:p.routeGeneration,activeTransport:p.activeTransport,parallelTransport:p.parallelTransport,latencyMs:p.latencyMs,latencyByTransport:p.latencyByTransport,online:Qe?l.online:p.online,presenceStatus:Qe?N:p.presenceStatus,presenceUpdatedAt:Qe?O:p.presenceUpdatedAt,presenceExpiresAt:Qe?z:p.presenceExpiresAt,connectable:Qe?G:p.connectable,platformType:p.platformType??l.platformType,deviceIdHint:Se??p.deviceIdHint,scopes:p.scopes}})}),...s]}async listDevices(){return this.filterLocallyDeletedDevices(await this.client.searchDevices())}async listDevicesWithStatus(){let e=this.backend;if(e&&typeof e.listDevicesWithStatus=="function"){let t=await e.listDevicesWithStatus(),[n,i]=await Promise.allSettled([typeof e.listPeerSessions=="function"?e.listPeerSessions():Promise.resolve([]),this.peerApi.refreshPeerSnapshot().catch(l=>{let p=this.peerApi.listConnectedPeers();return console.warn(`[RuntimeClient] refreshPeerSnapshot failed during listDevicesWithStatus(); using ${p.length} cached connected peers`,l),p})]),o=n.status==="fulfilled"?n.value:[],s=i.status==="fulfilled"?i.value:[],a=this.filterLocallyDeletedDevices(this.buildFinalDeviceStatusSnapshots(t,o,s,{preserveRoutableInputLifecycle:true}));return (a.some(l=>f$1(l.activeTransport))||o.some(l=>f$1(l.activeTransport))||s.some(l=>f$1(l.activeTransport)))&&b$2("[RuntimeClient] device status snapshot with transport labels",{devices:a.map(l=>({deviceId:l.deviceId,connectionStatus:l.connectionStatus,settledReady:!!l.settledReady,activeTransport:l.activeTransport??null,parallelTransport:l.parallelTransport??null,connectionId:l.connectionId??null})),peerSessions:o.map(l=>({peerId:l.peerId,deviceId:l.deviceId??null,activeConnectionId:l.activeConnectionId??null,status:l.status,activeTransport:l.activeTransport??null,parallelTransport:l.parallelTransport??null})),peers:s.map(l=>({peerId:l.peerId,deviceId:l.deviceId??null,connectionId:l.connectionId??null,status:l.status,activeTransport:l.activeTransport??null,parallelTransport:l.parallelTransport??null}))}),a}throw new Error("[pluto-rtc] listDevicesWithStatus() requires a Rust-backed runtime adapter that implements listDevicesWithStatus().")}async updateDevice(e,t){await this.client.updateDevice(e,t);}async deleteDevice(e){let t=this.normalizeLookupKey(e);await this.client.deleteDevice(e),t&&this.locallyDeletedDeviceIds.add(t);}watchDevices(e){return this.client.onDevicesChange(t=>e(this.filterLocallyDeletedDevices(t)))}watchDevicesWithStatus(e){let t=this.backend;if(!t||typeof t.listDevicesWithStatus!="function")throw new Error("[pluto-rtc] watchDevicesWithStatus() requires a Rust-backed runtime adapter that implements listDevicesWithStatus().");let n=true,i=null,o=null,s=null,a=null,c=false,l=false,p=T=>{let D=this.filterLocallyDeletedDevices(T);g(D);let _=this.deviceStatusSnapshotKey(D);_!==i&&(i=_,e(D));},u=()=>{a&&(clearTimeout(a),a=null);},g=T=>{if(u(),!n)return;let D=Date.now(),_=T.filter(A=>A.presenceStatus==="online").map(A=>typeof A.presenceUpdatedAt=="number"?A.presenceUpdatedAt+3e5:null).filter(A=>typeof A=="number"&&Number.isFinite(A)).sort((A,j)=>A-j)[0];if(_===void 0)return;let E=Math.max(25,_-D+5);a=setTimeout(()=>{a=null,v();},E);},y=()=>{c=false,!(!n||!l)&&(l=false,v());},m=()=>{if(n){if(c){l=true;return}c=true,this.listDevicesWithStatus().then(T=>{n&&p(this.mergeWatchedDevicesIntoStatusSnapshots(o,T));}).catch(T=>{console.warn("[RuntimeDeviceManager] device-status refresh failed",T);}).finally(()=>y());}},v=()=>{!n||s||(s=setTimeout(()=>{s=null,m();},this.deviceStatusRefreshDebounceMs));};this.deviceStatusRefreshWakeups.add(v);let S=this.client.onDevicesChange(T=>{Array.isArray(T)&&(o=this.filterLocallyDeletedDevices(T)),v();}),I=this.peerApi.watchPeerStates(()=>{v();}),k=this.startManagedReconciliation(()=>v());return m(),()=>{n=false,s&&clearTimeout(s),u(),this.deviceStatusRefreshWakeups.delete(v),k(),S(),I();}}notifyLifecycleMutation(){for(let e of this.deviceStatusRefreshWakeups)e();}async connectDeviceWithRetry(e,t,n){return this.connectDevice(e,{localDeviceId:n.localDeviceId,targetUserId:n.targetUserId,onConnected:t.onConnected})}async connectDevice(e,t){let n=e,i=typeof e.ticket=="string"?e.ticket.trim():"";if(!i){let u=(await this.listDevicesWithStatus().catch(()=>this.listDevices().catch(()=>[]))).find(g=>g.deviceId===e.deviceId);u&&(n={...e,...u},i=typeof u.ticket=="string"?u.ticket.trim():"");}if(!i)return {success:false,error:`Cannot connect to ${e.deviceId}: missing endpoint ticket`,attempts:1};let o=this.peerApi.getPeerState(e.deviceId),s=o?.status,a=this.client.hasApplicationRouteForPeer?.(o?.connectionId??void 0)??false;if(s==="connected"&&a)return {success:true,skipped:"already-connecting",attempts:0};this.client.clearManualDisconnectProjection?.(n.deviceId);let c=Date.now(),l=()=>Math.max(1,ft.EXPLICIT_CONNECT_SETTLE_TIMEOUT_MS-(Date.now()-c));try{let p=await this.connectToDevice({deviceId:n.deviceId,endpointTicket:i,timeoutMs:ft.EXPLICIT_CONNECT_SETTLE_TIMEOUT_MS}),u=this.backend;if(u&&typeof u.waitForSettledPeer=="function"){let g=l();if(!(await u.waitForSettledPeer(p.deviceId??n.deviceId??p.remoteNodeId??p.connectionId,g))?.settledReady)throw new Error(`Connection to ${n.deviceId} did not become application-routable`)}return await this.peerApi.refreshPeerSnapshot().catch(()=>{}),this.notifyLifecycleMutation(),await t.onConnected?.(n),{success:!0,attempts:1}}catch(p){return {success:false,error:p instanceof Error?p.message:`Cannot connect to ${e.deviceId}`,attempts:1}}}};ft.EXPLICIT_CONNECT_SETTLE_TIMEOUT_MS=3e4;var ni=ft;var ii=class{constructor(e,t){this.client=e;this.backend=t;}normalizeUiConnectionStatus(e){switch((e||"disconnected").trim().toLowerCase()){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "disconnected"}}buildLookup(e,t){let n=new Map,i=(o,s)=>{let a=typeof o=="string"?o.trim():"";!a||n.has(a)||n.set(a,s);};for(let o of e)for(let s of t(o))i(s,o);return n}uniqueLookupIds(...e){let t=new Set,n=[];for(let i of e){let o=typeof i=="string"?i.trim():"";!o||t.has(o)||(t.add(o),n.push(o));}return n}matchSessionByLookupId(e,t){if(!e.length||!t.length)return null;let n=this.buildLookup(e,i=>[i.peerId,i.deviceId,i.deviceIdHint,i.nodeId,i.activeConnectionId]);for(let i of t){let o=n.get(i);if(o)return o}return null}matchLocalPeerState(e,t){let n=this.uniqueLookupIds(...e,t.peerId,t.deviceId,t.deviceIdHint,t.nodeId,t.activeConnectionId);for(let o of n){let s=this.client.getPeerState(o);if(s)return s}let i=this.buildLookup(this.client.listConnectedPeers(),o=>[o.peerId,o.deviceId,o.deviceIdHint,o.nodeId,o.connectionId,...o.connectionIds??[]]);for(let o of n){let s=i.get(o);if(s)return s}return null}async resolvePeerLookupIds(e,t){let n=typeof t.resolvePeerIdentity=="function"?await t.resolvePeerIdentity(e).catch(()=>null):null,i=this.uniqueLookupIds(e,n?.peerId,n?.deviceId,n?.deviceIdHint,n?.nodeId);if(typeof t.listPeerSessions!="function")return i;let o=this.matchSessionByLookupId(await t.listPeerSessions().catch(()=>[]),i);return this.uniqueLookupIds(...i,o?.peerId,o?.deviceId,o?.deviceIdHint,o?.nodeId,o?.activeConnectionId)}async resolvePeerConnectionRecords(e){let t=this.backend;if(!t||typeof t.resolvePeerConnectionRecords!="function")throw new Error("[pluto-rtc] resolvePeerConnectionRecords() requires a Rust-backed runtime adapter that implements resolvePeerConnectionRecords().");return t.resolvePeerConnectionRecords(e)}async getPeerSession(e){let t=this.backend;if(!t||typeof t.getPeerSession!="function")throw new Error("[pluto-rtc] getPeerSession() requires a Rust-backed runtime adapter that implements getPeerSession().");let n=await this.resolvePeerLookupIds(e,t);for(let i of n){let o=await t.getPeerSession(i);if(o)return o}return typeof t.listPeerSessions=="function"?this.matchSessionByLookupId(await t.listPeerSessions(),n):null}async listPeerSessions(){let e=this.backend;if(!e||typeof e.listPeerSessions!="function")throw new Error("[pluto-rtc] listPeerSessions() requires a Rust-backed runtime adapter that implements listPeerSessions().");return e.listPeerSessions()}async waitForConnectedPeer(e,t){let n=this.backend;if(!n||typeof n.waitForSettledPeer!="function")throw new Error("[pluto-rtc] waitForConnectedPeer() requires a Rust-backed runtime adapter that implements waitForSettledPeer().");let i=typeof n.resolvePeerIdentity=="function"?await n.resolvePeerIdentity(e).catch(()=>null):null,o=this.uniqueLookupIds(i?.peerId,i?.deviceId,i?.deviceIdHint,i?.nodeId,e),s=o[0]??e,a=Date.now(),c=await n.waitForSettledPeer(s,t);if(!c?.settledReady)return c;let l=typeof t=="number"?Math.max(0,t):5e3;for(;;){let p=this.matchLocalPeerState(o,c);if(!p||p.routable===true||p.protocolState==="routable")return c;if(Date.now()-a>=l)return {...c,settledReady:false,readinessState:p.protocolState??"transport-only",readinessReason:p.error??"application-route-not-ready"};await new Promise(u=>setTimeout(u,50));}}async getPeerReadiness(e,t){let n=this.client.getPeerState(e)??null,i=typeof t=="number"?await this.waitForConnectedPeer(e,t).catch(()=>null):await this.getPeerSession(e).catch(()=>null),o=this.normalizeUiConnectionStatus(i?.status??n?.status??"disconnected"),s=n?.routable===false&&n?.protocolState==="unverified";return {requestedId:e,connected:o==="connected",settledReady:s?false:!!i?.settledReady,status:o,health:i?.health??n?.health??"unknown",deviceId:i?.deviceId??n?.deviceId??null,deviceIdHint:i?.deviceIdHint??n?.deviceIdHint??null,activeConnectionId:i?.activeConnectionId??n?.connectionId??null,readinessState:s?n?.protocolState:i?.readinessState??n?.protocolState,readinessReason:s?n?.error:i?.readinessReason??n?.error,scopes:[...i?.scopes??n?.scopes??[]]}}async resolvePeerIdentity(e){let t=this.backend;if(!t||typeof t.resolvePeerIdentity!="function")throw new Error("[pluto-rtc] resolvePeerIdentity() requires a Rust-backed runtime adapter that implements resolvePeerIdentity().");return t.resolvePeerIdentity(e)}async resolveIncomingStreamPeer(e){return this.resolvePeerIdentity(e)}addPeerScope(e,t){return this.client.addPeerScope(e,t)}releasePeerScope(e,t){return this.client.releasePeerScope(e,t)}getPeerScopes(e){return this.client.getPeerScopes(e)}isSamePeer(e,t){return this.client.isSamePeer(e,t)}};var Ks="drive-view.",to=[68,86,67,72],Mc=new TextDecoder;function no(r){if(r.byteLength>=to.length){let e=true;for(let t=0;t<to.length;t+=1)if(r[t]!==to[t]){e=false;break}if(e)return true}try{let e=JSON.parse(Mc.decode(r));return typeof e.t=="string"&&e.t.startsWith(Ks)}catch{return false}}function Gs(r){return !!r&&!r.isClosed&&typeof r.send=="function"&&(typeof r.isReadyForApplicationPayload!="function"||r.isReadyForApplicationPayload())}var qs=new WeakMap;function Ec(r){if(r instanceof Uint8Array)return no(r)?r:null;if(r instanceof ArrayBuffer){let e=new Uint8Array(r);return no(e)?e:null}return r&&typeof r=="object"&&typeof r.t=="string"&&r.t.startsWith(Ks)?new TextEncoder().encode(JSON.stringify(r)):null}function xc(r,e){let t=qs.get(r);if(!t){t={receivers:new Set([e])},qs.set(r,t);let n=i=>{let o=false;for(let s of [...t.receivers])try{o=s(i)||o;}catch(a){c$1("[RuntimeClient][connectScopedChannel] route-scoped receiver failed",{connectionId:r.id,error:String(a)});}return o};return typeof r.onWebRTCBinaryMessage=="function"&&r.onWebRTCBinaryMessage(i=>n(i)),typeof r.onMessage=="function"&&r.onMessage(i=>{let o=Ec(i);o&&n(o);}),()=>t?.receivers.delete(e)}return t.receivers.add(e),()=>t?.receivers.delete(e)}var Q=class Q{constructor(e,t){this.managedSessionKey=null;this.managedSessionUserId=null;this.managedSessionOptions=null;this.managedSessionTransition=Promise.resolve();this.managedSessionStartInFlight=new Map;this.managedReconciliationTasks=new Set;this.managedReconciliationTimer=null;this.managedReconciliationFollowupTimers=new Set;this.scopedConnectionActorRegistry=null;this.client=new mt(e),this.backend=t??null,t&&this.client.setSignalingBackend(t),this.peerManager=new ii(this.client,this.backend),this.connectionController=new At(this.client,this.backend,()=>this.deviceManager.notifyLifecycleMutation()),this.deviceManager=new ni({client:this.client,backend:this.backend,peerApi:{watchPeerStates:n=>this.client.watchPeerStates(n),refreshPeerSnapshot:()=>this.client.refreshPeerSnapshot(),listConnectedPeers:()=>this.client.listConnectedPeers(),getPeerState:n=>this.client.getPeerState(n)},connectToDevice:n=>this.connectionController.connectToDevice(n),startManagedReconciliation:n=>this.startManagedReconciliation(n),deviceStatusRefreshDebounceMs:Q.DEVICE_STATUS_REFRESH_DEBOUNCE_MS});}static describeTicketForLogs(e){let t=typeof e=="string"?e.trim():"";if(!t)return {hasTicket:false,isCompound:false,scope:null};let n=t.indexOf(".");if(n<0)return {hasTicket:true,isCompound:false,scope:null};try{let i=t.slice(n+1).replace(/-/g,"+").replace(/_/g,"/"),o=(4-i.length%4)%4,s=JSON.parse(atob(i+"=".repeat(o)));return {hasTicket:!0,isCompound:!0,scope:typeof s?.s=="string"?s.s:null}}catch{return {hasTicket:true,isCompound:true,scope:null}}}async serializeManagedSessionOperation(e,t){let n=Date.now(),i=this.managedSessionTransition,o,s=new Promise(c=>{o=c;});this.managedSessionTransition=s,console.info("[RuntimeClient][managed-session][operation-queued]",{label:e,managedSessionUserId:this.managedSessionUserId,hasManagedSession:this.managedSessionKey!==null}),await i.catch(()=>{});let a=Date.now();console.info("[RuntimeClient][managed-session][operation-started]",{label:e,queueWaitMs:a-n,managedSessionUserId:this.managedSessionUserId,hasManagedSession:this.managedSessionKey!==null});try{return await t()}finally{console.info("[RuntimeClient][managed-session][operation-finished]",{label:e,queueWaitMs:a-n,operationMs:Date.now()-a,managedSessionUserId:this.managedSessionUserId,hasManagedSession:this.managedSessionKey!==null}),o(),this.managedSessionTransition===s&&(this.managedSessionTransition=Promise.resolve());}}get identity(){return this.client.currentUser}resolveManagedSessionUserId(e,t){let n=this.identity?.id??null;return n?(t&&t!==n&&console.warn("[RuntimeClient][managed-session][user-id-override]",{requestedUserId:t,runtimeIdentityUserId:n}),n):t??null}resolveManagedAutoConnectEnabled(e){return e.autoConnectPolicy==="disabled"?false:e.autoConnectPolicy==="enabled"?true:e.autoConnectPolicy==="scoped-only"?false:e.autoConnect!==false}resolveManagedPresenceEnabled(e){return e.presencePolicy==="disabled"?false:e.presencePolicy==="online"?true:e.presence!==false}getEffectiveRuntimeUserId(){return this.identity?.id??this.managedSessionUserId??this.managedSessionOptions?.userId??null}async fetchAndApplyAppLimits(){try{await this.client.refreshHostedAppSettings();}catch(e){console.warn("[pluto-rtc] Could not fetch app limits, using free-tier defaults.",e);}}async resolvePeerStreamTarget(e){let t=this.client.getPeerState(e)??null,n=await this.getPeerSession(e).catch(()=>null),i=n?.activeConnectionId?.trim()||null,o=(i?this.client.getConnections().find(a=>!a.isClosed&&a.id===i):void 0)??null,s=n?.nodeId?.trim()||o?.remoteNodeId?.trim()||t?.nodeId?.trim()||null;return {peer:t,session:n,connection:o,remoteNodeId:s}}compatPeerConnectionFromTarget(e,t){let n=e.session?.activeConnectionId?.trim()||`peer-stream:${t}`,i=e.remoteNodeId||t;return {id:n,deviceId:i,remoteNodeId:i,isClosed:false}}isTransportOnlyStreamChannel(e){let t=typeof e=="string"?e.trim():"";if(!t)return false;let n=this.client.listChannels().find(i=>i.id.trim()===t);return on(n??null)}nextNativeStartRetryDelayMs(e){return x$1(e,Q.NATIVE_START_RETRY_MIN_DELAY_MS,Q.NATIVE_START_RETRY_MAX_DELAY_MS)}hasManagedSession(){return !!(this.managedSessionKey||this.managedSessionUserId)}usesNativeIpcBackend(){let t=this.backend?.getRuntimeCapabilities?.();return t?.adapter==="native-ipc"||t?.adapter==="tauri-ipc"||t?.signaling.nativeIpc===true}startManagedReconciliation(e){return this.managedReconciliationTasks.add(e),this.managedReconciliationTimer||(this.managedReconciliationTimer=setInterval(()=>{this.notifyManagedReconciliation();},Q.MANAGED_RECONCILIATION_INTERVAL_MS)),()=>{this.managedReconciliationTasks.delete(e),this.managedReconciliationTasks.size===0&&this.managedReconciliationTimer&&(clearInterval(this.managedReconciliationTimer),this.managedReconciliationTimer=null);}}scheduleManagedReconciliationFollowups(){this.notifyManagedReconciliation();for(let e of this.managedReconciliationFollowupTimers)clearTimeout(e);this.managedReconciliationFollowupTimers.clear();for(let e of [1500,5e3]){let t=setTimeout(()=>{this.managedReconciliationFollowupTimers.delete(t),this.notifyManagedReconciliation();},e);this.managedReconciliationFollowupTimers.add(t);}}stopManagedReconciliation(){this.managedReconciliationTimer&&(clearInterval(this.managedReconciliationTimer),this.managedReconciliationTimer=null);for(let e of this.managedReconciliationFollowupTimers)clearTimeout(e);this.managedReconciliationFollowupTimers.clear(),this.managedReconciliationTasks.clear();}notifyManagedReconciliation(){this.hasManagedSession()&&this.managedReconciliationTasks.forEach(e=>{if(this.hasManagedSession())try{e();}catch{}});}async reconcileNativeManagedSession(e="frontend"){let t=this.backend;t&&typeof t.reconcileNativeManagedSession=="function"&&await t.reconcileNativeManagedSession({reason:e}),await this.refreshPeerSnapshot().catch(()=>[]),this.scheduleManagedReconciliationFollowups();}async notifyNetworkChange(e="host"){let t=this.backend;typeof t.notifyNetworkChange=="function"&&await t.notifyNetworkChange({reason:e});}connectionStateSnapshotKey(e){return JSON.stringify({connectionId:e.connectionId,deviceId:e.deviceId??null,deviceIdHint:e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null,state:e.state,transportState:e.transportState??null,protocolState:e.protocolState??null,routable:e.routable??null,readinessState:e.readinessState??null,readinessReason:e.readinessReason??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null,activeTransport:e.activeTransport??null,parallelTransport:e.parallelTransport??null,replacementInProgress:e.replacementInProgress??null,error:e.error??null,updatedAt:e.updatedAt??null})}async runNativeStartLoop(e){let t=Date.now(),n=0;for(;Date.now()-t<=Q.NATIVE_START_RETRY_WINDOW_MS;){n+=1;try{await e.start(),n>1&&c$1(`[RuntimeClient] ${e.label} recovered after ${n} attempts`);return}catch(i){if(this.isUnsupportedRuntimeAdapterError(i,e.label))throw i;let o=this.nextNativeStartRetryDelayMs(n);console.warn(`[RuntimeClient] ${e.label} failed attempt=${n} retry_in_ms=${o}:`,i),await u(o);}}throw new Error(e.exhaustedMessage)}isUnsupportedRuntimeAdapterError(e,t){if(!(e instanceof Error))return false;let n=e.message||"",i=t==="startPresenceLoop"?"startPresenceLoopOnce":t==="startAutoConnect"?"startAutoConnectOnce":null;return !!i&&n.includes(`does not support ${i}`)}onIdentityChange(e){return this.client.onAuthChange(e)}async signInAnonymously(){await this.client.signInAnonymously();}async signInWithPluto(){await this.client.signInWithPluto();}async setAuthContext(e){let t=this.backend;if(!t||typeof t.setAuthContext!="function")throw new Error("RuntimeClient auth context requires a runtime adapter that supports setAuthContext().");let n=typeof e?.userId=="string"&&e.userId.trim()||null,i=this.managedSessionUserId;i&&i!==n&&(console.info("[RuntimeClient][auth-context][managed-session-replace]",{previousUserId:i,nextUserId:n}),await this.stopManagedSession()),await t.setAuthContext(e);}async signOut(){await this.stopManagedSession().catch(()=>{}),await this.client.signOut();}async initialize(){if(this.usesNativeIpcBackend()){console.info("[RuntimeClient][native] initialize() skipped; native IPC backend owns runtime startup");return}await this.client.init();}async getRuntimeStatus(){return this.client.getRuntimeStatus()}getPeerReconciliationStats(){return this.client.getPeerReconciliationStats()}getRuntimePolicy(){return w}getRuntimeCapabilities(){let e=this.backend;return typeof e?.getRuntimeCapabilities=="function"?e.getRuntimeCapabilities():B$1()}getCapabilityProfile(){return D(this.getRuntimeCapabilities())}async start(e){if(this.usesNativeIpcBackend()){let t=await this.getManagedNodeId({initializeIfMissing:true});if(!t)throw new Error("Native runtime started without a node id for the admitted application-stream queue.");this.client.attachIncomingStreamSource(this.backend,t),await this.client.startListening({startPresence:false});return}e?.clearSessionTokens!==false&&await this.client.clearSessionTokens().catch(()=>{}),await this.client.refreshRuntimeAuthToken("runtime-start"),await this.client.startListening();}stop(){this.client.stopListening();}async getNodeId(){if(this.usesNativeIpcBackend()){let e=await this.getManagedNodeId({initializeIfMissing:true});if(!e)throw new Error("Native node id unavailable from IPC backend");return e}return this.client.getNodeId()}async getNodeIdFromTicket(e){return this.client.getNodeIdFromTicket(e)}async getLocalDeviceId(){return this.client.getLocalDeviceId()}async getLocalDeviceInfo(){let e=this.backend;return !e||typeof e.getLocalDeviceInfo!="function"?null:e.getLocalDeviceInfo()}async getLocalDeviceProfile(e){let t=await this.getLocalDeviceInfo().catch(()=>null),n=e?.localDeviceId??t?.deviceId??await this.getLocalDeviceId().catch(()=>null)??null,i=await this.getRuntimeStatus().catch(()=>({runtime:"unknown",wasmLoaded:false,localNodeId:void 0,userId:void 0})),o=e?.platform??(i.runtime==="tauri"?"native":"web");return {deviceId:n,deviceName:e?.deviceName||t?.deviceName||"Unknown Device",platformType:t?.platformType||(o==="native"?"desktop":"web"),userId:e?.userId??this.identity?.id??i.userId??null,capabilities:t?.capabilities??{can_host:o==="native",can_sync:o==="native",read_only:o!=="native"},lastSeenAt:t?.lastSeenAt||new Date().toISOString(),localNodeId:i.localNodeId||null}}async updateLocalDeviceName(e){let t=this.backend;return !t||typeof t.updateLocalDeviceName!="function"?null:t.updateLocalDeviceName(e)}async getManagedNodeId(e){let t=this.backend;if(console.info("[RuntimeClient][getManagedNodeId] enter",{hasBackend:!!t,hasMethod:!!(t&&typeof t.getManagedNodeId=="function"),backendCtor:t?.constructor?.name??null}),!t||typeof t.getManagedNodeId!="function")return null;let n=await t.getManagedNodeId(e);return console.info("[RuntimeClient][getManagedNodeId] resolved",{result:n}),n}async getTicket(){return this.usesNativeIpcBackend()?this.getEndpointTicket():this.client.getTicket()}async getTicketWithToken(e,t=0){let n=this.backend;if(n?.getEndpointTicketWithToken)try{let i=await n.getEndpointTicketWithToken(e,t);if(i)return i}catch(i){if(this.usesNativeIpcBackend())throw i}if(this.usesNativeIpcBackend())throw new Error("Native endpoint ticket with token unavailable from IPC backend");return this.client.getEndpointTicketWithToken(e,t)}async revokeTokensByScope(e){return this.revokeTokensByScopeInternal(e,{rotateManagedScopeIfActive:true})}async revokeTokensByScopeInternal(e,t){o("revokeTokensByScopeInternal",{grantScope:e,rotateManagedScopeIfActive:t?.rotateManagedScopeIfActive!==false,hasManagedSessionOptions:!!this.managedSessionOptions});let n=this.usesNativeIpcBackend(),i=n?[]:await this.client.revokeTokensByScope(e),o$1=this.backend,s=[];if(o$1?.revokeSessionTokensByScope)s=await o$1.revokeSessionTokensByScope(e).catch(()=>[]);else if(n)throw new Error("Native token revoke requires revokeSessionTokensByScope() on the IPC backend.");let a=Array.from(new Set([...i,...s]));return t?.rotateManagedScopeIfActive!==false&&e===Q.MANAGED_USER_DEVICE_SCOPE&&this.managedSessionOptions&&this.managedSessionOptions.presence!==false&&await this.rotateManagedUserDeviceGrant(),a}revokeSessionToken(e){this.client.revokeSessionToken(e);}watchFriendDevices(e,t){let n=this.backend;return n?.watchFriendDevices?n.watchFriendDevices(e,t):()=>{}}async getFriendTicket(e=0){return this.getTicketWithToken(Q.MANAGED_FRIEND_SCOPE,e)}async revokeFriendTokens(){return this.revokeTokensByScope(Q.MANAGED_FRIEND_SCOPE)}async updateFriendTicket(e){let t=this.backend;t?.updateFriendTicket&&await t.updateFriendTicket(e);}async getEndpointTicket(){let e=this.backend;if(e&&typeof e.getEndpointTicket=="function")try{return await e.getEndpointTicket()}catch(t){if(this.usesNativeIpcBackend())throw t}if(this.usesNativeIpcBackend())throw new Error("Native endpoint ticket unavailable from IPC backend");return this.client.getTicket()}async startManagedSession(e){let t=this.resolveManagedSessionUserId(e.platform,e.userId??null),n=JSON.stringify({platform:e.platform,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,userId:t,autoConnect:this.resolveManagedAutoConnectEnabled(e),autoConnectPolicy:e.autoConnectPolicy??null,presence:this.resolveManagedPresenceEnabled(e),presencePolicy:e.presencePolicy??null}),i=this.managedSessionStartInFlight.get(n);if(i)return i;let o$1=this.serializeManagedSessionOperation("start",async()=>{if(this.managedSessionKey===n){if(e.platform==="native"&&t){let l=this.backend;if(l&&typeof l.startManagedSessionNative=="function")try{let p=await l.startManagedSessionNative({userId:t,deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,metadata:e.metadata,autoConnect:this.resolveManagedAutoConnectEnabled(e),presence:this.resolveManagedPresenceEnabled(e)});console.info("[RuntimeClient][managed-session][native-replayed]",{userId:t,localNodeId:p.localNodeId,presenceStarted:p.presenceStarted,autoConnectStarted:p.autoConnectStarted,localDeviceId:p.localDevice?.deviceId??null});}catch(p){console.warn("[RuntimeClient][managed-session][native-replay-failed]",{userId:t,message:p instanceof Error?p.message:String(p)});}}let c=await this.getLocalDeviceProfile({deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,platform:e.platform,userId:t});return {mode:e.platform,device:c,stop:async()=>this.stopManagedSession()}}o("managed-session-replace",{previousSessionKey:this.managedSessionKey,nextSessionKey:n}),await this.stopManagedSessionInternal(),this.managedSessionKey=n,this.managedSessionUserId=t,this.managedSessionOptions={...e,userId:t};let s=null,a=null;console.info("[RuntimeClient][managed-session][start]",{platform:e.platform,requestedUserId:e.userId??null,runtimeUserId:this.identity?.id??null,effectiveUserId:this.managedSessionUserId,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,localDeviceId:e.localDeviceId??null,deviceName:e.deviceName??null,presence:this.resolveManagedPresenceEnabled(e),presencePolicy:e.presencePolicy??null,autoConnect:this.resolveManagedAutoConnectEnabled(e),autoConnectPolicy:e.autoConnectPolicy??null});try{if(e.platform==="web")await this.initialize(),this.resolveManagedPresenceEnabled(e)?(await this.client.clearSessionTokens().catch(()=>{}),s=await this.getTicketWithToken(Q.MANAGED_USER_DEVICE_SCOPE,0),this.client.setManagedPresenceTicket(s),await this.start({clearSessionTokens:!1})):(this.client.clearManagedPresenceTicket(),await this.start());else {if(!this.managedSessionUserId)throw new Error("Native managed session startup requires an authenticated user id.");await this.client.ensureAuthenticated("discovery");let l=this.backend;if(!l||typeof l.startManagedSessionNative!="function")throw new Error("Native managed session startup requires a native backend-owned startManagedSessionNative() surface.");a=await l.startManagedSessionNative({userId:this.managedSessionUserId,deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,metadata:e.metadata,autoConnect:this.resolveManagedAutoConnectEnabled(e),presence:this.resolveManagedPresenceEnabled(e)}),console.info("[RuntimeClient][managed-session][native-started]",{userId:this.managedSessionUserId,localNodeId:a.localNodeId,ticketScope:a.ticketScope??null,presenceStarted:a.presenceStarted,autoConnectStarted:a.autoConnectStarted,localDeviceId:a.localDevice?.deviceId??null});let p=a.localNodeId??await this.getManagedNodeId({initializeIfMissing:!1});if(!p)throw new Error("Native managed session started without a node id for the admitted application-stream queue.");this.client.attachIncomingStreamSource(this.backend,p),await this.client.startListening({startPresence:!1});}this.fetchAndApplyAppLimits();let c=await this.getLocalDeviceProfile({deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,platform:e.platform,userId:this.managedSessionUserId});return e.platform==="native"?(this.resolveManagedPresenceEnabled(e)&&!a?.presenceStarted&&console.warn("[RuntimeClient][managed-session][native-presence-missing]",{userId:this.managedSessionUserId,deviceId:c.deviceId}),this.resolveManagedAutoConnectEnabled(e)&&c.deviceId&&!a?.autoConnectStarted&&console.warn("[RuntimeClient][managed-session][native-auto-connect-missing]",{userId:this.managedSessionUserId,deviceId:c.deviceId})):this.resolveManagedPresenceEnabled(e)&&(console.info("[RuntimeClient][managed-session][start-presence]",{platform:e.platform,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,userId:this.managedSessionUserId,deviceId:c.deviceId,deviceName:c.deviceName,ticketScope:Q.describeTicketForLogs(s).scope}),await this.startPresenceLoop({deviceName:c.deviceName,ticket:s,metadata:e.metadata}),console.info("[RuntimeClient][managed-session][presence-started]",{platform:e.platform,userId:this.managedSessionUserId,deviceId:c.deviceId})),e.platform!=="native"&&this.resolveManagedAutoConnectEnabled(e)&&c.deviceId&&(await this.startAutoConnect(c.deviceId),console.info("[RuntimeClient][managed-session][auto-connect-started]",{platform:e.platform,sessionKind:e.sessionKind??"app-user-device",scope:e.scope??null,userId:this.managedSessionUserId,deviceId:c.deviceId})),await this.refreshPeerSnapshot().catch(()=>[]),this.scheduleManagedReconciliationFollowups(),{mode:e.platform,device:c,stop:async()=>this.stopManagedSession()}}catch(c){throw console.warn("[RuntimeClient][managed-session][start-failed-cleanup]",{platform:e.platform,requestedUserId:e.userId??null,runtimeUserId:this.identity?.id??null,effectiveUserId:this.managedSessionUserId,message:c instanceof Error?c.message:String(c)}),await this.stopManagedSessionInternal().catch(()=>{}),c}});this.managedSessionStartInFlight.set(n,o$1);try{return await o$1}finally{this.managedSessionStartInFlight.delete(n);}}async stopManagedSession(e){return this.serializeManagedSessionOperation(e?.preserveBackendSession?"stop-preserve-backend":"stop",()=>this.stopManagedSessionInternal(e))}async stopManagedSessionInternal(e){if(!this.managedSessionKey&&!this.managedSessionUserId)return;let t=!!e?.preserveBackendSession;o("stopManagedSessionInternal",{preserveBackendSession:t,managedSessionKey:this.managedSessionKey,managedSessionUserId:this.managedSessionUserId??null});let n=this.backend;this.managedSessionOptions;let o$1=Date.now();if(console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"local-invalidate",elapsedMs:0,managedSessionUserId:this.managedSessionUserId,preserveBackendSession:t}),this.client.clearManagedPresenceTicket(),t?console.info("[RuntimeClient] Preserving native backend-managed session across frontend teardown",{userId:this.managedSessionUserId??this.identity?.id??null,scope:Q.MANAGED_USER_DEVICE_SCOPE}):(console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"revoke-user-device-grants",elapsedMs:Date.now()-o$1,managedSessionUserId:this.managedSessionUserId}),await this.revokeTokensByScopeInternal(Q.MANAGED_USER_DEVICE_SCOPE,{rotateManagedScopeIfActive:false}).catch(()=>[]),this.stop(),n&&typeof n.stopAuthScopedActivity=="function"?(console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"stop-backend-auth-scope",elapsedMs:Date.now()-o$1,managedSessionUserId:this.managedSessionUserId}),await n.stopAuthScopedActivity({userId:this.managedSessionUserId??this.identity?.id??null})):await this.setOffline().catch(()=>{})),t){this.notifyManagedReconciliation();return}await this.scopedConnectionActorRegistry?.shutdownAll().catch(s=>{console.warn("[RuntimeClient] scoped connection actor shutdown failed",s);}),this.scopedConnectionActorRegistry=null,this.managedSessionKey=null,this.managedSessionUserId=null,this.managedSessionOptions=null,console.info("[RuntimeClient][managed-session][stop-stage]",{stage:"complete",elapsedMs:Date.now()-o$1,managedSessionUserId:null});}async rotateManagedUserDeviceGrant(){let e=this.managedSessionOptions;if(!e||!this.resolveManagedPresenceEnabled(e))return;if(e.platform==="native"){let o=this.backend;if(!o||typeof o.startManagedSessionNative!="function")throw new Error("Native managed ticket rotation requires a native backend-owned startManagedSessionNative() surface.");let s=this.managedSessionUserId??e.userId??this.identity?.id??null;if(!s)throw new Error("Native managed ticket rotation requires an authenticated user id.");await o.startManagedSessionNative({userId:s,deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,metadata:e.metadata,autoConnect:this.resolveManagedAutoConnectEnabled(e),presence:this.resolveManagedPresenceEnabled(e)}),console.info("[RuntimeClient][managed-ticket][rotate]",{scope:Q.MANAGED_USER_DEVICE_SCOPE,platform:e.platform,userId:s});return}let t=await this.getTicketWithToken(Q.MANAGED_USER_DEVICE_SCOPE,0),n=this.managedSessionUserId??e.userId??this.identity?.id??null;this.client.setManagedPresenceTicket(t);let i=await this.getLocalDeviceProfile({deviceName:e.deviceName,localDeviceId:e.localDeviceId??null,platform:e.platform,userId:e.userId??null});await this.startPresenceLoop({deviceName:i.deviceName,ticket:t,metadata:e.metadata}),console.info("[RuntimeClient][managed-ticket][rotate]",{scope:Q.MANAGED_USER_DEVICE_SCOPE,platform:e.platform,userId:n});}async listDevices(){return this.deviceManager.listDevices()}async listDevicesWithStatus(){return this.deviceManager.listDevicesWithStatus()}async updateDevice(e,t){await this.deviceManager.updateDevice(e,t);}async deleteDevice(e){await this.deviceManager.deleteDevice(e);}watchDevices(e){return this.deviceManager.watchDevices(e)}watchDevicesWithStatus(e){return this.deviceManager.watchDevicesWithStatus(e)}async connectDeviceWithRetry(e,t,n){return this.deviceManager.connectDeviceWithRetry(e,t,n)}async connectDevice(e,t){return this.deviceManager.connectDevice(e,t)}watchPeerStates(e){return this.client.watchPeerStates(e)}watchPeerLifecycle(e){return this.watchPeerStates(e)}getPeerState(e){return this.client.getPeerState(e)}async resolvePeerConnectionRecords(e){return this.peerManager.resolvePeerConnectionRecords(e)}async getPeerSession(e){return this.peerManager.getPeerSession(e)}async listPeerSessions(){return this.peerManager.listPeerSessions()}async waitForConnectedPeer(e,t){return this.peerManager.waitForConnectedPeer(e,t)}async getPeerReadiness(e,t){return this.peerManager.getPeerReadiness(e,t)}async resolvePeerIdentity(e){return this.peerManager.resolvePeerIdentity(e)}async resolveIncomingStreamPeer(e){return this.peerManager.resolveIncomingStreamPeer(e)}listConnectedPeers(){return this.client.listConnectedPeers()}addPeerScope(e,t){return this.peerManager.addPeerScope(e,t)}releasePeerScope(e,t){return this.peerManager.releasePeerScope(e,t)}getPeerScopes(e){return this.peerManager.getPeerScopes(e)}isSamePeer(e,t){return this.peerManager.isSamePeer(e,t)}async refreshPeerSnapshot(){return this.client.refreshPeerSnapshot()}async subscribeSessions(e,t){return this.client.subscribeSessions(e,t)}getAppLimits(){return this.client.appLimits}syncRoomRtdbPresenceFromBackend(){let e=this.backend?.rtdbPresence;e&&this.client.rooms.setRtdbPresence(e);}async createRoom(e){return this.syncRoomRtdbPresenceFromBackend(),this.client.rooms.createRoom(e)}async joinRoom(e,t){return this.syncRoomRtdbPresenceFromBackend(),this.client.rooms.joinRoom(e,t)}async leaveRoom(e){return this.client.rooms.leaveRoom(e)}async getRoomMembers(e){return this.client.rooms.getRoomMembers(e)}watchRoom(e,t){return this.client.rooms.watchRoom(e,t)}async connectByTicket(e){return this.client.connect(e.ticket,e.timeoutMs)}async connectPeer(e){return this.client.connectPeer(e)}async connectScopedChannel(e){let t=e.timeoutMs===void 0?void 0:Math.max(1,e.timeoutMs),n=t===void 0?void 0:Date.now()+t,i=N=>{if(n===void 0||t===void 0)return;let O=n-Date.now();if(O<=0)throw new Error(`connectScopedChannel timeout after ${t}ms during ${N}`);return Math.max(1,O)},o=e.scope,s=e.channelId.trim();if(!s)throw new Error("connectScopedChannel requires a channelId");let a=e.peerId??e.peerNodeId??e.deviceId??(e.ticket?await this.getNodeIdFromTicket(e.ticket).catch(()=>null):null);if(!a)throw new Error("connectScopedChannel requires peerId, peerNodeId, deviceId, or a ticket with an embedded node id");let c=this.client.getConnections().find(N=>!N.isClosed&&(N.remoteNodeId===a||N.deviceId===a))??null,l=c?[c.id,c.remoteNodeId,c.deviceId,a,e.deviceId].map(N=>typeof N=="string"?N.trim():"").filter(Boolean).map(N=>this.client.getPeerState(N)).find(N=>N!==void 0):void 0,p=c?await this.resolvePeerConnectionRecords(e.deviceId??a).catch(()=>[]):[],u$1=this.usesNativeIpcBackend()?await this.getPeerSession(e.deviceId??a).catch(()=>null):null,g=p.some(N=>N.state.toLowerCase()==="connected"&&N.transportStableId!==null&&N.transportStableId!==void 0),y=l?.status==="connected"&&l.lifecycleStage!=="closed"&&l.baseTransportState!=="closed"&&l.routable!==false,m=(p.length>0?g:y)&&l?.scopes.includes(o)===true,v=u$1?.status==="connected"&&u$1.settledReady===true&&u$1.scopes.includes(o);c$1("[RuntimeClient][connectScopedChannel] existing route decision",{peerId:a,scope:o,hasWrapper:c!==null,projectedStatus:l?.status??null,projectedScopes:l?.scopes??[],managedRecords:p.map(N=>({connectionId:N.connectionId,state:N.state,transportStableId:N.transportStableId??null})),nativeSession:u$1?{peerId:u$1.peerId,deviceId:u$1.deviceId??null,nodeId:u$1.nodeId??null,status:u$1.status,settledReady:u$1.settledReady===true,scopes:u$1.scopes}:null,reuse:m||v});let S=m?c:null,I=null,k=v?u$1?.nodeId??a:null;if(!S)if(this.usesNativeIpcBackend()){if(!v)if(e.ticket){let N=o===Q.MANAGED_USER_DEVICE_SCOPE?e.deviceId:null,O=await this.connectToDevice({endpointTicket:e.ticket,deviceId:N,timeoutMs:i("native peer dial")}),z=O.remoteNodeId??O.deviceId??O.deviceIdHint??a;k=z,S=this.client.getConnections().find(G=>!G.isClosed&&(G.id===O.connectionId||G.remoteNodeId===z||G.deviceId===z||G.deviceId===e.deviceId))??null;}else throw new Error("native connectScopedChannel requires an endpoint ticket when no connection exists")}else I=this.getScopedConnectionActor({scope:o,peerNodeId:a},{ticket:e.ticket,timeoutMs:i("scoped peer actor"),channelId:s,dial:async()=>{S=await this.connectPeer({ticket:e.ticket,deviceId:e.deviceId??a,scope:o,channelId:s,timeoutMs:i("browser peer dial"),respectManualDisconnect:e.respectManualDisconnect??true});}}),await I.ensureReady();S||(this.usesNativeIpcBackend()?S=this.client.getConnections().find(N=>!N.isClosed&&(N.remoteNodeId===(k??a)||N.deviceId===a))??null:S=await this.connectPeer({ticket:e.ticket,deviceId:e.deviceId??a,scope:o,channelId:s,timeoutMs:i("peer dial fallback"),respectManualDisconnect:e.respectManualDisconnect??true}));let T=S?.remoteNodeId??k??a,D=S,_=e.nativeLabel===true,E=e.framing??"raw",A=async()=>{if(_)try{let O=await this.openPeerNativeBi(T,s,{timeoutMs:i("native labelled stream open"),scope:o});return {connection:O.connection,readable:O.readable,writer:O.writable.getWriter(),openedWithNativeLabel:!0}}catch(O){c$1("[RuntimeClient][connectScopedChannel] native-labelled stream open failed; falling back",{peerId:T,channelId:s,error:String(O)});let z=await this.openPeerBi(T,{timeoutMs:i("scoped stream fallback"),scope:o,channelId:s});return {connection:z.connection,readable:z.readable,writer:z.writable.getWriter(),openedWithNativeLabel:true}}let N=await this.openPeerBi(T,{timeoutMs:i("scoped stream open"),scope:o,channelId:s});return {connection:N.connection,readable:N.readable,writer:N.writable.getWriter(),openedWithNativeLabel:false}},j=await A();S=D??j.connection;let q=j.writer,F=j.openedWithNativeLabel,W=new Set,U=false,Z=false,ne=0,Me=null,qe=null,ri=Promise.resolve(),yt=null,si=null,Ke=null,ai=N=>{s!=="drive-view"||!N||N===si||typeof N.onWebRTCBinaryMessage!="function"&&typeof N.onMessage!="function"||(Ke?.(),Ke=xc(N,O=>{if(U||!no(O))return false;for(let z of [...W])z(O);return true}),si=N);},ze=()=>{let N=new Set([S?.id,S?.remoteNodeId,S?.deviceId,T,a,e.deviceId,e.peerId,e.peerNodeId].map(G=>typeof G=="string"?G.trim():"").filter(Boolean)),O=this.client.getConnections().filter(G=>!G.isClosed&&(N.has(G.id)||N.has(G.remoteNodeId)||N.has(G.deviceId??""))),z=O.find(G=>Gs(G))??O.find(G=>typeof G.sendOnWebRTC=="function"||typeof G.getWebRTCTransport=="function")??O[0]??null;if(z&&z!==S&&(S=z),!S)throw new Error(`Scoped channel '${s}' has no active connection`);return ai(S),S};ai(S);let ci=N=>{let O=N.getReader(),z=++ne,G=new Uint8Array(0);Me=O,Z=false,(async()=>{try{for(;!U&&z===ne;){let{value:re,done:oo}=await O.read();if(oo)break;if(!(!re||re.byteLength===0)){if(E==="raw"){for(let Se of [...W])Se(re);continue}for(G=Ri(G,re);G.byteLength>=4;){let Se=Pi(G,0);if(G.byteLength<4+Se)break;let ro=G.slice(4,4+Se);G=G.slice(4+Se);for(let di of [...W])di(ro);}}}}catch(re){!U&&z===ne&&c$1("[RuntimeClient][connectScopedChannel] physical stream read loop ended with error",{peerId:T,channelId:s,error:String(re)});}finally{z===ne&&(Z=true,Me===O&&(Me=null));try{O.releaseLock();}catch{}}})();};ci(j.readable);let li=async()=>{Z&&(qe||(qe=(async()=>{let N=q,O=await A();if(U){try{await O.readable.cancel("scoped channel closed during physical stream reopen");}catch{}try{await O.writer.abort("scoped channel closed during physical stream reopen");}catch{}try{O.writer.releaseLock();}catch{}throw new Error(`Scoped channel '${s}' is closed`)}S=O.connection??S,q=O.writer,F=F||O.openedWithNativeLabel,ci(O.readable);try{await N.abort("scoped channel physical stream replaced");}catch{}try{N.releaseLock();}catch{}})().finally(()=>{qe=null;})),await qe);},io=async N=>{let O=ri.then(async()=>{if(U)throw new Error(`Scoped channel '${s}' is closed`);let z=ze();if(s==="drive-view"&&Gs(z))try{await z.send(N),yt=z.getLastApplicationPayloadTransport?.()??z.getTransportStatus?.().activeTransport??null;return}catch(re){c$1("[RuntimeClient][connectScopedChannel] current-route scoped-channel send failed; falling back to stream",{peerId:T,channelId:s,error:String(re)});}let G=E==="u32be"?Ii(N):N;await li();try{await q.write(G);}catch(re){if(U)throw re;Z=true,await li(),await q.write(G);}yt="stream";});ri=O.catch(()=>{}),await O;};if(!this.usesNativeIpcBackend()){let N=Math.max(1,Math.min(i("application route settlement")??5e3,5e3)),O=Date.now();for(;;){let z=ze();if(typeof z.isReadyForApplicationPayload!="function"||z.isReadyForApplicationPayload())break;if(Date.now()-O>=N){U=true,ne+=1;let G=Me;try{await G?.cancel("scoped channel application route timeout");}catch{}try{await q.abort("scoped channel application route timeout");}catch{}try{q.releaseLock();}catch{}throw await I?.shutdown().catch(()=>{}),new Error(`Scoped channel '${s}' timed out waiting for an application payload route`)}await u(20);}}return {channelId:s,peerId:T,get connection(){return ze()},send:io,onMessage(N){return W.add(N),()=>W.delete(N)},async close(){if(!U){U=true,ne+=1,W.clear(),Ke?.(),Ke=null;try{await Me?.cancel("scoped channel closed");}catch{}try{await q.abort("scoped channel closed");}catch{}try{q.releaseLock();}catch{}await I?.shutdown().catch(()=>{});}},diagnostics:()=>{let N=ze();return {connectionId:N.id??null,remoteNodeId:N.remoteNodeId??null,transports:N.getAvailableTransports?.()??[],hasSendOnWebRTC:typeof N.sendOnWebRTC=="function",hasWebRTCTransport:typeof N.getWebRTCTransport=="function"?N.getWebRTCTransport()!==null:false,lastSendTransport:yt,framing:E,nativeLabel:F||_}}}}getScopedConnectionActor(e,t){let n=a=>{let c=t?.ticket,l=t?.channelId,p=t?.dial;return new Xe({key:a,dial:async u=>{if(this.assertScopedDialAllowed(u),p){await p(u);return}await this.connectPeer({deviceId:u.peerNodeId,ticket:c,scope:u.scope,channelId:l,respectManualDisconnect:true});},close:async()=>{}})};this.scopedConnectionActorRegistry||(this.scopedConnectionActorRegistry=new Ze(n));let i=Si(e.scope,e.peerNodeId),o=this.scopedConnectionActorRegistry.get(i),s=this.scopedConnectionActorRegistry.getOrSpawn(i,n);return (o===null||o!==null&&o!==s)&&oe("[runtime-client][scoped-connection-actor]",Je(i.scope,{peerNodeId:i.peerNodeId}),"spawn"),s}assertScopedDialAllowed(e){let t=this.scopedDialCandidateIds(e).find(n=>this.hasManualDisconnectSuppression(n));if(t)throw oe("[runtime-client][scoped-connection-actor]",Je(e.scope,{peerNodeId:e.peerNodeId}),"dial_suppressed_manual_disconnect peerId={}",t),new Error(`scoped connection dial suppressed by manual disconnect for peer ${t}`)}scopedDialCandidateIds(e){let t=new Set,n=e.peerNodeId.trim();n&&t.add(n);let i=e.scope.trim();if(i.startsWith("trusted-device:")){let o=i.slice(15).split(":")[0]?.trim();o&&t.add(o);}return [...t]}hasManualDisconnectSuppression(e){let t=this.client.getPeerState(e);if(!t)return false;if(t.manualDisconnect===true)return true;let n=t,i=[t.error,n.lastDisconnectReason].filter(o=>typeof o=="string"&&o.length>0).join(" ");return /manual disconnect/i.test(i)}async shutdownScopedConnectionActors(){if(!this.scopedConnectionActorRegistry)return;let e=this.scopedConnectionActorRegistry.size();oe("[runtime-client][scoped-connection-actor]",{sessionKind:"drive-grant-guest"},"shutdown_all count={}",e),await this.scopedConnectionActorRegistry.shutdownAll();}async openPeerBi(e,t){let n=this.backend;if(n&&typeof n.openPeerBi=="function"){await this.waitForBrowserApplicationCrypto(e,t?.timeoutMs);let i=await n.openPeerBi(e,t?.timeoutMs),o=await this.resolvePeerStreamTarget(e);return {connection:o.connection??this.compatPeerConnectionFromTarget(o,e),readable:i.readable,writable:t?.channelId?this.client.wrapChannelWritable(i.writable,t.channelId):i.writable}}throw new Error("[pluto-rtc] openPeerBi() requires a Rust-backed runtime adapter that implements openPeerBi().")}async openPeerNativeBi(e,t,n){let i=this.backend;if(i&&typeof i.openPeerNativeBi=="function"){await this.waitForBrowserApplicationCrypto(e,n?.timeoutMs);let o=await i.openPeerNativeBi(e,t,n?.timeoutMs),s=await this.resolvePeerStreamTarget(e);return {connection:s.connection??this.compatPeerConnectionFromTarget(s,e),readable:o.readable,writable:o.writable}}throw new Error("[pluto-rtc] openPeerNativeBi() requires a Rust-backed runtime adapter that implements openPeerNativeBi().")}async openPeerBiTransportOnly(e,t){let n=this.backend;if(n&&typeof n.openPeerBiTransportOnly=="function"){let i=await n.openPeerBiTransportOnly(e,t?.timeoutMs),o=await this.resolvePeerStreamTarget(e);return {connection:o.connection??this.compatPeerConnectionFromTarget(o,e),readable:i.readable,writable:t?.channelId?this.client.wrapChannelWritable(i.writable,t.channelId):i.writable}}return this.openPeerBi(e,t)}async openPeerUni(e,t){let n=this.backend;if(n&&typeof n.openPeerUni=="function"){await this.waitForBrowserApplicationCrypto(e,t?.timeoutMs);let i=await n.openPeerUni(e,t?.timeoutMs),o=await this.resolvePeerStreamTarget(e);return {connection:o.connection??this.compatPeerConnectionFromTarget(o,e),writable:t?.channelId?this.client.wrapChannelWritable(i.writable,t.channelId):i.writable}}throw new Error("[pluto-rtc] openPeerUni() requires a Rust-backed runtime adapter that implements openPeerUni().")}async waitForBrowserApplicationCrypto(e,t){if(this.usesNativeIpcBackend())return;let n=Math.max(1,t??1e4);if(!await this.client.waitForApplicationCryptoForPeer(e,n))throw new Error(`[OpenRTC] protected application stream to '${e}' timed out waiting for application crypto`)}async connectToDevice(e){return this.connectionController.connectToDevice(e)}async connectRaw(e){return this.connectionController.connectRaw(e)}async openBi(e){return this.connectionController.openBi(e)}async openUni(e){return this.connectionController.openUni(e)}onIncomingStream(e){return this.client.onIncomingStream(e)}registerChannel(e){this.client.registerChannel(e);}unregisterChannel(e){this.client.unregisterChannel(e);}listChannels(){return this.client.listChannels()}onIncomingChannelStream(e,t){return this.client.onIncomingChannelStream(e,t)}async sendExplicitFilePath(e,t,n){let i=this.backend;if(!i||typeof i.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return i.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){let t=this.backend;if(!t||typeof t.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");let n=this.client.getConnectionForPeer(e.connectionId,e.remoteNodeId),i=e.requireApplicationCrypto??(typeof n?.isApplicationCryptoRequired=="function"?n.isApplicationCryptoRequired():void 0),o=e.remoteNodeId??n?.remoteNodeId??e.connectionId??n?.deviceId,s=e.applicationCrypto??this.client.getApplicationCrypto(n??void 0)??this.client.resolveApplicationCryptoForPeer(o,n??void 0)??(i?await this.client.waitForApplicationCryptoForPeer(o):void 0),a=e.receiverPlatformType;if(a===void 0){let l=new Set([e.remoteNodeId,n?.remoteNodeId,n?.deviceId,e.connectionId].map(p=>typeof p=="string"?p.trim():"").filter(p=>p.length>0));if(l.size>0){let u=(await this.listDevicesWithStatus().catch(()=>[])).find(g=>l.has(String(g.deviceId??""))||l.has(String(g.peerId??""))||l.has(String(g.nodeId??""))||l.has(String(g.connectionId??"")));a=typeof u?.platformType=="string"&&u.platformType.trim().length>0?u.platformType:null;}}let c={...e,connection:e.connection??n,remoteNodeId:e.remoteNodeId??n?.remoteNodeId,receiverPlatformType:a,applicationCrypto:s,requireApplicationCrypto:i};return t.sendExplicitFileData(c)}async getTransferHistory(e){let t=this.backend;return !t||typeof t.getTransferHistory!="function"?[]:t.getTransferHistory(e)}async deleteTransferJob(e){let t=this.backend;if(!(!t||typeof t.deleteTransferJob!="function"))return t.deleteTransferJob(e)}async startPresenceLoop(e){let t=this.backend;if(this.usesNativeIpcBackend()&&t&&typeof t.startPresenceLoopOnce=="function"){let n=this.getEffectiveRuntimeUserId();if(!n){await this.client.startPresenceLoop(e);return}let i=await this.getManagedNodeId({initializeIfMissing:true}).catch(()=>null),o=i||await this.getNodeId(),s=e?.ticket||await this.getEndpointTicket(),a=await this.getLocalDeviceProfile({deviceName:e?.deviceName,platform:"native",userId:n}),c=Q.describeTicketForLogs(s);console.info("[RuntimeClient][native-presence][start]",{userId:n,localNodeId:o,nodeSource:i?"native-managed":"client-getNodeId-fallback",deviceId:a.deviceId,deviceName:e?.deviceName||a.deviceName,ticketScope:c.scope,isCompoundTicket:c.isCompound});try{await this.runNativeStartLoop({label:"startPresenceLoop",exhaustedMessage:`[RuntimeClient] startPresenceLoop exhausted retries user_id=${n} local_node_id=${o}`,start:()=>t.startPresenceLoopOnce(n,o,e?.deviceName||a.deviceName,s,e?.metadata)});}catch(p){if(!this.isUnsupportedRuntimeAdapterError(p,"startPresenceLoop"))throw p;await this.client.startPresenceLoop(e);return}console.info("[RuntimeClient][native-presence][started]",{userId:n,localNodeId:o,nodeSource:i?"native-managed":"client-getNodeId-fallback",deviceId:a.deviceId});let l=t.rtdbPresence;l&&this.client.rooms.setRtdbPresence(l);return}await this.client.startPresenceLoop(e);}async updatePresence(e){await this.client.updatePresence(e?.isOnline,e?.ttlMs,e?.metadata,e?.ticket);}async refreshLivePresence(e){let t=this.backend;if(!t||typeof t.refreshLivePresence!="function"){await this.updatePresence(e);return}let n=await this.getNodeId(),i=e?.ticket||await this.getEndpointTicket();await t.refreshLivePresence(n,i,e?.metadata);}async setOffline(){await this.client.setOffline();}async cleanupStaleDevices(){await this.client.cleanupStaleDevices();}async startAutoConnect(e){await this.client.refreshRuntimeAuthToken("runtime-start");let t=this.backend;if(t&&typeof t.startAutoConnectOnce=="function"){let n=this.getEffectiveRuntimeUserId();if(!n)throw new Error("startAutoConnect requires an authenticated user");let i=e||await this.getLocalDeviceId();if(!i)throw new Error("startAutoConnect requires a local device id");try{await this.runNativeStartLoop({label:"startAutoConnect",exhaustedMessage:`[RuntimeClient] startAutoConnect exhausted retries user_id=${n} local_device_id=${i}`,start:()=>t.startAutoConnectOnce(n,i)});}catch(o){if(!this.isUnsupportedRuntimeAdapterError(o,"startAutoConnect"))throw o;await this.client.startAutoConnect(e);return}return}await this.client.startAutoConnect(e);}async isConnected(e){return this.connectionController.isConnected(e)}async disconnectNode(e){await this.connectionController.disconnectNode(e);}async disconnectDevice(e){return this.connectionController.disconnectDevice(e)}async setAutoConnectExcluded(e,t){await this.connectionController.setAutoConnectExcluded(e,t);}async disconnectPeer(e,t){await this.connectionController.disconnectPeer(e,t);}async forceDisconnectPeer(e){await this.connectionController.forceDisconnectPeer(e);}async getPeerHealth(e){return this.client.getPeerHealth(e)}async getConnectionStates(){return this.client.signaling.getConnectionStates()}onConnectionStateChange(e){let t=true,n=new Map,i=l=>{if(!t)return;let p=this.connectionStateSnapshotKey(l);n.get(l.connectionId)!==p&&(n.set(l.connectionId,p),e(l));},o=()=>{t&&this.getConnectionStates().then(l=>{l.forEach(p=>i(p));}).catch(()=>{});},s=l=>()=>{t=false,a(),l?.();},a=this.startManagedReconciliation(()=>o()),c=this.client.signaling.onConnectionStateChange(l=>i(l));return o(),typeof c=="function"?s(c):Promise.resolve(c).then(l=>s(typeof l=="function"?l:null))}getConnections(){return this.client.getConnections()}getApplicationReadyConnections(e={}){return this.client.getApplicationReadyConnections(e)}onConnection(e){return this.client.onConnection(e)}onDisconnection(e){return this.client.onDisconnection(e)}onMessage(e){return this.client.onMessage(e)}onConnectionEvent(e){let t=this.client.onConnection(i=>{let{activeTransport:o}=i.getTransportStatus();e({type:"connected",connectionId:i.id,localNodeId:i.localNodeId,remoteNodeId:i.remoteNodeId,transport:o});}),n=this.client.onDisconnection(i=>{let{activeTransport:o}=i.getTransportStatus();e({type:"disconnected",connectionId:i.id,localNodeId:i.localNodeId,remoteNodeId:i.remoteNodeId,transport:o});});return ()=>{t(),n();}}forceReconnectSnapshot(){this.client.forceReconnectSnapshot();}async connect(){await this.initialize(),await this.start();}disconnect(){this.stop();}destroy(){this.stopManagedReconciliation(),this.stop();let e=this.client;e&&typeof e.destroy=="function"&&e.destroy();}dispose(){this.destroy();}onAuthChange(e){return this.onIdentityChange(e)}async setAuth(e){return this.setAuthContext(e)}async signIn(){return this.signInWithPluto()}async getDevices(){return this.listDevices()}onDevices(e,t){return t?.status?this.watchDevicesWithStatus(e):this.watchDevices(e)}async getInvite(){return this.getTicket()}async connectTo(e){return this.connectPeer(e)}async waitFor(e,t){return this.waitForConnectedPeer(e,t)}async openStream(e,t){if(t?.direction==="send")return this.openPeerUni(e,t);if(this.isTransportOnlyStreamChannel(t?.channelId))try{return await this.openPeerBiTransportOnly(e,t)}catch(n){let i=n instanceof Error?n.message:String(n);if(!/application crypto/i.test(i))throw n;c$1("[RuntimeClient] transport-only channel requires encrypted peer stream; falling back",{peerId:e,channelId:t?.channelId??null});}return this.openPeerBi(e,t)}async openChannelStream(e,t,n){return this.openStream(t,{...n,channelId:e})}onStream(e){return this.onIncomingStream(e)}onChannelStream(e,t){return this.onIncomingChannelStream(e,t)}onRoomChange(e,t){return this.watchRoom(e,t)}createSession(e){return new Tt(this,e)}};Q.NATIVE_START_RETRY_WINDOW_MS=w.managedSession.nativeStartRetryWindowMs,Q.NATIVE_START_RETRY_MIN_DELAY_MS=w.managedSession.nativeStartRetryMinDelayMs,Q.NATIVE_START_RETRY_MAX_DELAY_MS=w.managedSession.nativeStartRetryMaxDelayMs,Q.MANAGED_RECONCILIATION_INTERVAL_MS=w.managedSession.reconciliationIntervalMs,Q.DEVICE_STATUS_REFRESH_DEBOUNCE_MS=w.managedSession.deviceStatusRefreshDebounceMs,Q.MANAGED_USER_DEVICE_SCOPE="user-device",Q.MANAGED_FRIEND_SCOPE="friend";var oi=Q;function zs(r,e){let t=new oi(r,e),n=r.spaceKey??r.space,i=(r.discoveryMode===void 0||r.discoveryMode==="space")&&typeof r.apiKey=="string"&&r.apiKey.trim().length>0&&typeof n=="string"&&n.trim().length>0,o={runtime:t,async setAuthContext(s){await t.setAuthContext(s);},async syncPlutoAuth(s){if(i)return;let a=G(),c=a.getCurrentUser(),p=(typeof s?.userId=="string"?s.userId.trim():"")||c?.uid||null;if(!p){await o.setAuthContext(null);return}let u=await a.getIdToken({forceRefresh:s?.forceRefresh??false}).catch(()=>null),g=a.getCurrentUser()?.refreshToken??null,y=a.getCurrentUser()?.stsTokenManager?.expirationTime??null;await o.setAuthContext({userId:p,token:u,refreshToken:g,tokenProvider:async m=>a.getIdToken({forceRefresh:m??true}),expiresAtMs:y});},bindPlutoAuthHost(){let s=G();return o.syncPlutoAuth({userId:s.getCurrentUser()?.uid??null,forceRefresh:false}),s.onIdTokenChanged(a=>{o.syncPlutoAuth({userId:a?.uid??null,forceRefresh:false});})},signInWithPluto:()=>t.signInWithPluto(),signOut:()=>t.signOut(),stopManagedSession:()=>t.stopManagedSession(),startManagedSession:s=>t.startManagedSession(s),onAuthChange:s=>t.onIdentityChange(s),getManagedNodeId:s=>t.getManagedNodeId(s),getRuntimeStatus:()=>t.getRuntimeStatus(),listDevicesWithStatus:()=>t.listDevicesWithStatus(),watchDevicesWithStatus:s=>t.watchDevicesWithStatus(s),connectDevice:(s,a)=>t.connectDevice(s,a),setAutoConnectExcluded:(s,a)=>t.setAutoConnectExcluded(s,a)};return Object.defineProperty(o,"identity",{get:()=>t.identity,enumerable:true}),o}function _f(r){let e=t(r);return zs(e,new a$1(e))}function wf(r,e){let t$1=t(r);return zs(t$1,new h({...t$1,bridge:e}))}export{wf as A,Oc as a,_t as b,Bo as c,Wo as d,Oo as e,Ho as f,Tt as g,At as h,Zs as i,Je as j,oe as k,ce as l,Si as m,bi as n,Xe as o,Ze as p,Ii as q,oa as r,ra as s,sa as t,Zc as u,el as v,Ri as w,Pi as x,oi as y,_f as z};