openrtc 1.0.10 → 1.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{DelegatingRuntimeAdapter-lFDUNBy9.d.ts → DelegatingRuntimeAdapter-CemTo26O.d.ts} +4 -1
- package/dist/{assembly-C2G0P2L5.d.ts → assembly-BT4wKsfZ.d.ts} +2 -2
- package/dist/auth/index.js +1 -1
- package/dist/auth/internal.js +1 -1
- package/dist/{chunk-N6UBUNGC.js → chunk-75KFQDH4.js} +1 -1
- package/dist/chunk-DYMZAX7Q.js +2 -0
- package/dist/chunk-HVN5T6U4.js +3 -0
- package/dist/chunk-MU5FL5WW.js +1 -0
- package/dist/{chunk-GFIH6LQG.js → chunk-NXQJYXUK.js} +1 -1
- package/dist/chunk-YFNRKQEA.js +2 -0
- package/dist/chunk-YJ4XMLDL.js +2 -0
- package/dist/{chunk-SJ5BFL6W.js → chunk-ZZIIBIEC.js} +1 -1
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/native.d.ts +5 -5
- package/dist/native.js +1 -1
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/runtime/WasmRuntimeAdapter.d.ts +2 -2
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +2 -2
- package/dist/runtime/index.d.ts +20 -8
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/tauri.d.ts +3 -3
- package/dist/runtime/tauri.js +1 -1
- package/dist/{spaceTokens-3sbs1mUF.d.ts → spaceTokens-BdM1QhjV.d.ts} +3 -3
- package/dist/{tauri-WEvOC_Z6.d.ts → tauri-AzvFjyR0.d.ts} +2 -2
- package/dist/transport/index.d.ts +2 -2
- package/dist/{types-N9s66nF8.d.ts → types-CX2negKR.d.ts} +1 -1
- package/dist/{types-ZDsZknDI.d.ts → types-CYgBbeVF.d.ts} +28 -1
- package/package.json +3 -2
- package/dist/chunk-56WJZUHE.js +0 -3
- package/dist/chunk-DI5IPRPM.js +0 -2
- package/dist/chunk-HVTYSEU7.js +0 -2
- package/dist/chunk-MNI6JGR2.js +0 -1
- package/dist/chunk-YTUWXCRO.js +0 -1
package/dist/{DelegatingRuntimeAdapter-lFDUNBy9.d.ts → DelegatingRuntimeAdapter-CemTo26O.d.ts}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { D as DiscoveryMode, A as AuthMode, d as SignalingMode, E as ExplicitFileDataSendParams, I as ISignalingBackend,
|
|
1
|
+
import { D as DiscoveryMode, A as AuthMode, d as SignalingMode, e as ClientOptions, E as ExplicitFileDataSendParams, I as ISignalingBackend, f as RuntimeIdentity, g as Device, h as DeviceStatusSnapshot, P as PeerSessionSnapshot, R as ResolvedPeerIdentity, M as ManagedConnectionRecord, i as SignalingEnvelope, j as DeviceEvent, k as SignalingSession, l as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, m as BackendPeerUniStream, n as NativeConnectParams, o as NativeConnectResult, p as BackendConnectionState } from './types-CYgBbeVF.js';
|
|
2
2
|
import { A as AuthContext } from './IEngineBridge-C7OT2CRv.js';
|
|
3
3
|
import { R as RuntimeCapabilities } from './capabilities-C4Dqs_pB.js';
|
|
4
4
|
|
|
@@ -10,6 +10,9 @@ interface WasmBridgeOptions {
|
|
|
10
10
|
authMode?: AuthMode;
|
|
11
11
|
signalingMode?: SignalingMode;
|
|
12
12
|
projectId?: string;
|
|
13
|
+
coordinationGateway?: ClientOptions['coordinationGateway'];
|
|
14
|
+
/** Internal host hint used by the provider-neutral gateway projection. */
|
|
15
|
+
coordinationPlatformType?: 'web' | 'desktop' | 'mobile';
|
|
13
16
|
storagePrefix?: string;
|
|
14
17
|
deviceIdPersistence?: 'persistent' | 'ephemeral';
|
|
15
18
|
endpointIdPersistence?: 'persistent' | 'ephemeral';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { A as AuthContext } from './IEngineBridge-C7OT2CRv.js';
|
|
2
|
-
import { G as GrantScope, I as ISignalingBackend, b as ConnectDeviceHooks, c as ConnectDeviceOptions, C as ConnectDeviceResult, M as ManagedConnectionRecord, P as PeerSessionSnapshot, R as ResolvedPeerIdentity, X as AppLimits,
|
|
3
|
-
import { h as RuntimePeerState, s as RuntimeConnectionStateSnapshot, j as RuntimePeerReadinessSnapshot, i as RuntimePeerConnectOptions, C as Connection, n as RuntimeIncomingStream, R as RuntimeClientOptions, H as RuntimeAuthIdentity, f as RuntimeLocalDeviceInfo, g as RuntimeLocalDeviceProfile, c as RuntimeDevice, a as RuntimeManagedSessionOptions, b as RuntimeManagedSession, d as RuntimeDeviceStatusSnapshot, e as RuntimeDeviceConnectOptions, X as RuntimeSession, q as RuntimeJoinRoomOptions, r as RuntimeRoomMember, K as RuntimeConnectionTarget, o as RuntimeScopedChannelOptions, p as RuntimeScopedLogicalChannel, m as RuntimePeerStreamOptions, v as RuntimeRawConnection, l as RuntimeChannelDescriptor, V as RuntimePresenceLoopOptions, k as RuntimePeerHealth, t as RuntimeApplicationPayloadReadinessOptions, u as RuntimeConnectionEvent } from './types-
|
|
2
|
+
import { G as GrantScope, I as ISignalingBackend, b as ConnectDeviceHooks, c as ConnectDeviceOptions, C as ConnectDeviceResult, M as ManagedConnectionRecord, P as PeerSessionSnapshot, R as ResolvedPeerIdentity, X as AppLimits, n as NativeConnectParams, o as NativeConnectResult, E as ExplicitFileDataSendParams } from './types-CYgBbeVF.js';
|
|
3
|
+
import { h as RuntimePeerState, s as RuntimeConnectionStateSnapshot, j as RuntimePeerReadinessSnapshot, i as RuntimePeerConnectOptions, C as Connection, n as RuntimeIncomingStream, R as RuntimeClientOptions, H as RuntimeAuthIdentity, f as RuntimeLocalDeviceInfo, g as RuntimeLocalDeviceProfile, c as RuntimeDevice, a as RuntimeManagedSessionOptions, b as RuntimeManagedSession, d as RuntimeDeviceStatusSnapshot, e as RuntimeDeviceConnectOptions, X as RuntimeSession, q as RuntimeJoinRoomOptions, r as RuntimeRoomMember, K as RuntimeConnectionTarget, o as RuntimeScopedChannelOptions, p as RuntimeScopedLogicalChannel, m as RuntimePeerStreamOptions, v as RuntimeRawConnection, l as RuntimeChannelDescriptor, V as RuntimePresenceLoopOptions, k as RuntimePeerHealth, t as RuntimeApplicationPayloadReadinessOptions, u as RuntimeConnectionEvent } from './types-CX2negKR.js';
|
|
4
4
|
import { R as RuntimeCapabilities, a as RuntimeCapabilityProfile } from './capabilities-C4Dqs_pB.js';
|
|
5
5
|
|
|
6
6
|
/**
|
package/dist/auth/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{H as authHost,G as getAuthHost,F as registerDesktopAuthRelay}from'../chunk-
|
|
1
|
+
export{H as authHost,G as getAuthHost,F as registerDesktopAuthRelay}from'../chunk-YFNRKQEA.js';import'../chunk-C7YN5MSV.js';
|
package/dist/auth/internal.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{F as registerDesktopAuthRelay}from'../chunk-
|
|
1
|
+
export{F as registerDesktopAuthRelay}from'../chunk-YFNRKQEA.js';import'../chunk-C7YN5MSV.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {g,h}from'./chunk-
|
|
1
|
+
import {g,h}from'./chunk-YJ4XMLDL.js';function c(){return g()}var i=class extends h{constructor(r){super({...r,bridge:g(),allowWasmFallback:r.allowWasmFallback??false});}};export{c as a,i as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {h,b as b$1}from'./chunk-QT2ASNI3.js';import {v as v$1,b,d,c,G,e,u,a,w,t,E as E$1,x as x$1}from'./chunk-YFNRKQEA.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';import {getFirestore,connectFirestoreEmulator,Timestamp,getDoc,serverTimestamp as serverTimestamp$1,setDoc,updateDoc,deleteDoc,collection,doc,getDocs,query,where,limit,onSnapshot,getDocFromServer}from'firebase/firestore';import {getAuth}from'firebase/auth';import {getDatabase,connectDatabaseEmulator,onValue,ref,onDisconnect,set,onChildAdded,onChildChanged,onChildRemoved,serverTimestamp,get}from'firebase/database';import {httpsCallable,getFunctions}from'firebase/functions';import*as Ce from'tweetnacl';function Zt(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function Ee(r,e,t){if(Zt()){if(typeof t>"u"){console[r](e);return}console[r](e,t);}}function ue(r,e){Ee("debug",r,e);}function R(r,e){Ee("info",r,e);}function xi(r,e){Ee("log",r,e);}var B=new Uint8Array([79,82,84,67,69,49]),pe=2,K=8,X=24,ot=32,en=3,tn=16*1024*1024,nn=4096;function rn(r,e){if(r.byteLength<e.byteLength)return false;let t=0;for(let n=0;n<e.byteLength;n+=1)t|=r[n]^e[n];return t===0}function sn(r){let e=new Uint8Array(r),t=globalThis.crypto;if(!t||typeof t.getRandomValues!="function")throw new Error("[OpenRTC] application payload crypto requires crypto.getRandomValues");return t.getRandomValues(e),e}function on(r,e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return `${r}:${t}`}function at(r){if(!rn(r,B))return null;let e=r[B.byteLength];return e===pe?e:null}function an(r){return at(r)===pe&&r.byteLength>B.byteLength+1+K+X}function Fi(r,e={}){if(!(r instanceof Uint8Array)||r.byteLength!==ot)throw new Error(`[OpenRTC] application payload crypto key must be ${ot} bytes`);let t=new Uint8Array(r),n=e.requireEncrypted??true,i=e.randomBytes??sn,s=e.replayProtection??true,o=0,a=new Set,c=[];return {requireEncrypted:n,protectPayload(l,d){let u=i(X);if(!(u instanceof Uint8Array)||u.byteLength!==X)throw new Error(`[OpenRTC] application payload crypto nonce must be ${X} bytes`);let h=new Uint8Array(1+d.byteLength);h[0]=l,h.set(d,1);let p=xchacha20poly1305(t,u).encrypt(h);if(!s)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let f=new Uint8Array(B.byteLength+1+K+u.byteLength+p.byteLength),g=0;f.set(B,g),g+=B.byteLength,f[g]=pe,g+=1;let b=o;return o+=1,new DataView(f.buffer,f.byteOffset+g,K).setBigUint64(0,BigInt(b),false),g+=K,f.set(u,g),g+=u.byteLength,f.set(p,g),f},openPayload(l,d){if(!an(d))return n?null:d;if(at(d)!==pe)return null;let h=B.byteLength+1,p=Number(new DataView(d.buffer,d.byteOffset+h,K).getBigUint64(0,false));if(!Number.isFinite(p))return null;let f=h+K,g=f+X,b=d.slice(f,g),y=s?on(p,b):null;if(y&&a.has(y))return null;let w=d.slice(g),I;try{I=xchacha20poly1305(t,b).decrypt(w);}catch{return null}if(I.byteLength<1||I[0]!==l)return null;if(y)for(a.add(y),c.push(y);c.length>nn;){let D=c.shift();D&&a.delete(D);}return I.slice(1)}}}function cn(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 ct(r,e={}){let t=e.typeId??en,n=e.maxFrameBytes??tn;if(!Number.isInteger(t)||t<0||t>255)throw new Error("[OpenRTC] raw application crypto stream typeId must be an integer from 0 to 255");if(!Number.isInteger(n)||n<=0)throw new Error("[OpenRTC] raw application crypto maxFrameBytes must be a positive integer");let i=d=>r.protectPayload(t,d),s=d=>r.openPayload(t,d),o=()=>new TransformStream({transform(d,u){u.enqueue(cn(i(new Uint8Array(d))));}}),a=()=>{let d=new Uint8Array(0);return new TransformStream({transform(u,h){for(d=w([d,new Uint8Array(u)]);d.byteLength>=4;){let p=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,false);if(p===0||p>n)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(d.byteLength<4+p)return;let f=d.slice(4,4+p);d=d.slice(4+p);let g=s(f);if(!g)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");h.enqueue(g);}},flush(){if(d.byteLength!==0)throw new Error("[OpenRTC] encrypted raw stream ended mid-frame")}})},c=d=>d.pipeThrough(a()),l=d=>{let u=o();return u.readable.pipeTo(d).catch(()=>{}),u.writable};return {typeId:t,protectFrame:i,openFrame:s,createOutboundTransform:o,createInboundTransform:a,wrapReadable:c,wrapWritable:l,wrapBiStream(d){return {...d,send:l(d.send),recv:c(d.recv)}}}}var dn="[OpenRTC][teardown-trace]";function ln(){try{let r=globalThis;if(r.OPENRTC_TEARDOWN_TRACE===!0||r.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function dt(r,e={}){console.info(dn,{kind:r,ts:new Date().toISOString(),...e}),ln()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:r,stack:new Error(`teardown: ${r}`).stack});}var Q={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,reconciliationIntervalMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:8e3,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,defaultBoundedCommandTimeoutMs:15e3,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function Wi(){return Q}var un={adapter:"browser-wasm",signaling:{firestore:true,nativeIpc:false,rtdbPresence:true},transport:{irohQuic:true,irohLan:false,webRtcUpgrade:true,webRtcLan:true,nativeWebRtc:false,moq:true,ble:false,wasm:true},nativeProtocols:{productAlpn:false,irohDocs:false,irohBlobs:false,irohGossip:false},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:false,explicitFileData:true,history:false},fallback:{wasm:false}},pn={adapter:"native-ipc",signaling:{firestore:true,nativeIpc:true,rtdbPresence:true},transport:{irohQuic:true,irohLan:false,webRtcUpgrade:false,webRtcLan:false,nativeWebRtc:false,moq:false,ble:false,wasm:false},nativeProtocols:{productAlpn:true,irohDocs:true,irohBlobs:true,irohGossip:true},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:true,explicitFileData:true,history:true},fallback:{wasm:false}};function lt(r){return {adapter:r.adapter,signaling:{...r.signaling},transport:{...r.transport},nativeProtocols:{...r.nativeProtocols},lifecycle:{...r.lifecycle},transfers:{...r.transfers},fallback:{...r.fallback}}}function he(r=globalThis){let e=lt(un),t=typeof r?.RTCPeerConnection=="function";return e.transport.webRtcUpgrade=t,e.transport.webRtcLan=t,e}function U(r){return r?.compiled===true&&r.enabled===true}function Hi(r,e=false){let t=lt(pn),n=r?.transport;return n&&(t.transport.irohQuic=U(n.irohQuic),t.transport.irohLan=U(n.irohLan),t.transport.webRtcUpgrade=U(n.webRtc),t.transport.nativeWebRtc=U(n.webRtc),t.transport.webRtcLan=U(n.webRtcLan),t.transport.moq=U(n.moq),t.transport.ble=U(n.ble)),t.transport.wasm=false,t.fallback.wasm=e,t}function Ki(r){return {environment:r.adapter==="native-ipc"||r.adapter==="tauri-ipc"?"native":r.adapter==="browser-wasm"?"web":"unknown",transports:{quic:r.transport.irohQuic,irohRelay:r.transport.irohQuic,irohLan:r.transport.irohLan,webRtc:r.transport.webRtcUpgrade||r.transport.nativeWebRtc,webRtcLan:r.transport.webRtcLan,moq:r.transport.moq,ble:r.transport.ble},lifecycle:{...r.lifecycle},storage:{localFileSystem:r.transfers.explicitFilePath,transferHistory:r.transfers.history},nativeProtocols:{...r.nativeProtocols}}}function M(r){if(!r)return null;let e=2166136261;for(let t=0;t<r.length;t+=1)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var gn=1e4,mn=5e3,A=class{constructor(e,t,n,i,s){this.app=e;this.operationId=t;this.leaseId=n;this.route=i;this.onLeaseLost=s;this.timer=null;this.stopped=true;this.pending=null;}async start(){return !this.stopped&&this.pending?this.pending:(this.stopped=false,this.app?.options?.projectId?(this.pending=this.renew(),this.pending):(this.pending=Promise.resolve(),this.pending))}stop(){this.stopped=true,this.pending=null,this.timer&&(clearTimeout(this.timer),this.timer=null);}async renew(){try{let t=await httpsCallable(getFunctions(this.app),"renewUsageLease")({operationId:this.operationId,leaseId:this.leaseId,route:this.route});if(!t?.data||!Number.isFinite(t.data.validUntilMs)){if(globalThis.process?.env?.OPENRTC_DETERMINISTIC_TESTS==="1"){this.pending=Promise.resolve();return}throw new Error("renewUsageLease returned an invalid response")}if(this.stopped)return;let n=Math.max(mn,t.data.validUntilMs-Date.now()-gn);this.timer=setTimeout(()=>{let i=this.renew();this.pending=i,i.catch(()=>{});},n);}catch(e){throw this.stop(),this.onLeaseLost?.(e),e}}};var Pn=9e4,Dn=3e4;function Ne(r=Date.now()){return r+Pn}function P(r,e=Date.now()){return !r||r.online!==true?false:typeof r.leaseExpiresAt!="number"?true:r.leaseExpiresAt>e}function Tn(r,e){switch(r.kind){case "user-scoped":return `presence/${r.appTag}/users/${r.userId}/devices/${e}`;case "space":return `presence/spaces/${r.namespaceId}/devices/${e}`}}function _e(r,e,t){return `${Tn(r,e)}/instances/${t}`}function pt(r){switch(r.kind){case "user-scoped":return `presence/${r.appTag}/users/${r.userId}/devices`;case "space":return `presence/spaces/${r.namespaceId}/devices`}}function ht(r,e,t){return `presence/${r}/rooms/${e}/members/${t}`}function Cn(r,e){return `presence/${r}/rooms/${e}/members`}function Z(r){let e={},t=(n,i)=>{if(typeof i!="string")return;let s=i.trim();s&&(e[n]=s);};if(t("ticket",r?.ticket),t("nodeId",r?.nodeId),t("deviceName",r?.deviceName),t("platformType",r?.platformType),t("metadata",r?.metadata),Array.isArray(r?.excludedPeers)){let n=r.excludedPeers.map(i=>typeof i=="string"?i.trim().toLowerCase():"").filter(Boolean).filter((i,s,o)=>o.indexOf(i)===s).sort();n.length>0&&(e.excludedPeers=n);}return e}function En(r,e){if(!r||typeof r!="object")return null;let t=r,n=Z({ticket:t.ticket,nodeId:t.nodeId,deviceName:t.deviceName,platformType:t.platformType,metadata:t.metadata,excludedPeers:t.excludedPeers});return {online:P({online:t.online===true,leaseExpiresAt:typeof t.leaseExpiresAt=="number"?t.leaseExpiresAt:void 0},e),ticketVersion:typeof t.ticketVersion=="number"?t.ticketVersion:0,leaseExpiresAt:typeof t.leaseExpiresAt=="number"?t.leaseExpiresAt:void 0,...n}}function ft(r,e=Date.now()){if(!r||typeof r!="object")return null;let t=r.instances;if(!t||typeof t!="object")return null;let n=Object.entries(t).map(([i,s])=>({instanceId:i,state:En(s,e)})).filter(i=>!!i.state).sort((i,s)=>s.instanceId.localeCompare(i.instanceId));return n.length===0?null:n.find(i=>i.state.online)?.state??n[0].state}function An(){let r=Date.now().toString().padStart(13,"0"),e=globalThis.crypto?.randomUUID?.().replace(/-/g,"")??Math.random().toString(36).slice(2);return `${r}-${e}`}function Me(r,e){return {online:true,lastSeenAt:serverTimestamp(),ticketVersion:r,leaseExpiresAt:Ne(),...Z(e)}}function xe(r,e){return {online:false,lastSeenAt:serverTimestamp(),ticketVersion:r,leaseExpiresAt:Date.now(),...Z(e)}}function fe(r){return {...r}}function Le(r,e){return {...r,lastSeenAt:serverTimestamp(),leaseExpiresAt:e?Ne():Date.now()}}var ge=class{constructor(e,t=An()){this.desiredOnlineNodes=new Map;this.connected=null;this.connectedUnsubscribe=null;this.leaseRefreshTimer=null;this.activeSubscriptions=new Set;this.app=e,this.auth=getAuth(e),this.db=getDatabase(e);let n=t.trim().replace(/[^a-zA-Z0-9_-]/g,"-");if(!n)throw new Error("runtimeInstanceId is required");this.runtimeInstanceId=n,this.economicPresenceLease=new A(this.app,"presence.lease",this.runtimeInstanceId,"rtdb-presence",i=>{this.leaseRefreshTimer&&(clearInterval(this.leaseRefreshTimer),this.leaseRefreshTimer=null),this.connectedUnsubscribe?.(),this.connectedUnsubscribe=null;for(let s of this.activeSubscriptions)s();this.activeSubscriptions.clear(),this.desiredOnlineNodes.clear(),console.warn("[RtdbPresence] economic usage lease was lost; presence refresh stopped",{message:i instanceof Error?i.message:String(i)});});try{let i=globalThis?.__OPENRTC_RTDB_EMULATOR_HOST__,s=typeof i=="string"?i.trim():"";if(s){let[o,a]=s.split(":"),c=(o??"").trim()||"127.0.0.1",l=Number(a??9001);try{connectDatabaseEmulator(this.db,c,l);}catch{}}else {let o=import.meta?.env;if(!!o?.DEV&&String(o?.VITE_USE_EMULATORS)==="true"){let c=String(o?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",l=Number(o?.VITE_OPENRTC_RTDB_EMULATOR_PORT??9001);try{connectDatabaseEmulator(this.db,c,l);}catch{}}}}catch{}}ensureReconnectWatch(){this.connectedUnsubscribe||(this.connectedUnsubscribe=onValue(ref(this.db,".info/connected"),e=>{let t=e.val()===true,n=t&&this.connected===false;if(this.connected=t,!!n)for(let i of this.desiredOnlineNodes.keys())this.publishDesiredOnline(i).catch(s=>{console.warn("[RtdbPresence] failed to republish presence after reconnect:",{path:i,error:s});});}));}async publishDesiredOnline(e){let t=this.desiredOnlineNodes.get(e);if(!t)return;t.online=Le(t.online,true),t.offline=Le(t.offline,false);let n=ref(this.db,e);await onDisconnect(n).set(t.offline),await set(n,t.online);}ensureLeaseRefresh(){this.leaseRefreshTimer||(this.leaseRefreshTimer=setInterval(()=>{for(let e of this.desiredOnlineNodes.keys())this.publishDesiredOnline(e).catch(t=>{console.warn("[RtdbPresence] failed to refresh RTDB presence lease:",{path:e,error:t});});},Dn));}stopLeaseRefreshIfIdle(){this.desiredOnlineNodes.size>0||!this.leaseRefreshTimer||(clearInterval(this.leaseRefreshTimer),this.leaseRefreshTimer=null,this.economicPresenceLease.stop());}async registerOnlineNode(e,t,n){this.auth.currentUser&&await this.economicPresenceLease.start(),this.ensureReconnectWatch(),this.desiredOnlineNodes.set(e,{online:t,offline:n}),this.ensureLeaseRefresh(),await this.publishDesiredOnline(e);}async markNodeOffline(e,t){this.desiredOnlineNodes.delete(e),this.stopLeaseRefreshIfIdle();let n=ref(this.db,e);await onDisconnect(n).cancel(),await set(n,Le(t,false));}subscribeIncremental(e,t,n,i){let s=ref(this.db,e),o={},a=()=>n({...o}),c=p=>{let f=typeof p.key=="string"?p.key:"";if(!f)return;let g=t(f,p.val());g?o[f]=g:delete o[f],a();},l=p=>{console.warn(`[RtdbPresence] ${i} presence subscription error:`,p);},d=[onChildAdded(s,c,l),onChildChanged(s,c,l),onChildRemoved(s,p=>{let f=typeof p.key=="string"?p.key:"";f&&(delete o[f],a());},l)],u=true,h=()=>{if(u){u=false;for(let p of d)p();this.activeSubscriptions.delete(h);}};return this.activeSubscriptions.add(h),h}async registerDevice(e,t,n=0,i){let s=_e(e,t,this.runtimeInstanceId);try{await this.registerOnlineNode(s,fe(Me(n,i)),fe(xe(n,i))),R("[RtdbPresence] registered device presence",{path:s,scopeKind:e.kind,deviceId:t,ticketVersion:n,hasTicket:typeof i?.ticket=="string"&&i.ticket.length>0,hasNodeId:typeof i?.nodeId=="string"&&i.nodeId.length>0});}catch(o){let a=o;throw console.warn("[RtdbPresence] registerDevice failed",{path:s,scopeKind:e.kind,deviceId:t,ticketVersion:n,code:typeof a?.code=="string"?a.code:null,message:typeof a?.message=="string"?a.message:String(o)}),o}}async bumpTicketVersion(e,t,n,i){let s=_e(e,t,this.runtimeInstanceId),o=ref(this.db,s),a=this.desiredOnlineNodes.get(s),c=Z(i);if(a){let l=a.online;c=Z({ticket:i?.ticket??l.ticket,nodeId:i?.nodeId??l.nodeId,deviceName:i?.deviceName??l.deviceName,platformType:i?.platformType??l.platformType,metadata:i?.metadata??l.metadata,excludedPeers:i?.excludedPeers??l.excludedPeers}),a.online=fe(Me(n,c)),a.offline=fe(xe(n,c));}await onDisconnect(o).set(xe(n,c)),await set(o,Me(n,c));}async markOffline(e,t,n=0){await this.markNodeOffline(_e(e,t,this.runtimeInstanceId),{online:false,lastSeenAt:serverTimestamp(),ticketVersion:n,leaseExpiresAt:Date.now()});}async registerRoomMember(e,t,n){await this.registerOnlineNode(ht(e,t,n),{online:true,lastSeenAt:serverTimestamp(),leaseExpiresAt:Ne()},{online:false,lastSeenAt:serverTimestamp(),leaseExpiresAt:Date.now()});}async markRoomMemberOffline(e,t,n){await this.markNodeOffline(ht(e,t,n),{online:false,lastSeenAt:serverTimestamp(),leaseExpiresAt:Date.now()});}onRoomPresenceChange(e,t,n){return this.subscribeIncremental(Cn(e,t),(i,s)=>{if(!s||typeof s!="object")return null;let o=s;return {online:P({online:o.online===true,leaseExpiresAt:typeof o.leaseExpiresAt=="number"?o.leaseExpiresAt:void 0}),leaseExpiresAt:typeof o.leaseExpiresAt=="number"?o.leaseExpiresAt:void 0}},n,"room")}onPresenceChange(e,t){return this.subscribeIncremental(pt(e),(n,i)=>ft(i),t,"device")}async readPresenceMap(e){let n=(await get(ref(this.db,pt(e)))).val();if(!n||typeof n!="object")return {};let i={};for(let[s,o]of Object.entries(n)){if(!o||typeof o!="object")continue;let a=ft(o);a&&(i[s]=a);}return i}};var Ue=100;function St(r,e){return !r||r.kind!==e.kind?false:r.kind==="user-scoped"&&e.kind==="user-scoped"?r.appTag===e.appTag&&r.userId===e.userId:r.kind==="space"&&e.kind==="space"&&r.namespaceId===e.namespaceId}function Ln(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,n=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(n));let i=globalThis.Buffer;if(i)return JSON.parse(i.from(n,"base64").toString("utf8"))}catch{return null}return null}function j(r){let e=typeof r=="string"?r.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),n=t>=0?e.slice(0,t):e,i=t>=0?e.slice(t+1):null,s=i?Ln(i):null,o=s&&typeof s.t=="string"&&s.t.trim().length>0?s.t.trim():null,a=s&&typeof s.s=="string"&&s.s.trim().length>0?s.s.trim():null,c=s&&typeof s.m=="number"&&Number.isFinite(s.m)?s.m:null;return {present:true,irohFingerprint:M(n),tokenFingerprint:M(o),tokenSuffixFingerprint:M(i),scope:a,maxConnections:c}}var q=class q{constructor(e){this.hooks=e;this.deviceListeners=new Map;this.devicesById=new Map;this.staleDeviceOfflineWrites=new Set;this.nextListenerIdSeed={value:1};this.activeDeviceScopeKey=null;this.activeDeviceUnsubscribe=null;this.deviceWatchSetup=null;this.deviceWatchGeneration=0;this.hasDeviceRosterSnapshot=false;this.durableRosterRead=null;this.freshnessRecheckTimer=null;this.rtdbPresence=null;this.rtdbScope=null;this.rtdbPresenceMap={};this.rtdbUnsubscribe=null;this.hasRtdbPresenceSnapshot=false;this.rtdbPresenceRead=null;this.knownTicketVersions=new Map;this.autoConnectRefreshes=new Map;let t=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`discovery-${Date.now()}-${Math.random().toString(16).slice(2)}`;this.economicDiscoveryLease=new A(e.firestore.app,"discovery.roster.lease",t,"firestore-device-roster",n=>{console.warn("[BrowserDeviceDiscovery] economic usage lease was lost; roster watch stopped",{message:n instanceof Error?n.message:String(n)}),this.stopDeviceWatch({clearDevices:false});});}get options(){return this.hooks.options}async ensureEconomicUsageLease(){this.options.auth.currentUser&&await this.economicDiscoveryLease.start();}stopEconomicUsageLease(){this.economicDiscoveryLease.stop();}setRtdbPresence(e,t){let n=this.rtdbPresence===e,i=St(this.rtdbScope,t);if(n&&i)return;let s=this.deviceListeners.size>0;R("[BrowserDeviceDiscovery][rtdb] adapter or scope changed",{sameAdapter:n,sameScope:i,hasActiveListeners:s,scopeKind:t.kind}),this.rtdbUnsubscribe&&(this.rtdbUnsubscribe(),this.rtdbUnsubscribe=null),this.rtdbPresence=e,this.rtdbScope=t,this.rtdbPresenceMap={},this.hasRtdbPresenceSnapshot=false,this.rtdbPresenceRead=null,this.knownTicketVersions.clear(),s&&this.handleScopeChange().catch(o=>{console.warn("[BrowserDeviceDiscovery] failed to restart device watch after RTDB scope change:",o);});}stopRtdbPresence(){this.rtdbUnsubscribe?.(),this.rtdbUnsubscribe=null,this.rtdbPresence=null,this.rtdbScope=null,this.rtdbPresenceMap={},this.hasRtdbPresenceSnapshot=false,this.rtdbPresenceRead=null,this.knownTicketVersions.clear();}stopAuthScopedActivity(){this.stopRtdbPresence(),this.stopDeviceWatch({clearDevices:true});}async searchDevices(e){let n=(this.rtdbPresence&&this.rtdbScope?await this.readLiveRtdbDeviceSnapshot():await this.readCurrentDeviceSnapshot()).filter(i=>i.online);return e?this.filterDevices(n,e):n}async listDevices(e){let t=await this.readCurrentDeviceSnapshot();return e?this.filterDevices(t,e):t}async subscribeDevices(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return new ReadableStream({start(s){s.close();}});let t=null,n=null,i=new A(this.hooks.firestore.app,"discovery.roster.lease",typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`stream-${Date.now()}-${Math.random().toString(16).slice(2)}`,"firestore-device-stream",s=>{t?.(),t=null;try{n?.error(s);}catch{}n=null;});return this.options.auth.currentUser&&await i.start(),new ReadableStream({start:s=>{n=s,t=onSnapshot(query(e,limit(Ue)),o=>{let a=Date.now(),c=[];for(let l of o.docChanges()){let d=this.toDevice(l.doc,a);if(l.type==="removed"){c.push({type:"removed",deviceId:l.doc.id});continue}if(!d){c.push({type:"removed",deviceId:l.doc.id});continue}c.push({type:l.type==="added"?"added":"modified",device:d});}c.length>0&&s.enqueue(c);},o=>{console.warn("[BrowserDeviceDiscovery] subscribeDevices snapshot error:",{message:o?.message,code:o?.code});try{s.close();}catch{}});},cancel:()=>{t?.(),t=null,n=null,i.stop();}})}onDevicesChange(e,t){let n=this.nextListenerIdSeed.value++;return this.deviceListeners.set(n,{callback:e,excludeNodeId:t}),this.emitDevicesToListener(n),this.ensureDeviceWatch(),()=>{this.deviceListeners.delete(n),this.deviceListeners.size===0&&this.stopDeviceWatch({clearDevices:true});}}async handleScopeChange(){let e=this.deviceListeners.size>0;this.stopDeviceWatch({clearDevices:true}),e&&await this.ensureDeviceWatch();}async cleanupStaleDevices(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return;this.options.auth.currentUser&&await this.economicDiscoveryLease.start();let t=Date.now(),n=!!(this.rtdbPresence&&this.rtdbScope),i=await getDocs(query(e,where("online","==",false),where("expiresAt","<",t),limit(100)));if(await Promise.allSettled(i.docs.map(async c=>{let l=c.data(),d=typeof l.deviceId=="string"&&l.deviceId.trim()?l.deviceId.trim():c.id,u=n&&this.hasRtdbPresenceSnapshot&&P(this.rtdbPresenceMap[d]),h=n&&!this.hasRtdbPresenceSnapshot;l.online===false&&this.isDeviceExpired(l,t)&&!u&&!h&&await deleteDoc(c.ref);})),n)return;let s=this.rtdbPresence&&this.rtdbScope?await this.rtdbPresence.readPresenceMap(this.rtdbScope).catch(()=>this.rtdbPresenceMap):this.rtdbPresenceMap,o=await getDocs(query(e,where("online","==",true),limit(100))),a=new Map;for(let c of o.docs)a.set(c.ref.path,c);await Promise.allSettled([...a.values()].map(async c=>{let l=c.data();this.isDeviceExpired(l,t);let u=l.online===true,h=this.toMillis(l.updatedAt)??this.toMillis(l.lastSeenAt)??0,p=this.rtdbPresence&&this.rtdbScope?3e4:3e5;if(!(!u||!h||h+p>t)){if(this.rtdbPresence&&this.rtdbScope){let f=typeof l.deviceId=="string"&&l.deviceId.trim()?l.deviceId.trim():c.id;if(P(s[f]))return}await updateDoc(c.ref,{online:false,updatedAt:serverTimestamp$1(),expiresAt:Timestamp.fromMillis(t+2592e6)});}}));}async refreshDeviceForAutoConnect(e){let t=e.trim();if(!t)return null;let n=this.autoConnectRefreshes.get(t);if(n)return n;let i=this.refreshDeviceForAutoConnectOnce(t);this.autoConnectRefreshes.set(t,i);try{return await i}finally{this.autoConnectRefreshes.get(t)===i&&this.autoConnectRefreshes.delete(t);}}async refreshDeviceForAutoConnectOnce(e){if(this.rtdbPresence&&this.rtdbScope){let p=false,f=await this.readRtdbPresenceSnapshot().then(g=>g[e]).catch(g=>(p=true,console.warn("[BrowserDeviceDiscovery][auto-connect][refresh] RTDB read failed; refusing Firestore liveness fallback",{deviceId:e,error:g}),this.rtdbPresenceMap[e]));if(P(f)&&(f.ticket||f.nodeId)){let g=this.devicesById.get(e)??null,b=this.mergeRtdbPresenceIntoDevice(e,g,f)??this.deviceFromRtdbPresence(e,f);if(b){let y=this.upsertDeviceProjection(e,b);return R("[BrowserDeviceDiscovery][auto-connect][refresh]",{deviceId:e,source:"rtdb",ticketChanged:(g?.ticket??null)!==(b.ticket??null),previousTicket:j(g?.ticket),refreshedTicket:j(b.ticket),previousNodeId:g?.nodeId??null,refreshedNodeId:b.nodeId??null}),y&&this.emitDevicesToAll(),this.devicesById.get(e)??b}}if(p||!P(f))return null}let t=await this.hooks.getDevicesCollectionRef();if(!t)return this.devicesById.get(e)??null;let n=doc(t,e),i=this.devicesById.get(e)??null;this.options.auth.currentUser&&await this.economicDiscoveryLease.start();let s="server",o=null;try{o=await getDocFromServer(n);}catch(p){s="cache",console.warn("[BrowserDeviceDiscovery][auto-connect][refresh] getDocFromServer failed; falling back to getDoc",{deviceId:e,error:p}),o=await getDoc(n).catch(()=>null);}if(!o?.exists()){let p=this.devicesById.delete(e);return R("[BrowserDeviceDiscovery][auto-connect][refresh] device doc missing during refresh",{deviceId:e,source:s,previousTicket:j(i?.ticket)}),p&&this.emitDevicesToAll(),null}let a=typeof o.data=="function"?o.data():null,c=this.deviceFromSnapshot(e,a,Date.now());if(!c){let p=this.devicesById.delete(e);return R("[BrowserDeviceDiscovery][auto-connect][refresh] refreshed device doc was filtered out",{deviceId:e,source:s,previousTicket:j(i?.ticket)}),p&&this.emitDevicesToAll(),null}let l=this.rtdbPresenceMap[e],d=l?this.mergeRtdbPresenceIntoDevice(e,c,l)??c:c,u=this.upsertDeviceProjection(e,d),h=(i?.ticket??null)!==(d.ticket??null);return R("[BrowserDeviceDiscovery][auto-connect][refresh]",{deviceId:e,source:s,ticketChanged:h,previousTicket:j(i?.ticket),refreshedTicket:j(d.ticket),previousNodeId:i?.nodeId??null,refreshedNodeId:d.nodeId??null}),u&&this.emitDevicesToAll(),this.devicesById.get(e)??d}resolveKnownDeviceId(e){let t=e.trim();if(!t)return null;let n=this.devicesById.get(t);if(n?.deviceId)return n.deviceId;for(let i of this.devicesById.values())if(i.deviceId===t||i.nodeId===t||i.ticket===t)return i.deviceId;return null}stopDeviceWatch(e){this.deviceWatchGeneration+=1,this.deviceWatchSetup=null,this.clearFreshnessRecheckTimer(),this.activeDeviceUnsubscribe?.(),this.activeDeviceUnsubscribe=null,this.activeDeviceScopeKey=null,this.economicDiscoveryLease.stop(),e?.clearDevices&&(this.devicesById.clear(),this.hasDeviceRosterSnapshot=false,this.emitDevicesToAll());}clearFreshnessRecheckTimer(){this.freshnessRecheckTimer&&(clearTimeout(this.freshnessRecheckTimer),this.freshnessRecheckTimer=null);}scheduleFreshnessRecheck(e){this.deviceListeners.size===0||this.freshnessRecheckTimer||(this.freshnessRecheckTimer=setTimeout(()=>{if(this.freshnessRecheckTimer=null,e!==this.deviceWatchGeneration||this.deviceListeners.size===0)return;let t=Date.now(),n=false;for(let[i,s]of this.devicesById){let o=s;if(this.isStaleOnlineDevice(o,t)){this.shouldRetainStaleDevice(o)?this.devicesById.set(i,this.retainedStaleDevice(s,i,t)):this.devicesById.delete(i),n=true;continue}this.isDeviceExpired(o,t)&&(this.devicesById.delete(i),n=true);}n&&this.emitDevicesToAll(),this.scheduleFreshnessRecheck(e);},q.DEVICE_FRESHNESS_RECHECK_MS));}emitDevicesToAll(){for(let e of this.deviceListeners.keys())this.emitDevicesToListener(e);}emitDevicesToListener(e){let t=this.deviceListeners.get(e);if(!t)return;let n=Array.from(this.devicesById.values()),i=t.excludeNodeId?this.filterDevices(n,t.excludeNodeId):n;t.callback(i);}filterDevices(e,t){return e.filter(n=>n.ticket!==t&&n.deviceId!==t&&n.nodeId!==t)}deviceProjectionKey(e){return JSON.stringify({deviceId:e.deviceId,deviceName:e.deviceName,online:e.online,ticket:e.ticket,nodeId:e.nodeId??null,userId:e.userId??null,metadata:e.metadata??null,capabilities:e.capabilities??null,excludedPeers:[...e.excludedPeers??[]].sort()})}upsertDeviceProjection(e,t){let n=this.devicesById.get(e);return n&&this.deviceProjectionKey(n)===this.deviceProjectionKey(t)?false:(this.devicesById.set(e,t),true)}watchedDeviceSnapshot(e){return this.activeDeviceScopeKey!==e||!this.hasDeviceRosterSnapshot||!this.activeDeviceUnsubscribe&&!this.deviceWatchSetup?null:Array.from(this.devicesById.values())}async readDurableRosterDocuments(e,t){this.options.auth.currentUser&&await this.economicDiscoveryLease.start();let n=this.durableRosterRead;if(n?.scopeKey===t)return n.promise;let i=getDocs(query(e,limit(Ue))).then(s=>s.docs);this.durableRosterRead={scopeKey:t,promise:i};try{return await i}finally{this.durableRosterRead?.promise===i&&(this.durableRosterRead=null);}}async readRtdbPresenceSnapshot(){if(!this.rtdbPresence||!this.rtdbScope)return {};if(this.rtdbUnsubscribe&&this.hasRtdbPresenceSnapshot)return this.rtdbPresenceMap;if(this.rtdbPresenceRead)return this.rtdbPresenceRead;let e=this.rtdbPresence,t=this.rtdbScope,n=e.readPresenceMap(t).then(i=>(this.rtdbPresence===e&&St(this.rtdbScope,t)&&(this.rtdbPresenceMap=i,this.hasRtdbPresenceSnapshot=true),i));this.rtdbPresenceRead=n;try{return await n}finally{this.rtdbPresenceRead===n&&(this.rtdbPresenceRead=null);}}async readCurrentDeviceSnapshot(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return [];let t=e.path,n=this.deviceWatchSetup;n?.scopeKey===t&&await n.promise;let i=this.watchedDeviceSnapshot(t);if(i)return i;let s=this.rtdbPresenceMap;if(this.rtdbPresence&&this.rtdbScope)try{s=await this.readRtdbPresenceSnapshot();}catch(d){console.warn("[BrowserDeviceDiscovery] RTDB direct presence read failed:",d);}let o=await this.readDurableRosterDocuments(e,t),a=Date.now(),c=[],l=new Set;for(let d of o){let u=d.data();if(!this.options.matchesTag(u))continue;let h=typeof u.deviceId=="string"&&u.deviceId.trim().length>0?u.deviceId.trim():d.id;l.add(h);let p=s[h],f=P(p);if(this.isStaleFirestoreOnlyRtdbDevice(h,u,a))continue;if((this.isStaleOnlineDevice(u,a)||u.online===true&&this.isDeviceExpired(u,a))&&!f){if((!this.rtdbPresence||!this.rtdbScope)&&await this.markStaleDeviceOffline(d,u,a),this.shouldRetainStaleDevice(u)){let w=this.retainedStaleDevice(this.options.normalizeDevice({...u,deviceId:u.deviceId??d.id,online:false},d.id),d.id,a);w.deviceId&&c.push(w);}continue}if(this.isDeviceExpired(u,a)&&!f)continue;let b=this.options.normalizeDevice({...u,deviceId:u.deviceId??d.id},d.id);if(!b?.deviceId)continue;let y=p?this.mergeRtdbPresenceIntoDevice(b.deviceId,b,p):b;y&&c.push(y);}if(this.rtdbPresence&&this.rtdbScope)for(let[d,u]of Object.entries(s)){if(l.has(d)||!P(u))continue;let h=this.deviceFromRtdbPresence(d,u);h&&c.push(h);}this.devicesById.clear();for(let d of c)this.devicesById.set(d.deviceId,d);return this.hasDeviceRosterSnapshot=true,c}async readLiveRtdbDeviceSnapshot(){if(!this.rtdbPresence||!this.rtdbScope)return this.readCurrentDeviceSnapshot();let e;try{e=await this.readRtdbPresenceSnapshot();}catch(n){return console.warn("[BrowserDeviceDiscovery] RTDB live search read failed; refusing Firestore liveness fallback:",n),[]}let t=[];for(let[n,i]of Object.entries(e)){if(!P(i))continue;let s=this.devicesById.get(n),o=this.mergeRtdbPresenceIntoDevice(n,s,i)??this.deviceFromRtdbPresence(n,i);o?.deviceId&&(this.devicesById.set(o.deviceId,o),t.push(o));}return t}toDevice(e,t){return this.deviceFromSnapshot(e.id,e.data(),t,e)}deviceFromSnapshot(e,t,n,i){if(!t||!this.options.matchesTag(t))return null;let s=typeof t.deviceId=="string"&&t.deviceId.trim().length>0?t.deviceId.trim():e,o=this.rtdbPresenceMap[s],a=P(o);if(this.isStaleFirestoreOnlyRtdbDevice(s,t,n))return null;if((this.isStaleOnlineDevice(t,n)||t.online===true&&this.isDeviceExpired(t,n))&&!a){if(i&&(!this.rtdbPresence||!this.rtdbScope)&&this.markStaleDeviceOffline(i,t,n),!this.shouldRetainStaleDevice(t))return null;let d=this.retainedStaleDevice(this.options.normalizeDevice({...t,deviceId:t.deviceId??e,online:false},e),e,n);return d.deviceId?d:null}if(this.isDeviceExpired(t,n)&&!a)return null;let l=this.options.normalizeDevice({...t,deviceId:t.deviceId??e},e);return l.deviceId?o?this.mergeRtdbPresenceIntoDevice(s,l,o)??l:l:null}shouldRetainStaleDevice(e){return this.options.discoveryMode!=="user-scoped"||this.rtdbPresence&&this.rtdbScope&&e.online===true?false:(typeof e.kind=="string"?e.kind.trim().toLowerCase():"device")!=="ephemeral"}retainedStaleDevice(e,t,n){let i=this.toMillis(e.lastSeenAt)??this.toMillis(e.updatedAt)??this.toMillis(e.createdAt)??n;return {...e,deviceId:e.deviceId||t,online:false,presenceStatus:"idle",presenceUpdatedAt:i,presenceExpiresAt:this.toMillis(e.expiresAt)??n+2592e6,connectable:false}}isStaleOnlineDevice(e,t){if(e.online!==true)return false;if(this.rtdbPresence&&this.rtdbScope){let s=typeof e.deviceId=="string"&&e.deviceId.trim().length>0?e.deviceId.trim():"";if(s&&P(this.rtdbPresenceMap[s]))return false}let n=this.toMillis(e.updatedAt)??this.toMillis(e.lastSeenAt)??this.toMillis(e.createdAt);if(typeof n!="number")return false;let i=this.rtdbPresence&&this.rtdbScope?3e4:3e5;return n+i<=t}isStaleFirestoreOnlyRtdbDevice(e,t,n){if(!this.rtdbPresence||!this.rtdbScope||t.online!==true||P(this.rtdbPresenceMap[e]))return false;let i=this.toMillis(t.updatedAt)??this.toMillis(t.lastSeenAt)??this.toMillis(t.createdAt);return typeof i!="number"?false:i+3e4<=n}async markStaleDeviceOffline(e,t,n){let i=typeof t.deviceId=="string"&&t.deviceId.trim().length>0?t.deviceId:e.id,s=e.ref?.path||i;if(!(!s||this.staleDeviceOfflineWrites.has(s))){this.staleDeviceOfflineWrites.add(s);try{let o=await this.hooks.resolveDeviceRef(i);if(!o)return;this.options.auth.currentUser&&await this.economicDiscoveryLease.start(),await updateDoc(o,{online:!1,updatedAt:serverTimestamp$1(),expiresAt:Timestamp.fromMillis(n+2592e6)});}catch(o){console.warn("[BrowserDeviceDiscovery] failed to mark stale device offline:",o);}finally{this.staleDeviceOfflineWrites.delete(s);}}}isDeviceExpired(e,t){let n=this.toMillis(e.expiresAt);if(typeof n=="number")return n<=t;let i=e.online===true?3e5:2592e6,s=this.toMillis(e.updatedAt);if(typeof s=="number")return s+i<=t;let o=this.toMillis(e.lastSeenAt);return typeof o=="number"?o+i<=t:false}toMillis(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Date.parse(e);return Number.isNaN(t)?void 0:t}if(e instanceof Date)return e.getTime();if(e&&typeof e=="object"&&typeof e.toMillis=="function")return e.toMillis()}async ensureDeviceWatch(){if(this.deviceListeners.size===0)return;let e=await this.hooks.getDevicesCollectionRef(),t=e?.path??null;if(!e||!t){this.devicesById.clear(),this.emitDevicesToAll();return}if(this.activeDeviceUnsubscribe&&this.activeDeviceScopeKey===t)return;let n=this.deviceWatchSetup;if(n?.scopeKey===t)return n.promise;if(this.stopDeviceWatch({clearDevices:true}),this.rtdbPresence&&this.rtdbScope){let i=this.ensureDeviceWatchRtdb(e,t);this.deviceWatchSetup={scopeKey:t,promise:i};try{await i;}finally{this.deviceWatchSetup?.promise===i&&(this.deviceWatchSetup=null);}return}await this.startFirestoreDeviceWatch(e,t);}async startFirestoreDeviceWatch(e,t){this.options.auth.currentUser&&await this.economicDiscoveryLease.start();let n=++this.deviceWatchGeneration;this.activeDeviceScopeKey=t,this.activeDeviceUnsubscribe=onSnapshot(query(e,limit(Ue)),i=>{if(n!==this.deviceWatchGeneration)return;let s=Date.now();this.devicesById.clear();for(let o of i.docs){let a=this.toDevice(o,s);a&&this.devicesById.set(a.deviceId,a);}this.hasDeviceRosterSnapshot=true,this.emitDevicesToAll(),this.scheduleFreshnessRecheck(n);},i=>{if(n!==this.deviceWatchGeneration)return;let s=i?.code,o=String(i?.message??"");if((s==="permission-denied"||s==="PERMISSION_DENIED"||/permission.?denied/i.test(o)||/missing or insufficient permissions/i.test(o))&&!this.options.auth.currentUser){console.warn("[BrowserDeviceDiscovery] device watch permission-denied before auth; retrying after auth establishes"),this.stopDeviceWatch({clearDevices:false}),setTimeout(()=>{n===this.deviceWatchGeneration&&this.options.auth.currentUser&&this.ensureDeviceWatch();},500);return}console.warn("[BrowserDeviceDiscovery] device watch failed:",i);});}async ensureDeviceWatchRtdb(e,t){let n=++this.deviceWatchGeneration;this.activeDeviceScopeKey=t;let i=null,s=null;for(let l=0;l<3;l+=1)try{i=await E$1(this.readDurableRosterDocuments(e,t),q.RTDB_ROSTER_READ_TIMEOUT_MS,()=>new Error("RTDB-backed device roster read timed out")),s=null;break}catch(d){if(s=d,n!==this.deviceWatchGeneration)return;await u(x$1(l+1,250,Number.MAX_SAFE_INTEGER));}if(!i)throw new Error(`[BrowserDeviceDiscovery] RTDB-backed device watch setup failed after retries: ${s instanceof Error?s.message:String(s)}`);if(n!==this.deviceWatchGeneration)return;let o=Date.now();this.devicesById.clear(),this.replaceDevicesFromDocuments(i,o),this.hasDeviceRosterSnapshot=true;let a=this.rtdbPresence,c=this.rtdbScope;this.rtdbUnsubscribe&&this.rtdbUnsubscribe();try{this.rtdbUnsubscribe=a.onPresenceChange(c,l=>{if(n!==this.deviceWatchGeneration)return;R("[BrowserDeviceDiscovery][rtdb] presence update",{generation:n,devices:Object.keys(l).length,online:Object.values(l).filter(u=>P(u)).length}),this.rtdbPresenceMap=l,this.hasRtdbPresenceSnapshot=!0;let d=[];for(let[u,h]of Object.entries(l)){let p=this.knownTicketVersions.get(u)??-1,f=this.devicesById.has(u),g=!!(h.ticket||h.nodeId);h.ticketVersion!==p?(this.knownTicketVersions.set(u,h.ticketVersion),!g&&(p!==-1||!f&&P(h))&&d.push(u)):!g&&!f&&P(h)&&d.push(u);}this.applyRtdbOverlay(),this.scheduleFreshnessRecheck(n),d.length>0&&this.refetchDeviceTickets(d,n);});}catch(l){if(n!==this.deviceWatchGeneration)return;throw new Error(`[BrowserDeviceDiscovery] RTDB presence subscription setup failed; refusing Firestore-only liveness fallback: ${l instanceof Error?l.message:String(l)}`)}this.activeDeviceUnsubscribe=()=>{this.rtdbUnsubscribe?.(),this.rtdbUnsubscribe=null;},this.emitDevicesToAll(),this.scheduleFreshnessRecheck(n);}replaceDevicesFromDocuments(e,t){this.devicesById.clear();for(let n of e){let i=this.toDevice(n,t);i&&this.devicesById.set(i.deviceId,i);}}applyRtdbOverlay(){let e=false;for(let[t,n]of this.devicesById){let i=this.rtdbPresenceMap[t];if(!i)continue;let s=this.mergeRtdbPresenceIntoDevice(t,n,i);s&&(e=this.upsertDeviceProjection(t,s)||e);}for(let[t,n]of Object.entries(this.rtdbPresenceMap)){if(this.devicesById.has(t)||!P(n))continue;let i=this.deviceFromRtdbPresence(t,n);i&&(e=this.upsertDeviceProjection(t,i)||e);}e&&this.emitDevicesToAll();}mergeRtdbPresenceIntoDevice(e,t,n){if(!n)return t??null;let i=P(n),s={...t??{},appTag:this.options.appTag,tag:this.options.appTag,deviceId:e,deviceName:n.deviceName??t?.deviceName??"Device",online:i,ticket:n.ticket??t?.ticket??"",nodeId:n.nodeId??t?.nodeId,platformType:n.platformType??t?.platformType,metadata:n.metadata??t?.metadata,excludedPeers:n.excludedPeers??t?.excludedPeers,userId:t?.userId??this.options.getCurrentUserId()??void 0,updatedAt:Date.now(),lastSeenAt:Date.now()};if(!this.options.matchesTag(s))return null;let o=this.options.normalizeDevice(s,e);return o.deviceId?{...t??o,...o,online:i,ticket:n.ticket??o.ticket??t?.ticket??"",nodeId:n.nodeId??o.nodeId??t?.nodeId,deviceName:n.deviceName??o.deviceName??t?.deviceName??"Device",platformType:n.platformType??o.platformType??t?.platformType,metadata:n.metadata??o.metadata??t?.metadata,excludedPeers:n.excludedPeers??o.excludedPeers??t?.excludedPeers}:null}deviceFromRtdbPresence(e,t){if(!t.ticket&&!t.nodeId)return null;let n={appTag:this.options.appTag,tag:this.options.appTag,deviceId:e,deviceName:t.deviceName||"Device",online:P(t),ticket:t.ticket||"",nodeId:t.nodeId,platformType:t.platformType,metadata:t.metadata,excludedPeers:t.excludedPeers,userId:this.options.getCurrentUserId()??void 0,updatedAt:Date.now(),lastSeenAt:Date.now()};if(!this.options.matchesTag(n))return null;let i=this.options.normalizeDevice(n,e);return i.deviceId?i:null}async refetchDeviceTickets(e,t){await Promise.allSettled(e.map(async n=>{try{if(await this.refreshDeviceForAutoConnect(n),t!==this.deviceWatchGeneration)return}catch(i){console.warn("[BrowserDeviceDiscovery] refetch device ticket failed:",i);}}));}};q.RTDB_ROSTER_READ_TIMEOUT_MS=5e3,q.DEVICE_FRESHNESS_RECHECK_MS=3e4;var me=q;var ye=class{constructor(e){this.ctx=e;this.friendDeviceUnsubscribes=new Map;this.firestore=getFirestore(e.app);}watchFriendDevices(e,t){if(this.usesSpaceMode())return ()=>{};let n=new Map,i=new Set(e),s=false;for(let[o,a]of this.friendDeviceUnsubscribes)i.has(o)||(a(),this.friendDeviceUnsubscribes.delete(o),n.delete(o));for(let o of e){if(this.friendDeviceUnsubscribes.has(o))continue;let a=`apps/${this.ctx.appTag}/users/${o}/devices`,c=collection(this.firestore,a),l=null,d=()=>l?.();this.friendDeviceUnsubscribes.set(o,d),this.ctx.ensureUsageLease().then(()=>{s||!i.has(o)||this.friendDeviceUnsubscribes.get(o)!==d||(l=onSnapshot(query(c,limit(100)),u=>{let h=[];u.forEach(p=>{let f=p.data();if(!f||f.kind!=="device"||!this.ctx.matchesTag(f))return;let g=this.ctx.normalizeDevice(f,p.id);g.online&&h.push(g);}),n.set(o,h),t(new Map(n));},u=>{console.warn("[BrowserFriendDiscovery] friend device watch failed:",{friendUid:o,message:u?.message,code:u?.code});}),this.friendDeviceUnsubscribes.set(o,d));}).catch(u=>{this.friendDeviceUnsubscribes.get(o)===d&&this.friendDeviceUnsubscribes.delete(o),console.warn("[BrowserFriendDiscovery] friend usage lease failed:",{friendUid:o,message:u instanceof Error?u.message:String(u)});});}return ()=>{s=true;for(let[,o]of this.friendDeviceUnsubscribes)o();this.friendDeviceUnsubscribes.clear();}}async updateFriendTicket(e){let t=await this.ctx.resolveOrCreateLocalDeviceRef();t&&(await this.ctx.ensureUsageLease(),await updateDoc(t,{friendTicket:e??null}));}usesSpaceMode(){return this.ctx.usesSpaceMode?this.ctx.usesSpaceMode():(this.ctx.discoveryMode??"space")==="space"&&typeof this.ctx.apiKey=="string"&&this.ctx.apiKey.trim().length>0&&typeof this.ctx.spaceKey=="string"&&this.ctx.spaceKey.trim().length>0}};var $n="createSignalingSession",Rt=50,Se=class{constructor(e){this.ctx=e;this.activeEconomicWatchStops=new Set;this.economicSignalingLease=new A(e.app,"signaling.exchange",typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`signaling-${Date.now()}-${Math.random().toString(16).slice(2)}`,"firestore-signaling",t=>{for(let n of this.activeEconomicWatchStops)n(t);this.activeEconomicWatchStops.clear();});}async ensureEconomicUsageLease(){getAuth(this.ctx.app).currentUser&&await this.economicSignalingLease.start();}async createSession(e){if(this.shouldUseHostedSessionCallable()){await this.createHostedSession(e);return}let t=await this.ctx.getSessionsCollectionRef();if(!t)throw new Error("createSession requires an active browser signaling namespace");await this.ensureEconomicUsageLease();let n=doc(t,e.connectionId),i=Date.now(),s=600*1e3;await setDoc(n,{appTag:e.appTag??this.ctx.appTag,connectionId:e.connectionId,initiator:e.initiator??this.ctx.getCurrentUserId(),target:e.target??this.ctx.getCurrentUserId(),initiatorDeviceId:e.initiatorDeviceId,targetDeviceId:e.targetDeviceId,connectionType:e.connectionType??null,state:e.state,offer:e.offer?JSON.stringify(e.offer):null,offerE2ee:e.offerE2ee?JSON.stringify(e.offerE2ee):null,answer:e.answer?JSON.stringify(e.answer):null,answerE2ee:e.answerE2ee?JSON.stringify(e.answerE2ee):null,iceCandidates:Array.isArray(e.iceCandidates)?JSON.stringify(e.iceCandidates):null,initiatorNodeId:e.initiatorNodeId??null,targetNodeId:e.targetNodeId??null,initiatorEndpointAddr:e.initiatorEndpointAddr??null,targetEndpointAddr:e.targetEndpointAddr??null,intent:e.intent??null,createdAt:e.createdAt??i,updatedAt:i,expiresAt:i+s},{merge:true});}async updateSession(e,t){let n=await this.ctx.getSessionsCollectionRef();if(!n)throw new Error("updateSession requires an active browser signaling namespace");let i=doc(n,this.ctx.parseScopedId(e)),s={};if(t&&typeof t=="object"){for(let[o,a]of Object.entries(t))if(a!==void 0){if(a===null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"){s[o]=a;continue}s[o]=JSON.stringify(a);}}Object.keys(s).length!==0&&(await this.ensureEconomicUsageLease(),s.updatedAt=Date.now(),await updateDoc(i,s));}async sendMessage(e,t,n,i){let s=await this.ctx.getMessagesCollectionRef();if(!s)throw new Error("sendMessage requires an active browser signaling namespace");await this.ensureEconomicUsageLease();let o=this.createDocumentId(),a=doc(s,o),c=this.ctx.getCurrentUserId()??this.ctx.getLocalDeviceId(),l=this.ctx.getCurrentUserId();if(!l&&(this.ctx.discoveryMode??"space")!=="space")throw new Error("sendMessage requires an authenticated user in app-scoped signaling mode");let d=Date.now(),u=1440*60*1e3,h={appTag:this.ctx.appTag,senderId:c,targetId:e,payload:t,state:n??null,replyPayload:i??null,timestamp:d,expiresAt:d+u};return l&&(h.senderUserId=l,h.targetUserId=l),await setDoc(a,h),a.path}async pollMessages(e){let t=await this.ctx.getMessagesCollectionRef();if(!t)return [];let n=this.ctx.getCurrentUserId();if(!n&&(this.ctx.discoveryMode??"space")!=="space")return [];let i=n?[where("targetId","==",e),where("targetUserId","==",n),limit(50)]:[where("targetId","==",e),limit(50)];await this.ensureEconomicUsageLease();let s=await getDocs(query(t,...i)),o=[];for(let a of s.docs){let c=a.data(),l=typeof c.senderId=="string"?c.senderId:"",d=typeof c.targetId=="string"?c.targetId:"",u=typeof c.payload=="string"?c.payload:"";!l||!d||!u||o.push({appTag:typeof c.appTag=="string"?c.appTag:this.ctx.appTag,senderId:l,targetId:d,senderUserId:typeof c.senderUserId=="string"?c.senderUserId:void 0,targetUserId:typeof c.targetUserId=="string"?c.targetUserId:void 0,payload:u,state:typeof c.state=="string"?c.state:void 0,replyPayload:typeof c.replyPayload=="string"?c.replyPayload:void 0,timestamp:this.ctx.toMillis(c.timestamp),expiresAt:this.ctx.toMillis(c.expiresAt),_documentId:a.id});}return o.sort((a,c)=>(a.timestamp??0)-(c.timestamp??0)),await Promise.allSettled(o.map(async a=>{await deleteDoc(doc(t,a._documentId));})),o.map(({_documentId:a,...c})=>c)}async subscribeSessions(e){let t=await this.ctx.getSessionsCollectionRef(),n=this.ctx.parseScopedId(e);if(!t||!n)return new ReadableStream({start(l){l.close();}});await this.ensureEconomicUsageLease();let i=null,s=null,o=false,a=null,c=l=>{if(!o){if(o=true,i?.(),s?.(),i=null,s=null,this.activeEconomicWatchStops.delete(c),l!==void 0)try{a?.error(l);}catch{}a=null;}};return new ReadableStream({start:l=>{a=l,this.activeEconomicWatchStops.add(c);let d={initiator:new Set,target:new Set},u=new Map,h=(p,f)=>{if(o)return;let g=[];for(let b of f.docChanges()){let y=b.doc.id;if(b.type==="removed"){d[p].delete(y),!(d.initiator.has(y)||d.target.has(y))&&u.delete(y)&&g.push({type:"removed",sessionId:y});continue}let w=this.toSession(b.doc.id,b.doc.data());if(!w)continue;d[p].add(y);let I=u.has(y);u.set(y,w),g.push({type:I?"modified":"added",session:w});}g.length>0&&l.enqueue(g);};i=onSnapshot(query(t,where("initiatorDeviceId","==",n),limit(Rt)),p=>h("initiator",p),p=>{o||l.error(p);}),s=onSnapshot(query(t,where("targetDeviceId","==",n),limit(Rt)),p=>h("target",p),p=>{o||l.error(p);});},cancel:()=>{c(),this.economicSignalingLease.stop();}})}shouldUseHostedSessionCallable(){return (this.ctx.discoveryMode??"space")!=="space"&&!!this.ctx.getCurrentUserId()}async createHostedSession(e){await httpsCallable(getFunctions(this.ctx.app),$n)({...e,appTag:e.appTag??this.ctx.appTag,initiator:e.initiator??this.ctx.getCurrentUserId()??void 0,target:e.target??this.ctx.getCurrentUserId()??void 0});}toSession(e,t){let n=typeof t.initiatorDeviceId=="string"?t.initiatorDeviceId:"",i=typeof t.targetDeviceId=="string"?t.targetDeviceId:"";return !n&&!i?null:{connectionId:typeof t.connectionId=="string"?t.connectionId:e,initiator:typeof t.initiator=="string"?t.initiator:"",target:typeof t.target=="string"?t.target:"",initiatorDeviceId:n,targetDeviceId:i,connectionType:typeof t.connectionType=="string"?t.connectionType:void 0,offer:this.parseMaybeJson(t.offer),offerE2ee:this.parseMaybeJson(t.offerE2ee),answer:this.parseMaybeJson(t.answer),answerE2ee:this.parseMaybeJson(t.answerE2ee),iceCandidates:Array.isArray(t.iceCandidates)?t.iceCandidates:[],initiatorNodeId:typeof t.initiatorNodeId=="string"?t.initiatorNodeId:void 0,targetNodeId:typeof t.targetNodeId=="string"?t.targetNodeId:void 0,initiatorEndpointAddr:typeof t.initiatorEndpointAddr=="string"?t.initiatorEndpointAddr:void 0,targetEndpointAddr:typeof t.targetEndpointAddr=="string"?t.targetEndpointAddr:void 0,intent:typeof t.intent=="string"?t.intent:void 0,appTag:typeof t.appTag=="string"?t.appTag:this.ctx.appTag,createdAt:this.ctx.toMillis(t.createdAt),expiresAt:this.ctx.toMillis(t.expiresAt),state:typeof t.state=="string"?t.state:""}}parseMaybeJson(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}createDocumentId(){return `${Date.now()}-${Math.random().toString(36).slice(2,10)}`}};function Xn(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="not-found"}var we=class{constructor(e){this.options=e;this.rtdbPresence=null;this.namespaceRootPromise=null;this.resolvedDeviceDocIds=new Map;this.initializedLocalDevicePaths=new Set;this.firestore=getFirestore(e.app);try{let t=globalThis?.__OPENRTC_FIRESTORE_EMULATOR_HOST__,n=typeof t=="string"?t.trim():"";if(n){let[i,s]=n.split(":"),o=(i??"").trim()||"127.0.0.1",a=Number(s??8082);try{connectFirestoreEmulator(this.firestore,o,a);}catch{}}else {let i=import.meta?.env;if(!!i?.DEV&&String(i?.VITE_USE_EMULATORS)==="true"){let o=String(i?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",a=Number(i?.VITE_OPENRTC_FIRESTORE_EMULATOR_PORT??8082);try{connectFirestoreEmulator(this.firestore,o,a);}catch{}}}}catch{}this.discovery=new me({options:this.options,firestore:this.firestore,getDevicesCollectionRef:()=>this.getDevicesCollectionRef(),resolveDeviceRef:t=>this.resolveDeviceRef(t)}),this.friendDiscovery=new ye({app:e.app,appTag:e.appTag,discoveryMode:e.discoveryMode,apiKey:e.apiKey,spaceKey:e.spaceKey,matchesTag:e.matchesTag,normalizeDevice:e.normalizeDevice,resolveOrCreateLocalDeviceRef:()=>this.resolveOrCreateLocalDeviceRef(),ensureUsageLease:()=>this.discovery.ensureEconomicUsageLease(),usesSpaceMode:()=>this.usesSpaceMode()}),this.sessionSignaling=new Se({app:e.app,appTag:e.appTag,discoveryMode:e.discoveryMode,getCurrentUserId:()=>e.getCurrentUserId(),getLocalDeviceId:()=>e.getLocalDeviceId(),getSessionsCollectionRef:()=>this.getSessionsCollectionRef(),getMessagesCollectionRef:()=>this.getMessagesCollectionRef(),parseScopedId:t=>this.parseScopedId(t),toMillis:t=>this.toMillis(t)});}setRtdbPresence(e,t){this.rtdbPresence=e,this.discovery.setRtdbPresence(e,t);}getRtdbPresence(){return this.rtdbPresence}stopRtdbPresence(){this.rtdbPresence=null,this.discovery.stopRtdbPresence();}searchDevices(e){return this.discovery.searchDevices(e)}listDevices(e){return this.discovery.listDevices(e)}subscribeDevices(){return this.discovery.subscribeDevices()}onDevicesChange(e,t){return this.discovery.onDevicesChange(e,t)}async handleScopeChange(){this.clearScopeCaches(),await this.discovery.handleScopeChange();}stopAuthScopedActivity(){this.clearScopeCaches(),this.discovery.stopAuthScopedActivity(),this.discovery.stopEconomicUsageLease();}async updatePresence(e,t,n,i,s,o){let a=await this.resolveOrCreateLocalDeviceRef();if(!a)return;await this.discovery.ensureEconomicUsageLease();let c=this.options.getLocalDeviceId(),l=Date.now(),d=o?.trim()||this.options.getDefaultDeviceName(),u=this.options.getCurrentUserId(),h=Timestamp.fromMillis(n?l+Math.max(0,Math.trunc(i)):l+2592e6),p=a.path,f=this.initializedLocalDevicePaths.has(p)?null:await getDoc(a).catch(()=>null),g={appTag:this.options.appTag,tag:this.options.appTag,kind:"device",deviceId:c,deviceName:d,nodeId:e,platformType:"web",online:n,ticket:t,metadata:s??null,capabilities:{canHost:false,canSync:false,readOnly:false},lastSeenAt:serverTimestamp$1(),updatedAt:serverTimestamp$1(),expiresAt:h};u&&(g.userId=u),!this.initializedLocalDevicePaths.has(p)&&f&&!f.exists()&&(g.createdAt=serverTimestamp$1()),await setDoc(a,g,{merge:true}),this.initializedLocalDevicePaths.add(p);}async setOffline(e){let t=await this.resolveOrCreateLocalDeviceRef();if(!t)return;await this.discovery.ensureEconomicUsageLease();let n={appTag:this.options.appTag,tag:this.options.appTag,kind:"device",deviceId:this.options.getLocalDeviceId(),deviceName:this.options.getDefaultDeviceName(),nodeId:e,platformType:"web",online:false,updatedAt:serverTimestamp$1(),lastSeenAt:serverTimestamp$1(),expiresAt:Timestamp.fromMillis(Date.now()+2592e6)},i=this.options.getCurrentUserId();i&&(n.userId=i);try{await updateDoc(t,n);}catch(s){if(!Xn(s))throw s;this.initializedLocalDevicePaths.delete(t.path);}}async cleanupStaleDevices(){await this.discovery.cleanupStaleDevices();}async updateDevice(e,t){let n=await this.resolveDeviceRef(e);if(!n)throw new Error("updateDevice requires a known device record");await this.discovery.ensureEconomicUsageLease();let i={updatedAt:serverTimestamp$1()};typeof t.deviceName=="string"&&(i.deviceName=t.deviceName),t.capabilities&&(i.capabilities={canHost:t.capabilities.canHost??t.capabilities.can_host??false,canSync:t.capabilities.canSync??t.capabilities.can_sync??false,readOnly:t.capabilities.readOnly??t.capabilities.read_only??false}),typeof t.metadata=="string"&&(i.metadata=t.metadata),await updateDoc(n,i);}async deleteDevice(e){let t=await this.resolveDeviceRef(e);t&&(await this.discovery.ensureEconomicUsageLease(),await deleteDoc(t),this.clearScopeCaches());}async createSession(e){await this.sessionSignaling.createSession(e);}async updateSession(e,t){await this.sessionSignaling.updateSession(e,t);}async sendMessage(e,t,n,i){return this.sessionSignaling.sendMessage(e,t,n,i)}async pollMessages(e){return this.sessionSignaling.pollMessages(e)}async subscribeSessions(e){return this.sessionSignaling.subscribeSessions(e)}refreshDeviceForAutoConnect(e){return this.discovery.refreshDeviceForAutoConnect(e)}toMillis(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Date.parse(e);return Number.isNaN(t)?void 0:t}if(e instanceof Date)return e.getTime();if(e&&typeof e=="object"&&typeof e.toMillis=="function")return e.toMillis()}async getDevicesCollectionRef(){let e=await this.getDevicesCollectionPath();return e?collection(this.firestore,e):null}clearScopeCaches(){this.resolvedDeviceDocIds.clear(),this.initializedLocalDevicePaths.clear();}async getSessionsCollectionRef(){let e=await this.getNamespaceRoot();return e?collection(this.firestore,`${e}/sessions`):null}async getMessagesCollectionRef(){let e=await this.getNamespaceRoot();return e?collection(this.firestore,`${e}/messages`):null}async getDevicesCollectionPath(){let e=await this.getNamespaceRoot();if(!e)return null;if(this.usesSpaceMode())return `${e}/devices`;let t=this.options.getDiscoveryScopeId();return t?`${e}/users/${t}/devices`:null}async getNamespaceRoot(){if(this.usesSpaceMode()){if(!this.namespaceRootPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";this.namespaceRootPromise=a(e,t).then(n=>`spaces/${n}`);}return this.namespaceRootPromise}return `apps/${this.options.appTag}`}usesSpaceMode(){return (this.options.discoveryMode??"space")==="space"&&typeof this.options.apiKey=="string"&&this.options.apiKey.trim().length>0&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0}parseScopedId(e){let t=e.split("::");return t.length===2?t[1]:e}async resolveOrCreateLocalDeviceRef(){let e=await this.getDevicesCollectionRef();return e?doc(e,this.options.getLocalDeviceId()):null}async resolveDeviceRef(e){let t=await this.getDevicesCollectionRef();if(!t)return null;let n=e.trim();if(!n)return null;let i=this.resolvedDeviceDocIds.get(n);if(i)return doc(t,i);let s=this.discovery.resolveKnownDeviceId(n);if(s)return this.resolvedDeviceDocIds.set(n,s),doc(t,s);let o=doc(t,n);if(await this.discovery.ensureEconomicUsageLease(),(await getDoc(o)).exists())return this.resolvedDeviceDocIds.set(n,n),o;let a=await getDocs(query(t,where("deviceId","==",n),limit(1)));if(!a.empty){let l=a.docs[0].id;return this.resolvedDeviceDocIds.set(n,l),a.docs[0].ref}let c=await getDocs(query(t,where("nodeId","==",n),limit(1)));if(!c.empty){let l=c.docs[0].id;return this.resolvedDeviceDocIds.set(n,l),c.docs[0].ref}return null}watchFriendDevices(e,t){return this.friendDiscovery.watchFriendDevices(e,t)}updateFriendTicket(e){return this.friendDiscovery.updateFriendTicket(e)}};var ei=3e4,ti=3e4,Mt=15e3,ni=1e3;function k(r){return typeof crypto.randomUUID=="function"?`${r}:${crypto.randomUUID()}`:`${r}:${Date.now()}:${Math.random().toString(16).slice(2)}`}async function ii(r){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)),t="";for(let n of new Uint8Array(e))t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function ri(r,e){let t=new URL(r);if(t.search||t.hash||t.username||t.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(t.protocol==="https:")t.protocol="wss:";else if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol!=="wss:"&&t.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return t.pathname=`${t.pathname.replace(/\/+$/,"")}/v1/connect/${e}`,t.toString()}function xt(r){let e=new URL(r);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}var Re=class r{constructor(e){this.options=e;this.runtimeInstanceId=k("runtime");this.socket=null;this.socketReady=false;this.connectPromise=null;this.desiredPresence=null;this.devices=new Map;this.deviceListeners=new Set;this.deviceStreams=new Set;this.sessionStreams=new Set;this.pendingAcks=new Map;this.pendingMessages=[];this.roomConnections=new Map;this.friendConnections=new Map;this.reconnectTimer=null;this.authRefreshTimer=null;this.reconnectAttempt=0;this.stopped=false;if(e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let t=new URL(e.gateway.endpoint),n=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]",i=t.protocol==="https:"||t.protocol==="wss:",s=e.gateway.environment==="staging"&&n&&(t.protocol==="http:"||t.protocol==="ws:");if(!i&&!s)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}async updatePresence(e,t,n,i,s,o){this.desiredPresence={localNodeId:e,ticket:t,online:n,ttlMs:i,metadata:s,deviceName:o?.trim()||this.options.getDefaultDeviceName()},await this.ensureConnected(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:k("presence"),ttlMs:i,device:this.gatewayDevice(this.desiredPresence)});}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:k("offline")}));}async updateDevice(e,t){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:k("device-patch"),patch:t});}async deleteDevice(e){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can delete only its local device.");await this.ensureConnected(),await this.sendOperation({v:1,type:"device.delete",idempotencyKey:k("device-delete")});}async cleanupStaleDevices(){}async searchDevices(e){return this.snapshot(e)}async listDevices(e){return this.snapshot(e)}onDevicesChange(e,t){let n=i=>e(t?i.filter(s=>s.nodeId!==t):i);return this.deviceListeners.add(n),n(this.snapshot()),this.desiredPresence&&this.ensureConnected(),()=>this.deviceListeners.delete(n)}async subscribeDevices(){let e=null;return new ReadableStream({start:t=>{e=t,this.deviceStreams.add(t);let n=this.snapshot().map(i=>({type:"added",device:i}));n.length>0&&t.enqueue(n);},cancel:()=>{e&&this.deviceStreams.delete(e),e=null;}})}async createSession(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:k("session-put"),sessionId:e.connectionId,session:e,expiresAtMs:e.expiresAt??Date.now()+15*6e4});}async updateSession(e,t){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:k("session-update"),sessionId:this.unscopedId(e),session:t,expiresAtMs:typeof t.expiresAt=="number"?t.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let t=null;return new ReadableStream({start:n=>{t=n,this.sessionStreams.add(n);},cancel:()=>{t&&this.sessionStreams.delete(t),t=null;}})}async sendMessage(e,t,n,i){await this.ensureConnected();let s=k("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:s,targetDeviceId:this.unscopedId(e),payload:t,state:n,replyPayload:i}),s}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,t){let n={value:false},i=new Map,s=[];t(new Map);for(let o of [...new Set(e)]){let a=o.trim();!a||a===this.options.getCurrentUserId()||this.openFriendConnection(a).then(c=>{if(n.value){c.stopAuthScopedActivity();return}s.push(c.onDevicesChange(l=>{i.set(a,l.filter(d=>d.online)),t(new Map(i));}));}).catch(()=>{n.value||(i.set(a,[]),t(new Map(i)));});}return ()=>{n.value=true;for(let o of s)o();for(let o of e)this.friendConnections.get(o.trim())?.stopAuthScopedActivity(),this.friendConnections.delete(o.trim());}}async updateFriendTicket(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:k("friend-ticket"),patch:{friendTicket:e??""}});}async handleScopeChange(){this.stopSocket(),this.devices.clear(),this.emitDevices();}stopAuthScopedActivity(){this.stopped=true,this.stopSocket();for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.reject(new Error("Coordination session stopped."));this.pendingAcks.clear(),this.devices.clear(),this.pendingMessages.splice(0,this.pendingMessages.length),this.emitDevices();for(let e of this.roomConnections.values())e.stopAuthScopedActivity();this.roomConnections.clear();for(let e of this.friendConnections.values())e.stopAuthScopedActivity();this.friendConnections.clear();}stopRtdbPresence(){}usesCoordinationGateway(){return true}async joinCoordinationRoom(e,t,n){let i=e.trim().toUpperCase(),s=this.roomConnections.get(i);s||(s=new r({...this.options,avenueOverride:{kind:"room",id:i}}),this.roomConnections.set(i,s)),await s.updatePresence(t,n,true,5*6e4,void 0,this.options.getDefaultDeviceName());}async leaveCoordinationRoom(e){let t=e.trim().toUpperCase(),n=this.roomConnections.get(t);n&&(await n.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),n.stopAuthScopedActivity(),this.roomConnections.delete(t));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(n=>this.roomMember(n))}watchCoordinationRoomMembers(e,t){return this.requireRoomConnection(e).onDevicesChange(i=>t(i.map(s=>this.roomMember(s))))}async ensureConnected(){if(this.connectPromise)return this.connectPromise;if(!(this.socket?.readyState===WebSocket.OPEN&&this.socketReady)){if(!this.desiredPresence)throw new Error("Coordination presence must be initialized before the gateway can connect.");this.stopped=false,this.connectPromise=this.connect();try{await this.connectPromise;}finally{this.connectPromise=null;}}}async connect(){let e=this.desiredPresence,t=await this.resolveAvenue(),n=await ii(e.ticket),i=this.options.getPlatformType()==="web"?"mintCoordinationCredential":"mintNativeCoordinationCredential",a=(await httpsCallable(getFunctions(this.options.app),i)({avenue:t,deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:n})).data;if(a.protocolVersion!==1)throw new Error("Unsupported coordination gateway protocol.");let c=xt(this.options.gateway.endpoint);if(xt(a.gatewayUrl)!==c)throw new Error("Coordination credential returned an unexpected gateway origin.");await new Promise((l,d)=>{let u=new WebSocket(ri(a.gatewayUrl,a.routeKey));this.socket=u;let h=false,p=setTimeout(()=>{u.close(4408,"authentication timeout"),d(new Error("Coordination gateway authentication timed out."));},Mt);u.onopen=()=>{u.send(JSON.stringify({v:1,type:"auth",token:a.token,device:this.gatewayDevice(e)}));},u.onmessage=f=>{let g;try{g=JSON.parse(String(f.data));}catch{u.close(4400,"invalid gateway frame"),h||(clearTimeout(p),d(new Error("Coordination gateway returned an invalid frame.")));return}g.type==="ready"&&!h&&(h=true,this.socketReady=true,clearTimeout(p),this.reconnectAttempt=0,this.scheduleAuthRefresh(a.expiresAtMs),l()),this.handleFrame(g);},u.onerror=()=>{h||(clearTimeout(p),d(new Error("Coordination gateway connection failed.")));},u.onclose=()=>{clearTimeout(p),this.socket===u&&(this.socket=null,this.socketReady=false),this.rejectPendingAcks("Coordination gateway connection closed."),!this.stopped&&this.desiredPresence&&this.scheduleReconnect();};});}handleFrame(e){if(e.type==="roster.snapshot"){this.devices.clear();for(let t of e.devices)this.devices.set(t.deviceId,this.toDevice(t));this.emitDevices();}else if(e.type==="presence.changed"){if(e.operation==="delete")this.devices.delete(e.device.deviceId),this.emitDeviceEvents([{type:"removed",deviceId:e.device.deviceId}]);else {let t=this.devices.has(e.device.deviceId),n=this.toDevice(e.device);this.devices.set(n.deviceId,n),this.emitDeviceEvents([{type:t?"modified":"added",device:n}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=ni&&this.pendingMessages.shift(),this.pendingMessages.push({senderId:e.senderDeviceId,targetId:this.options.getLocalDeviceId(),payload:e.payload,state:e.state,replyPayload:e.replyPayload,timestamp:e.createdAtMs,appTag:this.options.appTag});else if(e.type==="session.changed"){let t=e.operation==="delete"?[{type:"removed",sessionId:e.sessionId}]:[{type:"modified",session:{...e.session??{},connectionId:e.sessionId}}];for(let n of this.sessionStreams)n.enqueue(t);}else if(e.type==="ack"){let t=this.pendingAcks.get(e.idempotencyKey);t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.resolve());}else if(e.type==="error"){let t=e.idempotencyKey?this.pendingAcks.get(e.idempotencyKey):null;t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.reject(new Error(`Coordination gateway ${e.code}: ${e.message}`)));}}async sendOperation(e){let t=this.socket;if(!t||t.readyState!==WebSocket.OPEN)throw new Error("Coordination gateway is not connected.");await new Promise((n,i)=>{let s=setTimeout(()=>{this.pendingAcks.delete(e.idempotencyKey),i(new Error("Coordination gateway acknowledgement timed out."));},Mt);this.pendingAcks.set(e.idempotencyKey,{resolve:n,reject:i,timer:s}),t.send(JSON.stringify(e));});}async resolveAvenue(){if(this.options.avenueOverride)return this.options.avenueOverride;if((this.options.discoveryMode??"space")==="space"){let t=await this.options.resolveSpaceNamespaceId();if(!t)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:t}}let e=this.options.getCurrentUserId();if(!e)throw new Error("Authenticated user is required for coordination.");return {kind:"user",id:e}}gatewayDevice(e){return {deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,nodeId:e.localNodeId,deviceName:e.deviceName,platformType:this.options.getPlatformType(),ticket:e.ticket,metadata:e.metadata,online:e.online}}toDevice(e){return this.options.normalizeDevice({...e,appTag:this.options.appTag,lastSeenAt:e.updatedAtMs,expiresAt:e.expiresAtMs},e.deviceId)}snapshot(e){return [...this.devices.values()].filter(t=>!e||t.nodeId!==e).sort((t,n)=>t.deviceId.localeCompare(n.deviceId))}emitDevices(){let e=this.snapshot();for(let t of this.deviceListeners)t(e);}emitDeviceEvents(e){for(let t of this.deviceStreams)t.enqueue(e);}scheduleAuthRefresh(e){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.authRefreshTimer=setTimeout(()=>{this.stopSocket(false),this.stopped||this.ensureConnected();},Math.max(1e3,e-Date.now()-ei));}scheduleReconnect(){if(this.reconnectTimer)return;let e=Math.min(ti,250*2**Math.min(7,this.reconnectAttempt++));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(()=>this.scheduleReconnect());},e);}stopSocket(e=true){e&&this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.reconnectTimer=null,this.authRefreshTimer=null;let t=this.socket;this.socket=null,this.socketReady=false,t?.close(1e3,"coordination session stopped");}rejectPendingAcks(e){for(let t of this.pendingAcks.values())clearTimeout(t.timer),t.reject(new Error(e));this.pendingAcks.clear();}unscopedId(e){let t=e.split("::");return t.length===2?t[1]:e}requireRoomConnection(e){let t=e.trim().toUpperCase(),n=this.roomConnections.get(t);if(!n)throw new Error(`Room ${t} is not joined through the coordination gateway.`);return n}async openFriendConnection(e){let t=this.friendConnections.get(e);if(t||(t=new r({...this.options,avenueOverride:{kind:"user",id:e}}),this.friendConnections.set(e,t)),!t.desiredPresence){if(!this.desiredPresence)throw new Error("Local coordination presence must start before friend discovery.");t.desiredPresence={...this.desiredPresence};}return await t.ensureConnected(),t}roomMember(e){return {nodeId:e.nodeId??e.deviceId,userId:e.userId??"",ticket:e.ticket,joinedAt:Number(e.createdAt??e.lastSeenAt??Date.now()),lastSeenAt:Number(e.lastSeenAt??Date.now()),expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0}}};var T=class T{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.rtdbPresenceRetryTimer=null;this.rtdbPresenceRetryAttempt=0;this.durablePresenceRetryTimer=null;this.durablePresenceRetryAttempt=0;this.localExcludedPeers=new Set;}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let n=t.trim()||this.deps.resolveWebLogicalDeviceId(),i=`${e}::${n}`;this.startedAutoConnectKey===i&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.startedAutoConnectKey=i,this.browserAutoConnectUnsubscribe=this.deps.getBrowserFirestoreSignaling().onDevicesChange(s=>this.submitDesiredPeers(s),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let t=e.map(i=>({deviceId:String(i.deviceId??"").trim(),nodeId:typeof i.nodeId=="string"&&i.nodeId.trim()||null,ticket:typeof i.ticket=="string"&&i.ticket.trim()||null,online:i.online===true,sessionId:typeof i.sessionId=="string"&&i.sessionId.trim()||null,excludedPeers:Array.isArray(i.excludedPeers)?[...new Set(i.excludedPeers.map(s=>String(s??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(i=>i.deviceId.length>0).sort((i,s)=>i.deviceId.localeCompare(s.deviceId));this.desiredPeersByDeviceId=new Map(t.map(i=>[i.deviceId,i]));let n=JSON.stringify(t);n!==this.desiredPeerSignature&&(this.desiredPeerSignature=n,this.deps.onDesiredPeersChanged?.(),this.queuedDesiredPeers=t,this.flushDesiredPeerSubmission());}resolveDesiredPeer(e,t){let n=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(n){let s=this.desiredPeersByDeviceId.get(n);if(s&&(!i||!s.nodeId||s.nodeId===i))return s}return i?Array.from(this.desiredPeersByDeviceId.values()).find(s=>s.nodeId===i)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,n=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.deps.waitForWasmClient().then(async i=>{if(this.startedAutoConnectKey===e){if(!i||typeof i.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}await Promise.all(t.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(o){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:o});}})),await i.submit_browser_desired_peers(n,JSON.stringify(t));}}).catch(i=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:n,error:i});}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}async setAutoConnectExcluded(e,t){let n=await this.deps.waitForWasmClient();n&&typeof n.set_auto_connect_excluded=="function"&&await n.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async recordAutoConnectExcludedForPresence(e,t){let n=e.trim().toLowerCase();n&&(t?this.localExcludedPeers.add(n):this.localExcludedPeers.delete(n),await this.republishRtdbPresence("excluded-peers-updated"));}startPresenceLoop(e,t,n,i,s){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let o=++this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:i,metadata:s,deviceName:n};let a=this.deps.resolveWebLogicalDeviceId(),c=async l=>{let d=await this.deps.withWebPresenceMetadata(s,a),u=()=>o===this.presenceStartGeneration&&this.presenceState!==null;if(!u())return;if(!this.deps.isRtdbPresenceDisabledForSession()&&l&&a){let p=false,f=false,g=null,b=null,y=(I,D)=>{this.scheduleDurableRosterRetry(a,o,2592e6,I,D);},w=(I,D)=>{u()&&(this.deps.isRtdbPresenceDisabledForSession()||this.scheduleRtdbPresenceRetry(l,a,o,I,D));};g=setTimeout(()=>{p||y("initial durable roster write timed out");},T.INITIAL_PRESENCE_WRITE_TIMEOUT_MS),b=setTimeout(()=>{f||w("RTDB presence register timed out");},T.RTDB_PRESENCE_REGISTER_TIMEOUT_MS),this.deps.updatePresence(t,i,false,2592e6,d,n).then(()=>{p=true,g&&(clearTimeout(g),g=null),this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(I=>{g&&(clearTimeout(g),g=null),y("initial durable roster write failed",I);}),this.deps.registerRtdbPresence(l,a,this.deps.getRtdbTicketVersion(),{ticket:i,nodeId:t,deviceName:n,platformType:"web",metadata:d,excludedPeers:this.currentExcludedPeersSnapshot()}).then(()=>{f=true,this.rtdbPresenceRetryAttempt=0,this.clearRtdbPresenceRetryTimer(),b&&(clearTimeout(b),b=null);}).catch(I=>{b&&(clearTimeout(b),b=null),w("RTDB presence register failed",I);});return}let h=Q.browserIdentity.ephemeralDeviceIdTtlMs;this.deps.updatePresence(t,i,false,h,d,n).then(()=>{this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(p=>{this.scheduleDurableRosterRetry(a,o,h,"durable roster write failed without RTDB presence",p);});};if(this.deps.resolveRtdbScope){this.deps.resolveRtdbScope(e).then(l=>c(l));return}c(this.deps.buildRtdbScope(e));}clearDurablePresenceRetryTimer(){this.durablePresenceRetryTimer&&(clearTimeout(this.durablePresenceRetryTimer),this.durablePresenceRetryTimer=null);}scheduleDurableRosterRetry(e,t,n,i,s){if(t!==this.presenceStartGeneration||this.presenceState===null||this.durablePresenceRetryTimer)return;let o=this.durablePresenceRetryAttempt+1;this.durablePresenceRetryAttempt=o;let a=Math.min(T.RTDB_PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,o-1),T.RTDB_PRESENCE_RETRY_MAX_DELAY_MS),c=(o*17%21-10)/100,l=Math.max(T.RTDB_PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${i}; retrying durable roster registration in ${l}ms without Firestore heartbeat`,s),this.durablePresenceRetryTimer=setTimeout(()=>{this.durablePresenceRetryTimer=null,!(t!==this.presenceStartGeneration||this.presenceState===null)&&(async()=>{if(this.presenceState===null)return;let d=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,e);t!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(this.presenceState.localNodeId,this.presenceState.ticket,false,n,d,this.presenceState.deviceName);})().then(()=>{this.durablePresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer();}).catch(d=>{this.scheduleDurableRosterRetry(e,t,n,"durable roster registration retry failed",d);});},l);}clearRtdbPresenceRetryTimer(){this.rtdbPresenceRetryTimer&&(clearTimeout(this.rtdbPresenceRetryTimer),this.rtdbPresenceRetryTimer=null);}scheduleRtdbPresenceRetry(e,t,n,i,s){if(n!==this.presenceStartGeneration||this.presenceState===null||this.rtdbPresenceRetryTimer||this.deps.isRtdbPresenceDisabledForSession())return;let o=this.rtdbPresenceRetryAttempt+1;this.rtdbPresenceRetryAttempt=o;let a=Math.min(T.RTDB_PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,o-1),T.RTDB_PRESENCE_RETRY_MAX_DELAY_MS),c=(o*29%21-10)/100,l=Math.max(T.RTDB_PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${i}; retrying RTDB presence in ${l}ms without Firestore heartbeat fallback`,s),this.rtdbPresenceRetryTimer=setTimeout(()=>{this.rtdbPresenceRetryTimer=null,!(n!==this.presenceStartGeneration||this.presenceState===null||this.deps.isRtdbPresenceDisabledForSession())&&(async()=>{if(this.presenceState===null)return;let d=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,t);n!==this.presenceStartGeneration||this.presenceState===null||this.deps.isRtdbPresenceDisabledForSession()||await this.deps.registerRtdbPresence(e,t,this.deps.getRtdbTicketVersion(),{ticket:this.presenceState.ticket,nodeId:this.presenceState.localNodeId,deviceName:this.presenceState.deviceName,platformType:"web",metadata:d,excludedPeers:this.currentExcludedPeersSnapshot()});})().then(()=>{this.rtdbPresenceRetryAttempt=0;}).catch(d=>{this.scheduleRtdbPresenceRetry(e,t,n,"RTDB presence retry failed",d);});},l);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}async republishRtdbPresence(e){let t=this.presenceState;if(!t||this.deps.isRtdbPresenceDisabledForSession())return;let n=this.deps.resolveWebLogicalDeviceId();if(!n)return;let i=this.deps.resolveRtdbScope?await this.deps.resolveRtdbScope(t.userId):this.deps.buildRtdbScope(t.userId);if(!i)return;let s=await this.deps.withWebPresenceMetadata(t.metadata,n);await this.deps.registerRtdbPresence(i,n,this.deps.getRtdbTicketVersion(),{ticket:t.ticket,nodeId:t.localNodeId,deviceName:t.deviceName,platformType:"web",metadata:s,excludedPeers:this.currentExcludedPeersSnapshot()});}stopPresenceLoop(){this.presenceStartGeneration+=1,this.clearRtdbPresenceRetryTimer(),this.rtdbPresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0,this.presenceState=null;}};T.RTDB_PRESENCE_REGISTER_TIMEOUT_MS=5e3,T.INITIAL_PRESENCE_WRITE_TIMEOUT_MS=5e3,T.RTDB_PRESENCE_RETRY_MIN_DELAY_MS=2e3,T.RTDB_PRESENCE_RETRY_MAX_DELAY_MS=6e4;var Pe=T;var Te="trustedDevice",si="plutonium:e2ee:identity:v1",oi="plutonium:e2ee:identity:session:v1",ai="openrtc-trust",V="identity",Lt="transport-trust:v1",ci=1,E=null,ie=null;function _(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function re(r){let e="";for(let t=0;t<r.length;t+=1)e+=String.fromCharCode(r[t]);return btoa(e)}async function Nt(r){let e=await crypto.subtle.digest("SHA-256",r),t=new Uint8Array(e);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}function di(){return typeof sessionStorage>"u"?null:sessionStorage}function li(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(si);}catch{}}var De=null;async function Ot(){return De||(De=(async()=>{let r=globalThis.crypto?.subtle;if(!r||typeof r.generateKey!="function")return false;try{let e=await r.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),De)}async function ui(r){let e=await crypto.subtle.exportKey("raw",r);return new Uint8Array(e)}function pi(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function Ft(){let r=pi();return r?new Promise(e=>{let t;try{t=r.open(ai,1);}catch{e(null);return}t.onupgradeneeded=()=>{let n=t.result;n.objectStoreNames.contains(V)||n.createObjectStore(V);},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);}):Promise.resolve(null)}async function hi(){let r=await Ft();if(!r)return null;try{return await new Promise(e=>{let i=r.transaction(V,"readonly").objectStore(V).get(Lt);i.onsuccess=()=>{let s=i.result;e(s&&s.privateKey&&s.publicKey?s:null);},i.onerror=()=>e(null);})}catch{return null}finally{r.close();}}async function fi(r){let e=await Ft();if(!e)return false;try{return await new Promise(t=>{let n=e.transaction(V,"readwrite");n.objectStore(V).put(r,Lt),n.oncomplete=()=>t(!0),n.onerror=()=>t(!1),n.onabort=()=>t(!1);})}catch{return false}finally{e.close();}}async function Bt(r,e){let t=await ui(r.publicKey),n=await Nt(t),i=r.privateKey;return {publicKey:t,fingerprint:n,backend:"webcrypto-nonextractable",durable:e,privateKey:i,async signChallenge(s){let o=await crypto.subtle.sign({name:"Ed25519"},i,_(s));return re(new Uint8Array(o))}}}function gi(r,e,t){let n=r.secretKey;return {publicKey:r.publicKey,secretKey:n,fingerprint:e,backend:"tweetnacl",durable:t,async signChallenge(i){return mi(i,n)}}}function kr(r=32){let e=crypto.getRandomValues(new Uint8Array(r));return re(e)}function mi(r,e){let t=Ce.sign.detached(_(r),e);return re(t)}function yi(r,e,t){try{return Ce.sign.detached.verify(_(r),_(e),_(t))}catch{return false}}async function _r(r,e,t){let n=globalThis.crypto?.subtle;if(n&&typeof n.importKey=="function"&&typeof n.verify=="function")try{let i=await n.importKey("raw",_(t),{name:"Ed25519"},!1,["verify"]);return await n.verify({name:"Ed25519"},i,_(e),_(r))}catch{}return yi(r,e,t)}function Mr(r){return re(r)}function xr(r){if(!r||!r.trim())return null;try{let e=JSON.parse(r),t=e&&typeof e=="object"&&!Array.isArray(e)?e[Te]:null;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,i=typeof n.version=="number"?n.version:null,s=typeof n.identityPublicKey=="string"?n.identityPublicKey:null,o=typeof n.identityFingerprint=="string"?n.identityFingerprint:null;return !i||!s||!o?null:{version:i,identityPublicKey:s,identityFingerprint:o}}catch{return null}}async function vi(){let r=await Ri().catch(()=>null);return r?{version:ci,identityPublicKey:re(r.publicKey),identityFingerprint:r.fingerprint}:null}async function He(r){let e=await vi();if(!e)return r??void 0;let t=typeof r=="string"?r.trim():"";if(!t)return JSON.stringify({[Te]:e});try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return JSON.stringify({...n,[Te]:e})}catch{}return JSON.stringify({metadata:r,[Te]:e})}function bi(){if(typeof window>"u")return null;let r=window.__TAURI_INTERNALS__;return !r||typeof r.invoke!="function"?null:r.invoke.bind(r)}async function Si(){if(!t()||typeof window>"u"||/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||""))return null;let r=bi();if(!r)return null;try{let e=await r("openrtc_get_transport_trust_identity");return {publicKey:_(e.publicKeyBase64),fingerprint:e.fingerprint,backend:"native-keychain",durable:!0,async signChallenge(n){return r("openrtc_sign_transport_trust_challenge",{challenge:n})}}}catch{return null}}function Ii(){let r=di();r&&r.removeItem(oi);}async function wi(){if(li(),Ii(),E)return E;let r=await Si();if(r)return E=r,E;if(await Ot()){let e=await hi();if(e)return E=await Bt(e,true),E}return null}async function Ri(r={}){let e=await wi();if(e)return e;if(ie)return ie;let t=Pi(r);ie=t;try{return await t}finally{ie===t&&(ie=null);}}async function Pi(r){if(E)return E;let e=r.ephemeral===true;if(await Ot())try{let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),n=!1;return e||(n=await fi(t)),E=await Bt(t,n),E}catch{}if(!e)return console.warn("[OpenRTC][TRUST] Managed transport trust requires WebCrypto Ed25519 or native keychain; refusing extractable fallback storage"),null;try{let t=Ce.sign.keyPair(),n=await Nt(v$1(t.publicKey));return E=gi(t,n,!1),E}catch{return null}}function Y(r){return !r||typeof r!="object"?{}:r instanceof Map?Object.fromEntries(r):r}function Ke(r){let e=Y(r),t=Y(e.device);if(!Object.keys(t).length)return e;let n={...t,...e};return delete n.device,n}function m(r,...e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return n}}function H(r,...e){for(let t of e){let n=r[t];if(typeof n=="boolean")return n}}function v(r,...e){for(let t of e){let n=r[t];if(typeof n=="number"&&Number.isFinite(n))return n}}function x(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(r instanceof Date){let e=r.getTime();return Number.isFinite(e)?e:void 0}if(typeof r=="string"){let e=Date.parse(r);return Number.isFinite(e)?e:void 0}if(r&&typeof r=="object"){let e=r;if(typeof e.toMillis=="function"){let n=e.toMillis();return Number.isFinite(n)?n:void 0}let t=typeof e.seconds=="number"?e.seconds:typeof e._seconds=="number"?e._seconds:void 0;if(t!==void 0&&Number.isFinite(t)){let n=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return t*1e3+Math.floor((Number.isFinite(n)?n:0)/1e6)}}}function ze(...r){let e=r.map(x).filter(t=>typeof t=="number"&&Number.isFinite(t));return e.length?Math.max(...e):void 0}function je(r){if(typeof r!="string")return;let e=r.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Ut(r){let e=je("presenceStatus"in r?r.presenceStatus:void 0),t="presenceUpdatedAt"in r?x(r.presenceUpdatedAt):void 0,n="presenceExpiresAt"in r?x(r.presenceExpiresAt):void 0,i=t??ze(r.lastSeenAt,r.updatedAt,r.createdAt),s=n??x(r.expiresAt),o=e;o||(r.online?i!==void 0&&i+3e5<=Date.now()?o="idle":o="online":o="offline");let a=typeof r.ticket=="string"?r.ticket.trim():"",c="connectable"in r&&typeof r.connectable=="boolean"?r.connectable:o==="online"&&a.length>0;return {presenceStatus:o,presenceUpdatedAt:i,presenceExpiresAt:s,connectable:c}}function Wt(r){return b$1(r)}function J(r,...e){return Wt(m(r,...e))}function oe(r){if(!Array.isArray(r))return;let e=Array.from(new Set(r.map(Wt).filter(t=>!!t)));return e.length?e:void 0}function Gt(r){let e=Y(r),t={webrtc:v(e,"webrtc"),webrtcLan:v(e,"webrtcLan","webrtc_lan"),webrtcTurn:v(e,"webrtcTurn","webrtc_turn"),iroh:v(e,"iroh"),irohLan:v(e,"irohLan","iroh_lan"),irohRelay:v(e,"irohRelay","iroh_relay"),ble:v(e,"ble"),moq:v(e,"moq")};return Object.values(t).some(n=>n!==void 0)?t:void 0}function Ht(r){return (r.discoveryMode??"space")==="space"&&typeof r.apiKey=="string"&&r.apiKey.trim().length>0&&typeof r.spaceKey=="string"&&r.spaceKey.trim().length>0}function Kt(r,e,t){return t?true:(typeof r.appTag=="string"?r.appTag:typeof r.tag=="string"?r.tag:void 0)===e}function qe(r,e){let t=Ke(r),n=m(t,"deviceId","device_id")||e||"",i=m(t,"nodeId","node_id")||"",s=m(t,"ticket")||"";return {deviceId:n,deviceName:m(t,"deviceName","device_name")||"Unknown Device",online:!!t.online,ticket:s,friendTicket:m(t,"friendTicket","friend_ticket"),presenceStatus:je(m(t,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:v(t,"presenceUpdatedAt","presence_updated_at")??ze(t.presenceUpdatedAt,t.presence_updated_at,t.lastSeenAt,t.last_seen_at,t.updatedAt,t.updated_at,t.createdAt,t.created_at),presenceExpiresAt:v(t,"presenceExpiresAt","presence_expires_at")??x(t.presenceExpiresAt??t.presence_expires_at)??x(t.expiresAt??t.expires_at),connectable:H(t,"connectable"),kind:m(t,"kind"),nodeId:i||void 0,platformType:m(t,"platformType","platform_type"),capabilities:t.capabilities||void 0,sessionId:m(t,"sessionId","session_id"),userId:m(t,"userId","user_id"),lastSeenAt:t.lastSeenAt??t.last_seen_at,expiresAt:t.expiresAt??t.expires_at,createdAt:t.createdAt??t.created_at,updatedAt:t.updatedAt??t.updated_at,metadata:m(t,"metadata"),excludedPeers:$e(t.excludedPeers??t.excluded_peers),availableTransports:oe(t.availableTransports??t.available_transports),transports:oe(t.transports)}}function $e(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"):[]}function Di(r){let e=Ut(r);return {...r,...e,connectionStatus:"connectionStatus"in r&&typeof r.connectionStatus=="string"?r.connectionStatus:r.online?"online":"disconnected",settledReady:"settledReady"in r&&typeof r.settledReady=="boolean"?r.settledReady:false,readinessState:"readinessState"in r&&typeof r.readinessState=="string"?r.readinessState:void 0,readinessReason:"readinessReason"in r&&typeof r.readinessReason=="string"?r.readinessReason:void 0,peerHealth:"peerHealth"in r&&typeof r.peerHealth=="string"?r.peerHealth:"unknown",peerId:"peerId"in r&&typeof r.peerId=="string"?r.peerId:void 0,promotionEligible:"promotionEligible"in r&&typeof r.promotionEligible=="boolean"?r.promotionEligible:true,scopes:"scopes"in r?$e(r.scopes):[],connectionId:"connectionId"in r&&typeof r.connectionId=="string"?r.connectionId:void 0,deviceIdHint:"deviceIdHint"in r&&typeof r.deviceIdHint=="string"?r.deviceIdHint:void 0,activeTransportStableId:"activeTransportStableId"in r&&typeof r.activeTransportStableId=="number"?r.activeTransportStableId:"activeTransportStableId"in r?r.activeTransportStableId??null:void 0,transportGeneration:"transportGeneration"in r&&typeof r.transportGeneration=="number"?r.transportGeneration:void 0,routeGeneration:"routeGeneration"in r&&typeof r.routeGeneration=="number"?r.routeGeneration:void 0,activeTransport:"activeTransport"in r?r.activeTransport:void 0,parallelTransport:"parallelTransport"in r?r.parallelTransport:void 0,availableTransports:"availableTransports"in r?oe(r.availableTransports):"transports"in r?oe(r.transports):void 0,latencyMs:"latencyMs"in r&&typeof r.latencyMs=="number"?r.latencyMs:void 0,latencyByTransport:"latencyByTransport"in r?Gt(r.latencyByTransport):void 0}}function se(r,e){return e===void 0?true:e===null?r==null:r==null||r===e}function zt(r,e){let t=se(r.connectionId,e.connectionId)&&se(r.nodeId,e.nodeId)&&se(r.activeTransportStableId,e.activeTransportStableId)&&se(r.transportGeneration,e.transportGeneration)&&se(r.routeGeneration,e.routeGeneration),n=(i,s)=>i!==void 0?i:t?s:void 0;return {inheritsSnapshot:t,fields:{connectionId:n(e.connectionId??void 0,r.connectionId),activeTransportStableId:n(e.activeTransportStableId,r.activeTransportStableId),transportGeneration:n(e.transportGeneration,r.transportGeneration),routeGeneration:n(e.routeGeneration,r.routeGeneration),activeTransport:n(e.activeTransport,r.activeTransport),parallelTransport:n(e.parallelTransport,r.parallelTransport),latencyMs:t?r.latencyMs:void 0,latencyByTransport:t?r.latencyByTransport:void 0}}}var Ti={connectionId:void 0,activeTransportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function Ci(r,e,t){let n=zt(r,{connectionId:e.activeConnectionId,nodeId:e.nodeId,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),i=t?t({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):r.promotionEligible??true;if(!i)return {...r,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:i,scopes:e.scopes?.length?[...e.scopes]:r.scopes,nodeId:e.nodeId===void 0?r.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...n.fields,readinessReason:e.readinessReason??r.readinessReason};let s=e.status??r.connectionStatus,o=typeof s=="string"?s.trim().toLowerCase():"",a=o==="failed"||o==="closed"||o==="disconnected",l=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,d=r.settledReady===true||r.readinessState==="routable";if(n.inheritsSnapshot&&d&&!a&&!l)return {...r,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:i,scopes:e.scopes?.length?[...e.scopes]:r.scopes,nodeId:e.nodeId===void 0?r.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...n.fields,readinessReason:e.readinessReason??r.readinessReason};let u=a?false:l,h=l&&!a&&(o==="connecting"||o==="connected")?"connected":s,p=l?"routable":e.readinessState??(n.inheritsSnapshot?r.readinessState:void 0),f=u?e.readinessReason??"peer-session-settled":e.readinessReason??(n.inheritsSnapshot?r.readinessReason:void 0);return {...r,connectionStatus:h,settledReady:u,readinessState:p,readinessReason:f,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:i,scopes:e.scopes?.length?[...e.scopes]:r.scopes,nodeId:e.nodeId===void 0?r.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...n.fields}}function Ei(r,e){let t=zt(r,{connectionId:e.connectionId,nodeId:e.nodeId,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport});if(e.promotionEligible===false)return {...r,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:false,nodeId:e.nodeId??r.nodeId,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:r.scopes};let n=e.status??r.connectionStatus,i=typeof n=="string"?n.trim().toLowerCase():"",s=i==="failed"||i==="closed"||i==="disconnected",o=r.settledReady===true||r.readinessState==="routable",a=e.routable===false;if(t.inheritsSnapshot&&o&&s&&!a)return {...r,peerHealth:r.peerHealth??e.health,peerId:r.peerId??e.peerId,promotionEligible:e.promotionEligible??r.promotionEligible??true,connectionId:r.connectionId??e.connectionId,deviceIdHint:r.deviceIdHint??e.deviceIdHint,scopes:r.scopes?.length?r.scopes:e.scopes??r.scopes};if(o&&s)return {...r,connectionStatus:n,settledReady:false,readinessState:void 0,readinessReason:e.error??r.readinessReason,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:e.promotionEligible??r.promotionEligible??true,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...Ti,scopes:e.scopes?.length?[...e.scopes]:r.scopes};let c=e.routable===true||e.protocolState==="routable";if(t.inheritsSnapshot&&o&&!s&&!c)return {...r,peerHealth:r.peerHealth??e.health,peerId:r.peerId??e.peerId,promotionEligible:e.promotionEligible??r.promotionEligible??true,connectionId:r.connectionId??e.connectionId,deviceIdHint:r.deviceIdHint??e.deviceIdHint,activeTransportStableId:r.activeTransportStableId??e.activeTransportStableId,transportGeneration:r.transportGeneration??e.transportGeneration,routeGeneration:r.routeGeneration??e.routeGeneration,activeTransport:r.activeTransport??e.activeTransport,parallelTransport:r.parallelTransport===void 0?e.parallelTransport:r.parallelTransport,scopes:r.scopes?.length?r.scopes:e.scopes??r.scopes};let l=e.transportState==="connected"&&e.health==="healthy",d=s?false:c,u=!s&&(c||l)&&(i==="connecting"||i==="connected"||e.transportState==="connected")?"connected":n,h=d?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(t.inheritsSnapshot?r.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),p=d?(t.inheritsSnapshot?r.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(t.inheritsSnapshot?r.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...r,connectionStatus:u,settledReady:d,readinessState:h,readinessReason:p,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:e.promotionEligible??r.promotionEligible??true,nodeId:e.nodeId??r.nodeId,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:r.scopes}}function Ai(r){let{device:e,session:t=null,peer:n=null,isPromotionEligible:i}=r,s=Di(e);return t&&(s=Ci(s,t,i)),n&&(s=Ei(s,n)),s}function jt(r){let e=Ke(r),t=qe(e),n=je(m(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),i=Ut({...t,...n?{presenceStatus:n}:{},presenceUpdatedAt:v(e,"presenceUpdatedAt","presence_updated_at")??ze(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:v(e,"presenceExpiresAt","presence_expires_at")??x(e.presenceExpiresAt??e.presence_expires_at)??x(e.expiresAt??e.expires_at),connectable:H(e,"connectable")}),s={...t,...i,connectionStatus:m(e,"connectionStatus","connection_status")||"disconnected",settledReady:H(e,"settledReady","settled_ready")??false,readinessState:m(e,"readinessState","readiness_state")??void 0,readinessReason:m(e,"readinessReason","readiness_reason")??void 0,peerHealth:m(e,"peerHealth","peer_health")||"unknown",peerId:m(e,"peerId","peer_id"),scopes:$e(e.scopes),connectionId:m(e,"connectionId","connection_id"),deviceIdHint:m(e,"deviceIdHint","device_id_hint"),activeTransportStableId:v(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:v(e,"transportGeneration","transport_generation")??void 0,routeGeneration:v(e,"routeGeneration","route_generation")??void 0,activeTransport:J(e,"activeTransport","active_transport"),parallelTransport:J(e,"parallelTransport","parallel_transport")??null,availableTransports:oe(e.availableTransports??e.available_transports),latencyMs:v(e,"latencyMs","latency_ms"),latencyByTransport:Gt(e.latencyByTransport??e.latency_by_transport)};return Ai({device:s})}function qt(r){let e=Ke(r);return {peerId:m(e,"peerId","peer_id")||"",deviceId:m(e,"deviceId","device_id"),deviceIdHint:m(e,"deviceIdHint","device_id_hint"),nodeId:m(e,"nodeId","node_id"),activeConnectionId:m(e,"activeConnectionId","active_connection_id"),candidateConnectionIds:Array.isArray(e.candidateConnectionIds)?e.candidateConnectionIds.filter(t=>typeof t=="string"):Array.isArray(e.candidate_connection_ids)?e.candidate_connection_ids.filter(t=>typeof t=="string"):[],status:m(e,"status")||"disconnected",health:m(e,"health")||"unknown",settledReady:H(e,"settledReady","settled_ready")??false,readinessState:m(e,"readinessState","readiness_state")??void 0,activeTransportStableId:v(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:v(e,"transportGeneration","transport_generation")??void 0,routeGeneration:v(e,"routeGeneration","route_generation")??void 0,activeTransport:J(e,"activeTransport","active_transport"),parallelTransport:J(e,"parallelTransport","parallel_transport")??null,replacementPending:H(e,"replacementPending","replacement_pending")??void 0,lastLifecycleTransitionAtMs:v(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:m(e,"readinessReason","readiness_reason")??void 0,transitionCount:v(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:v(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:v(e,"replacementCount","replacement_count")??void 0,retireCount:v(e,"retireCount","retire_count")??void 0,lastDisconnectReason:m(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:m(e,"lastReconnectReason","last_reconnect_reason")??void 0,scopes:Array.isArray(e.scopes)?e.scopes.filter(t=>typeof t=="string"):[],lastSeenAtMs:typeof e.lastSeenAtMs=="number"?e.lastSeenAtMs:typeof e.last_seen_at_ms=="number"?e.last_seen_at_ms:0,error:m(e,"error")}}function Or(r){let e=Y(r);return {connectionId:typeof e.connectionId=="string"?e.connectionId:"",nodeId:typeof e.nodeId=="string"?e.nodeId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,endpointId:typeof e.endpointId=="string"?e.endpointId:null,transportGeneration:typeof e.transportGeneration=="number"?e.transportGeneration:0,routeGeneration:typeof e.routeGeneration=="number"?e.routeGeneration:void 0,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof e.lastRouteChangeAtMs=="number"?e.lastRouteChangeAtMs:void 0,state:typeof e.state=="string"?e.state:"pending",statusReason:typeof e.statusReason=="string"?e.statusReason:null,transitionCount:typeof e.transitionCount=="number"?e.transitionCount:void 0,connectingTransitionCount:typeof e.connectingTransitionCount=="number"?e.connectingTransitionCount:void 0,replacementCount:typeof e.replacementCount=="number"?e.replacementCount:void 0,retireCount:typeof e.retireCount=="number"?e.retireCount:void 0,lastDisconnectReason:typeof e.lastDisconnectReason=="string"?e.lastDisconnectReason:void 0,lastReconnectReason:typeof e.lastReconnectReason=="string"?e.lastReconnectReason:void 0,createdAtMs:typeof e.createdAtMs=="number"?e.createdAtMs:0,updatedAtMs:typeof e.updatedAtMs=="number"?e.updatedAtMs:0}}function Fr(r){let e=Y(r);return {peerId:typeof e.peerId=="string"?e.peerId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,nodeId:typeof e.nodeId=="string"?e.nodeId:null}}function ki(r){switch(r){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function $t(r){let e=r.activeConnectionId||r.candidateConnectionIds[0]||null;if(!e)return null;let t=ki(r.status),n=t==="connected"?"connected":t==="connecting"?"connecting":"closed",i=t==="connected"?r.settledReady?"routable":"transport-only":t==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.nodeId??null,state:t,transportState:n,protocolState:i,routable:!!r.settledReady,readinessState:r.readinessState,readinessReason:r.readinessReason,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,activeTransportStableId:r.activeTransportStableId,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport??null,replacementInProgress:r.replacementPending,lastLifecycleTransitionAtMs:r.lastLifecycleTransitionAtMs,transitionCount:r.transitionCount,connectingTransitionCount:r.connectingTransitionCount,replacementCount:r.replacementCount,retireCount:r.retireCount,lastDisconnectReason:r.lastDisconnectReason??void 0,lastReconnectReason:r.lastReconnectReason??void 0,updatedAt:r.lastSeenAtMs,error:r.error??void 0}}function Vt(r){let e=Y(r),t=m(e,"connectionId","connection_id");if(!t)return null;let n=m(e,"state")||"connecting",i=v(e,"createdAt","created_at")??v(e,"updatedAt","updated_at")??Date.now(),s=v(e,"updatedAt","updated_at")??i;return {connectionId:t,deviceId:m(e,"deviceId","device_id"),deviceIdHint:m(e,"deviceIdHint","device_id_hint"),remoteNodeId:m(e,"remoteNodeId","remote_node_id"),state:n,transportState:m(e,"transportState","transport_state")??(n==="connected"?"connected":n==="connecting"?"connecting":"closed"),protocolState:m(e,"protocolState","protocol_state")??(n==="connected"?"routable":n==="connecting"?"connecting":"closed"),routable:H(e,"routable")??false,readinessState:m(e,"readinessState","readiness_state")??void 0,readinessReason:m(e,"readinessReason","readiness_reason")??void 0,transportGeneration:v(e,"transportGeneration","transport_generation")??void 0,routeGeneration:v(e,"routeGeneration","route_generation")??void 0,activeTransportStableId:v(e,"activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:J(e,"activeTransport","active_transport"),parallelTransport:J(e,"parallelTransport","parallel_transport")??null,replacementInProgress:H(e,"replacementInProgress","replacement_in_progress")??void 0,lastLifecycleTransitionAtMs:v(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:v(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:v(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:v(e,"replacementCount","replacement_count")??void 0,retireCount:v(e,"retireCount","retire_count")??void 0,lastDisconnectReason:m(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:m(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:m(e,"error")??void 0,createdAt:i,updatedAt:s}}function Yt(r,e){return r?r.connectionId===e.connectionId&&(r.deviceId??null)===(e.deviceId??null)&&(r.deviceIdHint??null)===(e.deviceIdHint??null)&&(r.remoteNodeId??null)===(e.remoteNodeId??null)&&r.state===e.state&&(r.transportState??null)===(e.transportState??null)&&(r.protocolState??null)===(e.protocolState??null)&&!!r.routable==!!e.routable&&(r.activeTransport??null)===(e.activeTransport??null)&&(r.parallelTransport??null)===(e.parallelTransport??null)&&(r.activeTransportStableId??null)===(e.activeTransportStableId??null)&&(r.transportGeneration??null)===(e.transportGeneration??null)&&(r.routeGeneration??null)===(e.routeGeneration??null)&&!!r.replacementInProgress==!!e.replacementInProgress&&(r.transitionCount??null)===(e.transitionCount??null)&&(r.connectingTransitionCount??null)===(e.connectingTransitionCount??null)&&(r.replacementCount??null)===(e.replacementCount??null)&&(r.retireCount??null)===(e.retireCount??null)&&(r.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(r.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(r.error??null)===(e.error??null):false}function _i(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,n=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(n));let i=globalThis.Buffer;if(i)return JSON.parse(i.from(n,"base64").toString("utf8"))}catch{return null}return null}function Mi(r){let e=typeof r=="string"?r.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),n=t>=0?e.slice(0,t):e,i=t>=0?e.slice(t+1):null,s=i?_i(i):null,o=s&&typeof s.t=="string"&&s.t.trim().length>0?s.t.trim():null,a=s&&typeof s.s=="string"&&s.s.trim().length>0?s.s.trim():null,c=s&&typeof s.m=="number"&&Number.isFinite(s.m)?s.m:null;return {present:true,irohFingerprint:M(n),tokenFingerprint:M(o),tokenSuffixFingerprint:M(i),scope:a,maxConnections:c}}function ae(r,e,t={}){let n=typeof r.finishSend=="function"?r.finishSend.bind(r):typeof r.finish_send=="function"?r.finish_send.bind(r):null;if(!n){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let i=e.getWriter();return new WritableStream({write:s=>i.write(s),async close(){await i.close(),await n();},abort:s=>i.abort(s)})}var S=class S{constructor(e){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this._rtdbPresence=null;this.rtdbPresenceScope=null;this.rtdbTicketVersion=0;this.rtdbPresenceDisabledForSession=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationUnsubscribe=null;this.applicationRouteEscalationSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;try{let n=typeof import.meta<"u"?import.meta.env:null;if(!!n&&String(n.VITE_USE_EMULATORS)==="true"&&(n.DEV||String(n.VITE_E2E)==="true")){let s=String(n.VITE_OPENRTC_FIRESTORE_EMULATOR_HOST||"").trim()||"127.0.0.1:8082";globalThis.__OPENRTC_FIRESTORE_EMULATOR_HOST__=s;}}catch{}if(this.appTag=b(e),this.options={...e,appTag:this.appTag,authMode:c(e),projectId:d(e)},this.presenceManager=new Pe({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(n,i)=>this.waitForWasmClient(n,i),warnMissingWasmOnce:n=>this.warnMissingWasmOnce(n),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(n,i)=>this.withWebPresenceMetadata(n,i),updatePresence:(n,i,s,o,a,c)=>this.updatePresence(n,i,s,o,a,c),buildRtdbScope:n=>this.buildRtdbScope(n),resolveRtdbScope:n=>this.resolveRtdbScope(n),registerRtdbPresence:(n,i,s,o)=>this.registerRtdbPresence(n,i,s,o),isRtdbPresenceDisabledForSession:()=>this.rtdbPresenceDisabledForSession,getRtdbTicketVersion:()=>this.rtdbTicketVersion,getBrowserFirestoreSignaling:()=>this.getBrowserFirestoreSignaling(),rememberRouteRepairTokenFromTicket:n=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(n)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations()}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()){this.app=null,this.auth=null;return}let t=G();this.app=t.getApp(),this.auth=t.getAuth(),t.onAuthStateChanged(n=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(o=>o(this.toRuntimeIdentity(n)));return}let i=n?.uid??null,s=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=i,s&&s!==i&&this.stopAuthScopedActivity({userId:s}),this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(o=>o(this.toRuntimeIdentity(n)));});}get rtdbPresence(){return this._rtdbPresence}get tag(){return this.appTag}getRuntimeCapabilities(){return he()}getDeviceIdentityStorageKey(){let e$1=e(this.options);return `${S.WEB_DEVICE_ID_STORAGE_PREFIX}_${e$1}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let n=this.getDeviceIdentityStorageKey(),i=Date.now(),s=null;try{let d=localStorage.getItem(n);s=d?JSON.parse(d):null;}catch{s=null;}let o=typeof s?.deviceId=="string"?s.deviceId.trim():"",a=typeof s?.expiresAt=="number"?s.expiresAt:void 0;if(t==="persistent"){let d=o||this.createRandomDeviceId();return localStorage.setItem(n,JSON.stringify({deviceId:d})),d}if(o&&typeof a=="number"&&a>i){let d=i+S.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:o,expiresAt:d})),o}let c=this.createRandomDeviceId(),l=i+S.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:c,expiresAt:l})),c}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}getBrowserFirestoreSignaling(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Browser signaling is disabled when signalingMode="ticket-only".');return this.browserCoordinationSignaling||(this.browserCoordinationSignaling=this.options.coordinationGateway?new Re({app:this.app,gateway:this.options.coordinationGateway,appTag:this.appTag,discoveryMode:this.options.discoveryMode,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(e,t)=>this.normalizeDevice(e,t)}):new we({app:this.app,auth:this.auth,appTag:this.appTag,apiKey:this.options.apiKey,spaceKey:this.options.spaceKey,discoveryMode:this.options.discoveryMode,getCurrentUserId:()=>this.getCurrentUserId(),getDiscoveryScopeId:()=>this.getDiscoveryScopeId(),getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),matchesTag:e=>this.matchesTag(e),normalizeDevice:(e,t)=>this.normalizeDevice(e,t)})),this.browserCoordinationSignaling}usesCoordinationGateway(){return !!this.options.coordinationGateway}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}async joinCoordinationRoom(e,t,n){let i=this.getBrowserFirestoreSignaling();if(!i.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await i.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){await this.getBrowserFirestoreSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getBrowserFirestoreSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let n=this.getBrowserFirestoreSignaling();if(!n.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return n.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let n;if(!e||!e.trim())n=JSON.stringify({deviceId:t});else {try{let i=JSON.parse(e);if(i&&typeof i=="object"&&!Array.isArray(i))return n=JSON.stringify({...i,deviceId:t}),await He(n)??n}catch{}n=JSON.stringify({deviceId:t,metadata:e});}return await He(n)??n}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive;if(this.authContext=e,!this.isTicketOnlyMode()&&e?.customToken?.trim())try{await this.ensureBrowserFirestoreAuth(e.userId,e.customToken.trim());}catch(n){console.warn("[WasmBridge] ensureBrowserFirestoreAuth failed (non-fatal):",n);}else if(!this.isTicketOnlyMode()&&!e&&t)try{await this.auth?.signOut();}catch(n){console.warn("[WasmBridge] Failed to clear injected browser auth session:",n);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(n=>n(this.currentUser));}async ensureBrowserFirestoreAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await G().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){if(!this.wasmClient||typeof this.wasmClient.set_auth_token!="function"||!this.authContext&&this.isSpaceMode())return;let e=this.authContext?.userId??null,t=this.authContext?.token??null;this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===e&&this.lastWasmAuthToken===t||(this.lastWasmAuthUserId=e,this.lastWasmAuthToken=t,this.hasSyncedAuthToWasmClient=true,this.wasmClient.set_auth_token(t));}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return Ht(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return Kt(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}disableRtdbPresenceForSession(e,t){this.rtdbPresenceDisabledForSession||console.warn(`[WasmBridge] Disabling RTDB presence for this browser session (${e})`,t),this.rtdbPresenceDisabledForSession=true,this.rtdbPresenceScope=null,this.browserCoordinationSignaling?.stopRtdbPresence();}async registerRtdbPresence(e,t,n,i){if(this.isTicketOnlyMode()||this.options.coordinationGateway)return;if(!this._rtdbPresence)try{this._rtdbPresence=new ge(this.app);}catch(c){throw this.disableRtdbPresenceForSession("RTDB service unavailable",c),c}this.rtdbPresenceScope=e;let s=n??this.rtdbTicketVersion,o=this.getBrowserFirestoreSignaling(),a=o.setRtdbPresence;if(a){a.call(o,this._rtdbPresence,e);try{await this._rtdbPresence.registerDevice(e,t,s,i);}catch(c){throw c}}}buildRtdbPresenceFields(e,t,n,i){return {ticket:t,nodeId:e,deviceName:i?.trim()||this.getDefaultBrowserDeviceName(),platformType:"web",metadata:n}}async refreshRtdbPresenceTicket(e,t,n,i){if(this.isTicketOnlyMode()||this.rtdbPresenceDisabledForSession||this.options.coordinationGateway)return;let s=this.resolveWebLogicalDeviceId();if(!s)return;let o=this.rtdbPresenceScope??await this.resolveRtdbScope(this.getCurrentUserId()??void 0);if(!o)return;this.rtdbTicketVersion+=1;let a=this.rtdbTicketVersion,c=this.buildRtdbPresenceFields(e,t,n,i);if(this._rtdbPresence&&this.rtdbPresenceScope){await this._rtdbPresence.bumpTicketVersion(o,s,a,c);return}await this.registerRtdbPresence(o,s,a,c);}async stopAuthScopedActivity(e){dt("WasmBridge.stopAuthScopedActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(n){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",n);}this.presenceManager.stop(),this.rtdbPresenceDisabledForSession=false,this.rtdbPresenceScope=null,this.rtdbTicketVersion=0,this.browserCoordinationSignaling?.stopAuthScopedActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.hasSyncedAuthToWasmClient=false,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.syncWasmAuthToken();}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let n=Date.now();for(;!this.wasmClient&&Date.now()-n<e;)await u(t);return this.wasmClient??null}normalizeDevice(e,t){return qe(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}normalizeDeviceStatusSnapshot(e){return jt(e)}normalizePeerSessionSnapshot(e){return qt(e)}toBackendConnectionStateFromPeerSession(e){return $t(e)}normalizeConnectionStateSnapshot(e){return Vt(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return Yt(e,t)}deliverConnectionState(e,t,n,i){let s=this.stabilizeConnectionState(e);this.escalateManagedApplicationRoute(s),this.lastDeliveredConnectionStates.set(s.connectionId,s);let a=(i??this.lastDeliveredConnectionStates).get(s.connectionId);this.sameConnectionState(a,s)||(i&&i.set(s.connectionId,s),t(s));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(n=false)=>{if(e&&(!n||!t))return e;if(t)try{let s=await t(n);if(s)return s}catch{}let i=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(i&&i.uid===this.authContext?.userId)try{return await i.getIdToken(n)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||await G().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await G().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await G().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await G().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthScopedActivity({userId:e}),this.authContext=null,this.hasSyncedAuthToWasmClient=false,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,n=true,i=3e5,s,o){if(this.isTicketOnlyMode())return;let a=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?S.EPHEMERAL_DEVICE_ID_TTL_MS:i,l=await this.withWebPresenceMetadata(s,a);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:l,deviceName:o?.trim()||this.getDefaultBrowserDeviceName()}),await this.getBrowserFirestoreSignaling().updatePresence(e,t,n,c,l,o),await this.refreshRtdbPresenceTicket(e,t,l,o);}async refreshLivePresence(e,t,n,i){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),o=await this.withWebPresenceMetadata(n,s);if(this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:o,deviceName:i?.trim()||this.getDefaultBrowserDeviceName()}),this.options.coordinationGateway){await this.getBrowserFirestoreSignaling().updatePresence(e,t,true,3e5,o,i);return}await this.refreshRtdbPresenceTicket(e,t,o,i);}async setOffline(e){if(this.presenceManager.stopPresence(),!this.isTicketOnlyMode()){if(this._rtdbPresence&&this.rtdbPresenceScope){let t=this.resolveWebLogicalDeviceId();t&&await this._rtdbPresence.markOffline(this.rtdbPresenceScope,t,this.rtdbTicketVersion).catch(n=>console.warn("[WasmBridge] RTDB markOffline failed:",n));}await this.getBrowserFirestoreSignaling().setOffline(e);}}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().cleanupStaleDevices();}async sendMessage(e,t,n,i){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getBrowserFirestoreSignaling().sendMessage(e,t,n,i)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getBrowserFirestoreSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getBrowserFirestoreSignaling().searchDevices(e)}async listDevicesWithStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getBrowserFirestoreSignaling().listDevices(),n=this.wasmClient;return Promise.all(t.map(async i=>{let s=this.normalizeDeviceStatusSnapshot({...i,connectionStatus:i.online?"online":"disconnected"}),o=typeof i.nodeId=="string"?i.nodeId.trim():"";if(!o||typeof n?.iroh_path_kind!="function"||typeof n?.iroh_transport_rtt_ms!="function")return s;try{let[a,c]=await Promise.all([n.iroh_path_kind(o),n.iroh_transport_rtt_ms(o)]);if(typeof c!="number"||!Number.isFinite(c))return s;let l=Math.max(0,Math.round(c)),d={};if(a==="direct-lan")d.irohLan=l;else if(a==="direct-quic")d.iroh=l;else if(a==="ble")d.ble=l;else if(a==="relay")d.irohRelay=l;else return s;return {...s,latencyMs:l,latencyByTransport:d}}catch(a){return ue("[WasmBridge] iroh transport latency unavailable",{deviceId:i.deviceId,error:a instanceof Error?a.message:String(a)}),s}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let n=await t.peer_session(e);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(i=>this.normalizePeerSessionSnapshot(i)).filter(i=>!!(i.peerId||i.deviceId||i.deviceIdHint||i.nodeId||i.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.wait_for_settled_peer=="function"){let i=await n.wait_for_settled_peer(e,t);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.open_peer_bi=="function"){let i=await n.open_peer_bi(e,t);if(!i?.recv||!i?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:i.recv,writable:ae(i,i.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerNativeBi(e,t,n){let i=await this.waitForWasmClient(500),s=i&&i.open_peer_native_bi;if(typeof s=="function"){let o=await s.call(i,e,t,n);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_native_bi returned an invalid bidirectional stream");return {readable:o.recv,writable:ae(o,o.send)}}throw this.warnMissingWasmOnce("openPeerNativeBi"),new Error("WASM runtime does not support open_peer_native_bi()")}async openPeerBiTransportOnly(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiTransportOnly is debug-only and cannot be used when application crypto is required");let n=await this.waitForWasmClient(500),i=n&&typeof n.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiTransportOnly",{peerId:e,hasWasmClient:!!n,hasTransportOnly:i,timeoutMs:t}),i){let s=await n.open_peer_bi_transport_only(e,t);if(!s?.recv||!s?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:s.recv,writable:ae(s,s.send)}}return console.debug("[WasmBridge] openPeerBiTransportOnly falling back to openPeerBi",{peerId:e}),this.openPeerBi(e,t)}async openPeerUni(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.open_peer_uni=="function"){let i=await n.open_peer_uni(e,t),s=i?.writable??i;if(!s)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:ae(i,s)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}async resolvePeerConnectionRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let n=await t.resolve_peer_connection_records(e);return (Array.isArray(n)?n:[]).map(i=>({connectionId:typeof i.connectionId=="string"?i.connectionId:"",nodeId:typeof i.nodeId=="string"?i.nodeId:null,deviceId:typeof i.deviceId=="string"?i.deviceId:null,deviceIdHint:typeof i.deviceIdHint=="string"?i.deviceIdHint:null,endpointId:typeof i.endpointId=="string"?i.endpointId:null,transportGeneration:typeof i.transportGeneration=="number"?i.transportGeneration:0,routeGeneration:typeof i.routeGeneration=="number"?i.routeGeneration:void 0,transportStableId:typeof i.transportStableId=="number"?i.transportStableId:null,transportSource:typeof i.transportSource=="string"?i.transportSource:null,lastTransportChangeAtMs:typeof i.lastTransportChangeAtMs=="number"?i.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof i.lastRouteChangeAtMs=="number"?i.lastRouteChangeAtMs:void 0,state:typeof i.state=="string"?i.state:"pending",statusReason:typeof i.statusReason=="string"?i.statusReason:null,createdAtMs:typeof i.createdAtMs=="number"?i.createdAtMs:0,updatedAtMs:typeof i.updatedAtMs=="number"?i.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerConnectionRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let n=i=>{if(!i||typeof i!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let s=i;return {peerId:typeof s.peerId=="string"?s.peerId:null,deviceId:typeof s.deviceId=="string"?s.deviceId:null,deviceIdHint:typeof s.deviceIdHint=="string"?s.deviceIdHint:null,nodeId:typeof s.nodeId=="string"?s.nodeId:null}};if(typeof t.peer_session=="function")try{let i=await t.peer_session(e),s=n(i);if(s.peerId||s.deviceId||s.deviceIdHint||s.nodeId)return s}catch{}if(typeof t.peer_snapshot=="function")try{return n(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getBrowserFirestoreSignaling().onDevicesChange(e,t)}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getBrowserFirestoreSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let n=this.authScopedRuntimeGeneration;try{let i=await this.waitForWasmClient();if(n!==this.authScopedRuntimeGeneration||!i||typeof i.start_auto_connect!="function")return;await i.start_auto_connect(e,t),n===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(i){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:i});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnectSnapshot();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async setAutoConnectExcluded(e,t){await this.presenceManager.setAutoConnectExcluded(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.setAutoConnectExcluded(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(n){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:n?.message??String(n)}),n}}setCoreClient(e){e&&typeof e.connect=="function"?(this.coreClient=e,this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.applicationRouteEscalationSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,n=this.onConnectionStateChange(()=>{});this.applicationRouteEscalationUnsubscribe=()=>{},this.applicationRouteEscalationSubscriptionGeneration=e,Promise.resolve(n).then(i=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){i();return}this.applicationRouteEscalationUnsubscribe=i,this.applicationRouteEscalationSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.applicationRouteEscalationSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state)||this.applicationRouteEscalations.has(e.connectionId)||e.remoteNodeId&&this.coreClient.hasApplicationRouteForPeer?.(e.connectionId,e.remoteNodeId)===true)return;let t=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!t?.ticket)return;let n=this.authScopedRuntimeGeneration,i=this.coreClient,s;s=(async()=>{let o=typeof i.ensureManagedApplicationRoute=="function"?await i.ensureManagedApplicationRoute({ticket:t.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??t.nodeId,expectedDeviceId:t.deviceId,timeoutMs:2e4}):await i.connect(t.ticket,2e4,t.deviceId,void 0,{admissionAlreadyPresented:true});if(n!==this.authScopedRuntimeGeneration)return;let a=o,c=a.id?.trim()||e.connectionId,l=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||t.deviceId;if(i.hasApplicationRouteForPeer?.(c,l)!==true&&i.hasApplicationRouteForPeer?.(c,l)!==true)throw new Error(`application crypto was not ready for ${l}`)})().catch(o=>{n===this.authScopedRuntimeGeneration&&console.warn("[WasmBridge][ROUTE-ESCALATION] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:t.deviceId,remoteNodeId:e.remoteNodeId??t.nodeId,error:o?.message??String(o)});}).finally(()=>{this.applicationRouteEscalations.get(e.connectionId)===s&&this.applicationRouteEscalations.delete(e.connectionId);}),this.applicationRouteEscalations.set(e.connectionId,s);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let n=Date.now();R("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:Mi(e.endpointTicket),hasCoreClient:!!this.coreClient});let i=await t.connect_device(e.deviceId??null,e.endpointTicket);R("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:i?.remoteNodeId??null,connectionId:i?.connectionId??null,elapsedMs:Date.now()-n});let s=e.endpointTicket;if(s&&this.coreClient){let o=this.coreClient;try{R("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:i?.remoteNodeId??null,connectionId:i?.connectionId??null});let a=typeof o.ensureManagedApplicationRoute=="function"?await o.ensureManagedApplicationRoute({ticket:s,connectionId:i?.connectionId??null,remoteNodeId:i?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,timeoutMs:2e4}):await o.connect(s,2e4,e.deviceId??null,void 0,{admissionAlreadyPresented:!0}),c=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():"",l=typeof a?.deviceId=="string"?a.deviceId.trim():"",d=c||i?.remoteNodeId?.trim?.()||l||e.deviceId?.trim?.()||"",u=typeof o.hasApplicationRouteForPeer=="function"?o.hasApplicationRouteForPeer.bind(o):null;if(!(!!d&&u?.(a?.id??void 0,d)===!0)&&d&&typeof o.waitForApplicationCryptoForPeer=="function"&&!(!!await o.waitForApplicationCryptoForPeer(d,2e4)&&(!u||u(a?.id??void 0,d)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:c||(i?.remoteNodeId??null),connectionId:i?.connectionId??null,peerForCrypto:d,elapsedMs:Date.now()-n}),Object.assign(new Error(`application crypto was not ready for ${d}`),{applicationCryptoNotReady:!0});R("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:c||(i?.remoteNodeId??null),connectionId:i?.connectionId??null,elapsedMs:Date.now()-n});}catch(a){if(a?.applicationCryptoNotReady)throw a;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:i?.remoteNodeId??null,connectionId:i?.connectionId??null,error:a?.message??String(a)}),i}}return i}forceReconnectSnapshot(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,n,i,s){this.presenceManager.startPresenceLoop(e,t,n,i,s);}usesSpaceScopedRtdb(){return (this.options.discoveryMode??"space")==="space"}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=a(e,t).then(n=>(this.cachedSpaceNamespaceId=n,n)).catch(()=>null);}return this.spaceNamespaceIdPromise}buildRtdbScope(e){if(this.isTicketOnlyMode())return null;let t=this.options.discoveryMode??"space",n=this.appTag;if(t==="space")return this.usesSpaceScopedRtdb()&&this.cachedSpaceNamespaceId?{kind:"space",namespaceId:this.cachedSpaceNamespaceId}:null;let i=e||this.getDiscoveryScopeId()||this.getCurrentUserId();return i?{kind:"user-scoped",appTag:n,userId:i}:null}async resolveRtdbScope(e){let t=this.buildRtdbScope(e);if(t||(this.options.discoveryMode??"space")!=="space")return t;if(!this.usesSpaceScopedRtdb())return null;let n=await this.ensureSpaceNamespaceIdPromise();return n?{kind:"space",namespaceId:n}:null}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let n={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getBrowserFirestoreSignaling().createSession(n);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getBrowserFirestoreSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getBrowserFirestoreSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"&&await t.is_connected(e)?true:this.hasConnectedIndependentPeerRoute(t,e)}async hasConnectedIndependentPeerRoute(e,t){if(!e||typeof t!="string"||t.trim().length===0)return false;let n=t.trim(),i=[];if(typeof e.peer_session=="function")try{let s=await e.peer_session(n);s&&typeof s=="object"&&i.push(this.normalizePeerSessionSnapshot(s));}catch{}if(typeof e.peer_sessions=="function")try{let s=await e.peer_sessions();Array.isArray(s)&&i.push(...s.filter(o=>!!o&&typeof o=="object").map(o=>this.normalizePeerSessionSnapshot(o)));}catch{}return i.some(s=>{let o=typeof s.peerId=="string"?s.peerId.trim():"",a=typeof s.deviceId=="string"?s.deviceId.trim():"",c=typeof s.deviceIdHint=="string"?s.deviceIdHint.trim():"",l=typeof s.nodeId=="string"?s.nodeId.trim():"";return (n===o||n===a||n===c||n===l)&&s.status==="connected"&&s.settledReady===true&&s.replacementPending!==true&&h(s.activeTransport)})}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let i=await e.connection_states(),s=(Array.isArray(i)?i:[]).map(o=>this.normalizeConnectionStateSnapshot(o)).filter(o=>!!o);return s.length>0&&ue("[WasmBridge] replaying current wasm connection states",s.map(o=>({connectionId:o.connectionId,deviceId:o.deviceId??null,deviceIdHint:o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportState:o.transportState??null,protocolState:o.protocolState??null,routable:o.routable??null}))),s}let n=(await this.listPeerSessions().catch(()=>[])).map(i=>this.toBackendConnectionStateFromPeerSession(i)).filter(i=>!!i);return n.length>0&&ue("[WasmBridge] replaying current wasm connection states",n.map(i=>({connectionId:i.connectionId,deviceId:i.deviceId??null,deviceIdHint:i.deviceIdHint??null,remoteNodeId:i.remoteNodeId??null,state:i.state,transportState:i.transportState??null,protocolState:i.protocolState??null,routable:i.routable??null}))),n}onConnectionStateChange(e){let t=new Map,n=new Map,i=this.authScopedRuntimeGeneration,s=false,o=l=>{let d=l.detail,u=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!u||s)return;let h=(n.get(u)??0)+1;n.set(u,h);let p=this.authScopedRuntimeGeneration;(async()=>{let f=this.normalizeConnectionStateSnapshot(d),g=await this.waitForWasmClient(500);if(!(s||p!==this.authScopedRuntimeGeneration||n.get(u)!==h)){if(g&&typeof g.connection_state=="function"){let b=await g.connection_state(u),y=this.normalizeConnectionStateSnapshot(b);if(!s&&p===this.authScopedRuntimeGeneration&&n.get(u)===h&&y){this.deliverConnectionState(y,e,"rust-event",t);return}}!s&&p===this.authScopedRuntimeGeneration&&n.get(u)===h&&f&&this.deliverConnectionState(f,e,"rust-event-detail",t);}})().catch(f=>{s||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:u,error:f});});},a=typeof window<"u"?window:null,c=typeof a?.addEventListener=="function"&&typeof a?.removeEventListener=="function";return c&&a.addEventListener("connection-state-changed",o),this.getConnectionStates().then(l=>{!s&&i===this.authScopedRuntimeGeneration&&l.forEach(d=>{n.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(l=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",l);}),()=>{s=true,n.clear(),c&&a.removeEventListener("connection-state-changed",o);}}async sendExplicitFilePath(e,t,n=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let n=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(o=>o.trim().length>0)?.trim()??"";if(!n||n==="."||n==="..")return S.FALLBACK_EXPLICIT_FILE_NAME;let i="";for(let o of n){if([...i].length>=S.MAX_EXPLICIT_FILE_NAME_CHARS)break;let a=o.charCodeAt(0);o==="/"||o==="\\"||o==="\0"||a<32||a===127?i+="_":i+=o;}let s=i.trim();return !s||s==="."||s===".."?S.FALLBACK_EXPLICIT_FILE_NAME:s}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return S.FALLBACK_EXPLICIT_MIME_TYPE;let n="";for(let i of t){if(n.length>=S.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let s=i.charCodeAt(0);s<33||s>126||i==='"'||i==="\\"?n+="_":n+=i;}return n.length>0?n:S.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>S.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let n=0;n<e.byteLength;n+=1)e[n]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,n,i,s){let o=s?.headerFrame===true?4:0,a=new Uint8Array(25+o+i.byteLength);a[0]=S.EXPLICIT_FILE_PROTOCOL_TYPE,a.set(e,1);let c=new DataView(a.buffer);c.setUint32(17,t,false),c.setUint32(21,n,false);let l=s?.headerFrame===true?29:25;return s?.headerFrame===true&&c.setUint32(25,i.byteLength,false),a.set(i,l),a}async sendExplicitFileData(e){let t=e.connection,n=e.file,i=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!i)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let o=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`,a=typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null,c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(R("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:n.name,fileSize:n.size,transferId:o}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let l=await this.waitForWasmClient();if(!l)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,u={transfer_id:o,filename:this.sanitizeExplicitFileName(n.name),size:n.size,mime_type:this.sanitizeExplicitMimeType(n.type)},h=d.encode(JSON.stringify(u));this.assertExplicitTransferHeaderSize(h);let p=new Uint8Array(4);new DataView(p.buffer).setUint32(0,h.byteLength,false);let f=new Uint8Array(p.byteLength+h.byteLength);f.set(p,0),f.set(h,p.byteLength);let g=async()=>{if(a!=="web"||!t||typeof t.sendOnWebRTC!="function"||typeof t.isWebRtcApplicationRouteReady!="function"||t.isWebRtcApplicationRouteReady()!==true)return a&&a!=="web"&&typeof t?.isWebRtcApplicationRouteReady=="function"&&t.isWebRtcApplicationRouteReady()===true&&R("[WasmBridge] sendExplicitFileData kept on Iroh for non-browser receiver",{remoteNodeId:c,transferId:o,receiverPlatformType:a}),false;let y=i?ct(i):null,w=O=>y?y.protectFrame(O):O,I=new Uint8Array(await n.arrayBuffer()),D=this.createWebRTCExplicitTransferId(),L=Math.max(1,Math.ceil(I.byteLength/S.EXPLICIT_FILE_CHUNK_SIZE_BYTES)),C=typeof t.getWebRTCTransport=="function"?t.getWebRTCTransport():null,N=async()=>{C&&typeof C.getBufferedAmount=="function"&&typeof C.waitForDrain=="function"&&C.getBufferedAmount()>S.EXPLICIT_FILE_CHUNK_SIZE_BYTES*4&&await C.waitForDrain(S.EXPLICIT_FILE_CHUNK_SIZE_BYTES*2);};if(await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(D,4294967295,L,w(h),{headerFrame:true})),await N(),I.byteLength===0)return await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(D,0,L,w(new Uint8Array(0)))),true;let ce=0;for(let O=0;O<I.byteLength;O+=S.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let Qt=I.slice(O,Math.min(O+S.EXPLICIT_FILE_CHUNK_SIZE_BYTES,I.byteLength));await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(D,ce,L,w(Qt))),ce+=1,await N();}return R("[WasmBridge] sendExplicitFileData sent over WebRTC explicit route",{connectionId:e.connectionId??null,remoteNodeId:c,transferId:o,chunks:L,encrypted:!!y}),true},b=async()=>{let y=l.open_peer_bi_explicit_file_sender;if(typeof y!="function")return false;let w=await y.call(l,c,5e3),I=w?.writable??w?.send;if(!I||typeof I.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");R("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let D=ae(w,I,{requireFinish:true}).getWriter(),L=false;try{await D.write(f);let C=new Uint8Array(await n.arrayBuffer());for(let N=0;N<C.byteLength;N+=S.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let ce=C.slice(N,Math.min(N+S.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await D.write(ce);}}catch(C){throw L=true,C}finally{try{await D.close();}catch(C){if(!L)throw C}finally{D.releaseLock();}}return true};try{try{if(await g())return}catch(y){R("[WasmBridge] sendExplicitFileData WebRTC explicit route failed; falling back",{remoteNodeId:c,transferId:o,error:y instanceof Error?y.message:String(y)});}if(await b())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{R("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:o,fileName:n.name,fileSize:n.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getBrowserFirestoreSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().updateFriendTicket(e);}};S.EXPLICIT_FILE_PROTOCOL_TYPE=2,S.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,S.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,S.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",S.MAX_EXPLICIT_FILE_NAME_CHARS=180,S.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",S.MAX_EXPLICIT_MIME_TYPE_CHARS=255,S.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",S.EPHEMERAL_DEVICE_ID_TTL_MS=Q.browserIdentity.ephemeralDeviceIdTtlMs;var Jt=S;var Xt=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthScopedActivity(){typeof this.backend.stopAuthScopedActivity=="function"&&await this.backend.stopAuthScopedActivity();}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,s){return this.backend.updatePresence(e,t,n,i,s)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDevicesWithStatus(){if(typeof this.backend.listDevicesWithStatus!="function")throw new Error("Selected runtime adapter does not support listDevicesWithStatus().");return this.backend.listDevicesWithStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerConnectionRecords(e){return typeof this.backend.resolvePeerConnectionRecords!="function"?[]:this.backend.resolvePeerConnectionRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}startPresenceLoop(e,t,n,i,s){this.backend.startPresenceLoop(e,t,n,i,s);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnectSnapshot(){this.backend.forceReconnectSnapshot();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateLocalDeviceName(e){return typeof this.backend.updateLocalDeviceName!="function"?null:this.backend.updateLocalDeviceName(e)}async startManagedSessionNative(e){let t=this.backend;if(typeof t.startManagedSessionNative!="function")throw new Error("Selected runtime adapter does not support startManagedSessionNative().");return t.startManagedSessionNative(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresenceLoopOnce(e,t,n,i,s){let o=this.backend;if(typeof o.startPresenceLoopOnce!="function")throw new Error("Selected runtime adapter does not support startPresenceLoopOnce().");return o.startPresenceLoopOnce(e,t,n,i,s)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getEndpointTicketWithToken(e,t){let n=this.backend;return typeof n.getEndpointTicketWithToken!="function"?null:n.getEndpointTicketWithToken(e,t)}async registerSessionToken(e,t,n){let i=this.backend;typeof i.registerSessionToken=="function"&&await i.registerSessionToken(e,t,n);}async revokeSessionTokensByScope(e){let t=this.backend;return typeof t.revokeSessionTokensByScope!="function"?[]:t.revokeSessionTokensByScope(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async is_current_transport_stable_id(e,t){let n=this.backend;return typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerNativeBi(e,t,n){let i=this.backend;if(typeof i.openPeerNativeBi!="function")throw new Error("Selected runtime adapter does not support openPeerNativeBi().");return i.openPeerNativeBi(e,t,n)}async openPeerBiTransportOnly(e,t){let n=this.backend;return typeof n.openPeerBiTransportOnly=="function"?n.openPeerBiTransportOnly(e,t):this.openPeerBi(e,t)}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}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)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}getRuntimeCapabilities(){let e=this.backend;return typeof e.getRuntimeCapabilities=="function"?e.getRuntimeCapabilities():he()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};
|
|
2
|
+
export{pn as A,lt as B,he as C,Hi as D,Ki as E,Jt as F,Xt as G,A as a,Zt as b,ue as c,R as d,xi as e,ge as f,kr as g,_r as h,Mr as i,xr as j,He as k,Ri as l,an as m,Fi as n,ct as o,dt as p,Ke as q,Ai as r,jt as s,qt as t,Or as u,Fr as v,Vt as w,Q as x,Wi as y,un as z};
|