openrtc 0.2.0 → 0.2.1

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.
Files changed (36) hide show
  1. package/LICENSE +92 -0
  2. package/README.md +51 -10
  3. package/dist/{DelegatingRuntimeAdapter-CjHzBEBA.d.ts → DelegatingRuntimeAdapter-BxOcVIx_.d.ts} +23 -2
  4. package/dist/{IpcRuntimeAdapter-CtckyMol.d.ts → IpcRuntimeAdapter-U5AEH0jn.d.ts} +6 -3
  5. package/dist/auth/index.js +1 -1
  6. package/dist/auth/internal.js +1 -1
  7. package/dist/chunk-7DN33VUQ.js +1 -0
  8. package/dist/chunk-BLOEZIFJ.js +1 -0
  9. package/dist/chunk-FQETZQPW.js +2 -0
  10. package/dist/chunk-IUHUYHNZ.js +1 -0
  11. package/dist/chunk-UBEE42VU.js +2 -0
  12. package/dist/chunk-UPO23UMZ.js +3 -0
  13. package/dist/chunk-WNJE3MJF.js +1 -0
  14. package/dist/{factories-CwZiIRg1.d.ts → framing-lxzHEuSr.d.ts} +71 -4
  15. package/dist/index.d.ts +109 -9
  16. package/dist/index.js +2 -2
  17. package/dist/openrtc_bg.wasm +0 -0
  18. package/dist/runtime/WasmRuntimeAdapter.d.ts +2 -2
  19. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  20. package/dist/runtime/index.d.ts +14 -7
  21. package/dist/runtime/index.js +1 -1
  22. package/dist/runtime/tauri.d.ts +3 -3
  23. package/dist/runtime/tauri.js +1 -1
  24. package/dist/transport/index.d.ts +1 -1
  25. package/dist/transport/index.js +1 -1
  26. package/dist/{types-DyCGvj9l.d.ts → types-D0fRvUbN.d.ts} +31 -10
  27. package/env/index.d.ts +64 -0
  28. package/env/index.mjs +230 -0
  29. package/package.json +19 -10
  30. package/dist/chunk-3VTF5RKW.js +0 -1
  31. package/dist/chunk-JXGKO7SX.js +0 -1
  32. package/dist/chunk-MFT6SOZ6.js +0 -3
  33. package/dist/chunk-SGZWR63E.js +0 -1
  34. package/dist/chunk-VARALO7G.js +0 -1
  35. package/dist/chunk-WOHFM6DI.js +0 -2
  36. package/dist/chunk-YHJOXD46.js +0 -2
@@ -0,0 +1 @@
1
+ import {c,e,d,D as D$1,f,r,b,t,B,u}from'./chunk-FQETZQPW.js';import {f as f$1,b as b$1}from'./chunk-BLOEZIFJ.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';import {getFirestore,connectFirestoreEmulator,getDoc,serverTimestamp as serverTimestamp$1,setDoc,updateDoc,deleteDoc,collection,doc,getDocs,query,where,limit,onSnapshot,getDocFromServer}from'firebase/firestore';import {httpsCallable,getFunctions}from'firebase/functions';import {getDatabase,connectDatabaseEmulator,onValue,ref,onDisconnect,set,onChildAdded,onChildChanged,onChildRemoved,serverTimestamp,get}from'firebase/database';function It(){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 ge(r,e,t){if(It()){if(typeof t>"u"){console[r](e);return}console[r](e,t);}}function ve(r,e){ge("debug",r,e);}function D(r,e){ge("info",r,e);}function A(r,e){ge("log",r,e);}var N=new Uint8Array([79,82,84,67,69,49]),ee=2,x=8,$=24,He=32,wt=3,Ct=16*1024*1024,Rt=4096;function Dt(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 At(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 Tt(r,e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return `${r}:${t}`}function Ge(r){if(!Dt(r,N))return null;let e=r[N.byteLength];return e===ee?e:null}function Pt(r){return Ge(r)===ee&&r.byteLength>N.byteLength+1+x+$}function gn(r,e={}){if(!(r instanceof Uint8Array)||r.byteLength!==He)throw new Error(`[OpenRTC] application payload crypto key must be ${He} bytes`);let t=new Uint8Array(r),n=e.requireEncrypted??true,i=e.randomBytes??At,s=e.replayProtection??true,o=0,a=new Set,c=[];return {requireEncrypted:n,protectPayload(l,d){let u=i($);if(!(u instanceof Uint8Array)||u.byteLength!==$)throw new Error(`[OpenRTC] application payload crypto nonce must be ${$} bytes`);let p=new Uint8Array(1+d.byteLength);p[0]=l,p.set(d,1);let h=xchacha20poly1305(t,u).encrypt(p);if(!s)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let f=new Uint8Array(N.byteLength+1+x+u.byteLength+h.byteLength),v=0;f.set(N,v),v+=N.byteLength,f[v]=ee,v+=1;let m=o;return o+=1,new DataView(f.buffer,f.byteOffset+v,x).setBigUint64(0,BigInt(m),false),v+=x,f.set(u,v),v+=u.byteLength,f.set(h,v),f},openPayload(l,d){if(!Pt(d))return n?null:d;if(Ge(d)!==ee)return null;let p=N.byteLength+1,h=Number(new DataView(d.buffer,d.byteOffset+p,x).getBigUint64(0,false));if(!Number.isFinite(h))return null;let f=p+x,v=f+$,m=d.slice(f,v),S=s?Tt(h,m):null;if(S&&a.has(S))return null;let w=d.slice(v),b;try{b=xchacha20poly1305(t,m).decrypt(w);}catch{return null}if(b.byteLength<1||b[0]!==l)return null;if(S)for(a.add(S),c.push(S);c.length>Rt;){let R=c.shift();R&&a.delete(R);}return b.slice(1)}}}function _t(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 Ke(r,e={}){let t$1=e.typeId??wt,n=e.maxFrameBytes??Ct;if(!Number.isInteger(t$1)||t$1<0||t$1>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$1,d),s=d=>r.openPayload(t$1,d),o=()=>new TransformStream({transform(d,u){u.enqueue(_t(i(new Uint8Array(d))));}}),a=()=>{let d=new Uint8Array(0);return new TransformStream({transform(u,p){for(d=t([d,new Uint8Array(u)]);d.byteLength>=4;){let h=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,false);if(h===0||h>n)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(d.byteLength<4+h)return;let f=d.slice(4,4+h);d=d.slice(4+h);let v=s(f);if(!v)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");p.enqueue(v);}},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$1,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 Et="[OpenRTC][teardown-trace]";function kt(){try{let r=globalThis;if(r.OPENRTC_TEARDOWN_TRACE===!0||r.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function ze(r,e={}){console.info(Et,{kind:r,ts:new Date().toISOString(),...e}),kt()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:r,stack:new Error(`teardown: ${r}`).stack});}var _={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,reconciliationIntervalMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:3e4,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,managedSessionIpcTimeoutMs:15e3,managedSessionIpcMaxAttempts:1,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function yn(){return _}var te={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}},Mt={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 V(r){return {adapter:r.adapter,signaling:{...r.signaling},transport:{...r.transport},nativeProtocols:{...r.nativeProtocols},lifecycle:{...r.lifecycle},transfers:{...r.transfers},fallback:{...r.fallback}}}function O(r){return r?.compiled===true&&r.enabled===true}function Sn(r,e=false){let t=V(Mt),n=r?.transport;return n&&(t.transport.irohQuic=O(n.irohQuic),t.transport.irohLan=O(n.irohLan),t.transport.webRtcUpgrade=O(n.webRtc),t.transport.nativeWebRtc=O(n.webRtc),t.transport.webRtcLan=O(n.webRtcLan),t.transport.moq=O(n.moq),t.transport.ble=O(n.ble)),t.transport.wasm=false,t.fallback.wasm=e,t}function In(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 E(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")}`}function Ot(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 ie(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?Ot(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:E(n),tokenFingerprint:E(o),tokenSuffixFingerprint:E(i),scope:a,maxConnections:c}}var L=class L{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.deviceWatchGeneration=0;this.freshnessRecheckTimer=null;this.rtdbPresence=null;this.rtdbScope=null;this.rtdbPresenceMap={};this.rtdbUnsubscribe=null;this.knownTicketVersions=new Map;}get options(){return this.hooks.options}setRtdbPresence(e,t){this.rtdbUnsubscribe&&(this.rtdbUnsubscribe(),this.rtdbUnsubscribe=null),this.rtdbPresence=e,this.rtdbScope=t,this.rtdbPresenceMap={},this.knownTicketVersions.clear();}stopRtdbPresence(){this.rtdbUnsubscribe?.(),this.rtdbUnsubscribe=null,this.rtdbPresence=null,this.rtdbScope=null,this.rtdbPresenceMap={},this.knownTicketVersions.clear();}stopAuthScopedActivity(){this.stopRtdbPresence(),this.stopDeviceWatch({clearDevices:true});}async searchDevices(e){let n=(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(n){n.close();}});let t=null;return new ReadableStream({start:n=>{t=onSnapshot(e,i=>{let s=Date.now(),o=[];for(let a of i.docChanges()){let c=this.toDevice(a.doc,s);if(a.type==="removed"){o.push({type:"removed",deviceId:a.doc.id});continue}if(!c){o.push({type:"removed",deviceId:a.doc.id});continue}o.push({type:a.type==="added"?"added":"modified",device:c});}o.length>0&&n.enqueue(o);},i=>{console.warn("[BrowserDeviceDiscovery] subscribeDevices snapshot error:",{message:i?.message,code:i?.code});try{n.close();}catch{}});},cancel:()=>{t?.(),t=null;}})}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;let t=Date.now(),n=this.rtdbPresence&&this.rtdbScope?await this.rtdbPresence.readPresenceMap(this.rtdbScope).catch(()=>this.rtdbPresenceMap):this.rtdbPresenceMap,[i,s]=await Promise.all([getDocs(query(e,where("online","==",false),where("expiresAt","<",t),limit(100))),getDocs(query(e,where("online","==",true),limit(100)))]),o=new Map;for(let a of i.docs)o.set(a.ref.path,a);for(let a of s.docs)o.set(a.ref.path,a);await Promise.allSettled([...o.values()].map(async a=>{let c=a.data(),l=this.isDeviceExpired(c,t),d=c.online===true;if(l&&!d){await deleteDoc(a.ref);return}let u=this.toMillis(c.updatedAt)??this.toMillis(c.lastSeenAt)??0,p=this.rtdbPresence&&this.rtdbScope?3e4:3e5;!d||!u||u+p>t||this.rtdbPresence&&this.rtdbScope&&n[typeof c.deviceId=="string"&&c.deviceId.trim()?c.deviceId.trim():a.id]?.online===true||await updateDoc(a.ref,{online:false,updatedAt:serverTimestamp$1(),expiresAt:t+2592e6});}));}async refreshDeviceForAutoConnect(e){let t=e.trim();if(!t)return null;let n=await this.hooks.getDevicesCollectionRef();if(!n)return this.devicesById.get(t)??null;let i=doc(n,t),s=this.devicesById.get(t)??null,o="server",a=null;try{a=await getDocFromServer(i);}catch(h){o="cache",console.warn("[BrowserDeviceDiscovery][auto-connect][refresh] getDocFromServer failed; falling back to getDoc",{deviceId:t,error:h}),a=await getDoc(i).catch(()=>null);}if(!a?.exists())return this.devicesById.delete(t),console.info("[BrowserDeviceDiscovery][auto-connect][refresh] device doc missing during refresh",{deviceId:t,source:o,previousTicket:ie(s?.ticket)}),this.emitDevicesToAll(),null;let c=typeof a.data=="function"?a.data():null,l=this.deviceFromSnapshot(t,c,Date.now());if(!l)return this.devicesById.delete(t),console.info("[BrowserDeviceDiscovery][auto-connect][refresh] refreshed device doc was filtered out",{deviceId:t,source:o,previousTicket:ie(s?.ticket)}),this.emitDevicesToAll(),null;let d=this.rtdbPresenceMap[t],u=d?{...l,online:d.online}:l;this.devicesById.set(t,u);let p=(s?.ticket??null)!==(u.ticket??null);return console.info("[BrowserDeviceDiscovery][auto-connect][refresh]",{deviceId:t,source:o,ticketChanged:p,previousTicket:ie(s?.ticket),refreshedTicket:ie(u.ticket),previousNodeId:s?.nodeId??null,refreshedNodeId:u.nodeId??null}),this.emitDevicesToAll(),u}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.clearFreshnessRecheckTimer(),this.activeDeviceUnsubscribe?.(),this.activeDeviceUnsubscribe=null,this.activeDeviceScopeKey=null,e?.clearDevices&&(this.devicesById.clear(),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);},L.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)}async readCurrentDeviceSnapshot(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return [];let t=await getDocs(e),n=Date.now(),i=[];for(let s of t.docs){let o=s.data();if(!this.options.matchesTag(o))continue;let a=typeof o.deviceId=="string"&&o.deviceId.trim().length>0?o.deviceId.trim():s.id;if(this.isStaleFirestoreOnlyRtdbDevice(a,o,n))continue;if(this.isStaleOnlineDevice(o,n)||o.online===true&&this.isDeviceExpired(o,n)){if(await this.markStaleDeviceOffline(s,o,n),this.shouldRetainStaleDevice(o)){let d=this.retainedStaleDevice(this.options.normalizeDevice({...o,deviceId:o.deviceId??s.id,online:false},s.id),s.id,n);d.deviceId&&i.push(d);}continue}if(this.isDeviceExpired(o,n))continue;let l=this.options.normalizeDevice({...o,deviceId:o.deviceId??s.id},s.id);l?.deviceId&&i.push(l);}return i}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;if(this.isStaleFirestoreOnlyRtdbDevice(s,t,n))return null;if(this.isStaleOnlineDevice(t,n)||t.online===true&&this.isDeviceExpired(t,n)){if(i&&this.markStaleDeviceOffline(i,t,n),!this.shouldRetainStaleDevice(t))return null;let c=this.retainedStaleDevice(this.options.normalizeDevice({...t,deviceId:t.deviceId??e,online:false},e),e,n);return c.deviceId?c:null}if(this.isDeviceExpired(t,n))return null;let a=this.options.normalizeDevice({...t,deviceId:t.deviceId??e},e);return a.deviceId?a: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&&this.rtdbPresenceMap[s]?.online===true)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||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;await updateDoc(o,{online:!1,updatedAt:serverTimestamp$1(),expiresAt: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)){if(this.stopDeviceWatch({clearDevices:true}),this.rtdbPresence&&this.rtdbScope){await this.ensureDeviceWatchRtdb(e,t);return}this.startFirestoreDeviceWatch(e,t);}}startFirestoreDeviceWatch(e,t){let n=++this.deviceWatchGeneration;this.activeDeviceScopeKey=t,this.activeDeviceUnsubscribe=onSnapshot(e,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.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 d=0;d<3;d+=1)try{i=await B(getDocs(e),L.RTDB_ROSTER_READ_TIMEOUT_MS,()=>new Error("RTDB-backed device roster read timed out")),s=null;break}catch(u$1){if(s=u$1,n!==this.deviceWatchGeneration)return;await r(u(d+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.docs,o);let a=this.rtdbPresence,c=this.rtdbScope,l=null;this.rtdbUnsubscribe&&this.rtdbUnsubscribe();try{l=onSnapshot(e,d=>{n===this.deviceWatchGeneration&&(this.replaceDevicesFromDocuments(d.docs,Date.now()),this.applyRtdbOverlay(),this.scheduleFreshnessRecheck(n));},d=>{n===this.deviceWatchGeneration&&console.warn("[BrowserDeviceDiscovery] RTDB-backed Firestore roster watch failed:",d);}),this.rtdbUnsubscribe=a.onPresenceChange(c,d=>{if(n!==this.deviceWatchGeneration)return;this.rtdbPresenceMap=d;let u=[];for(let[p,h]of Object.entries(d)){let f=this.knownTicketVersions.get(p)??-1,v=this.devicesById.has(p);h.ticketVersion!==f?(this.knownTicketVersions.set(p,h.ticketVersion),(f!==-1||!v&&h.online)&&u.push(p)):!v&&h.online&&u.push(p);}this.applyRtdbOverlay(),this.scheduleFreshnessRecheck(n),u.length>0&&this.refetchDeviceTickets(u,e,n);});}catch(d){if(n!==this.deviceWatchGeneration){l?.();return}l?.(),console.warn("[BrowserDeviceDiscovery] RTDB presence subscription setup failed; falling back to Firestore listener:",d),this.startFirestoreDeviceWatch(e,t);return}this.activeDeviceUnsubscribe=()=>{l?.(),l=null,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(){for(let[e,t]of this.devicesById){let n=this.rtdbPresenceMap[e];n&&t.online!==n.online&&this.devicesById.set(e,{...t,online:n.online});}for(let[e,t]of Object.entries(this.rtdbPresenceMap)){if(this.devicesById.has(e)||!t.online)continue;let n=this.deviceFromRtdbPresence(e,t);n&&this.devicesById.set(e,n);}this.emitDevicesToAll();}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:t.online,ticket:t.ticket||"",nodeId:t.nodeId,metadata:t.metadata,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,n){await Promise.allSettled(e.map(async i=>{try{let s=doc(t,i),o=await getDoc(s);if(n!==this.deviceWatchGeneration)return;if(!o.exists()){let c=this.deviceFromRtdbPresence(i,this.rtdbPresenceMap[i]);c?this.devicesById.set(i,c):this.devicesById.delete(i);return}let a=this.deviceFromSnapshot(i,typeof o.data=="function"?o.data():null,Date.now());if(a){let c=this.rtdbPresenceMap[i];this.devicesById.set(i,c?{...a,online:c.online}:a);}else {let c=this.deviceFromRtdbPresence(i,this.rtdbPresenceMap[i]);c?this.devicesById.set(i,c):this.devicesById.delete(i);}}catch(s){console.warn("[BrowserDeviceDiscovery] refetch device ticket failed:",s);}})),n===this.deviceWatchGeneration&&this.emitDevicesToAll();}};L.RTDB_ROSTER_READ_TIMEOUT_MS=5e3,L.DEVICE_FRESHNESS_RECHECK_MS=3e4;var se=L;var oe=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);for(let[s,o]of this.friendDeviceUnsubscribes)i.has(s)||(o(),this.friendDeviceUnsubscribes.delete(s),n.delete(s));for(let s of e){if(this.friendDeviceUnsubscribes.has(s))continue;let o=`apps/${this.ctx.appTag}/users/${s}/devices`,a=collection(this.firestore,o),c=onSnapshot(a,l=>{let d=[];l.forEach(u=>{let p=u.data();if(!p||p.kind!=="device"||!this.ctx.matchesTag(p))return;let h=this.ctx.normalizeDevice(p,u.id);h.online&&d.push(h);}),n.set(s,d),t(new Map(n));},l=>{console.warn("[BrowserFriendDiscovery] friend device watch failed:",{friendUid:s,message:l?.message,code:l?.code});});this.friendDeviceUnsubscribes.set(s,c);}return ()=>{for(let[,s]of this.friendDeviceUnsubscribes)s();this.friendDeviceUnsubscribes.clear();}}async updateFriendTicket(e){let t=await this.ctx.resolveOrCreateLocalDeviceRef();t&&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 $t="createSignalingSession",ce=class{constructor(e){this.ctx=e;}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");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&&(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");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,p={appTag:this.ctx.appTag,senderId:c,targetId:e,payload:t,state:n??null,replyPayload:i??null,timestamp:d,expiresAt:d+u};return l&&(p.senderUserId=l,p.targetUserId=l),await setDoc(a,p),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)],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({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),_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(a){a.close();}});let i=null,s=null,o=false;return new ReadableStream({start:a=>{let c={initiator:new Set,target:new Set},l=new Map,d=(u,p)=>{if(o)return;let h=[];for(let f of p.docChanges()){let v=f.doc.id;if(f.type==="removed"){c[u].delete(v),!(c.initiator.has(v)||c.target.has(v))&&l.delete(v)&&h.push({type:"removed",sessionId:v});continue}let m=this.toSession(f.doc.id,f.doc.data());if(!m)continue;c[u].add(v);let S=l.has(v);l.set(v,m),h.push({type:S?"modified":"added",session:m});}h.length>0&&a.enqueue(h);};i=onSnapshot(query(t,where("initiatorDeviceId","==",n)),u=>d("initiator",u),u=>{o||a.error(u);}),s=onSnapshot(query(t,where("targetDeviceId","==",n)),u=>d("target",u),u=>{o||a.error(u);});},cancel:()=>{o=true,i?.(),s?.(),i=null,s=null;}})}shouldUseHostedSessionCallable(){return (this.ctx.discoveryMode??"space")!=="space"&&!!this.ctx.getCurrentUserId()}async createHostedSession(e){await httpsCallable(getFunctions(this.ctx.app),$t)({...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 jt(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="not-found"}var le=class{constructor(e){this.options=e;this.rtdbPresence=null;this.namespaceRootPromise=null;this.resolvedDeviceDocIds=new Map;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 se({options:this.options,firestore:this.firestore,getDevicesCollectionRef:()=>this.getDevicesCollectionRef(),resolveDeviceRef:t=>this.resolveDeviceRef(t)}),this.friendDiscovery=new oe({app:e.app,appTag:e.appTag,discoveryMode:e.discoveryMode,apiKey:e.apiKey,spaceKey:e.spaceKey,matchesTag:e.matchesTag,normalizeDevice:e.normalizeDevice,resolveOrCreateLocalDeviceRef:()=>this.resolveOrCreateLocalDeviceRef(),usesSpaceMode:()=>this.usesSpaceMode()}),this.sessionSignaling=new ce({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(){await this.discovery.handleScopeChange();}stopAuthScopedActivity(){this.discovery.stopAuthScopedActivity();}async updatePresence(e,t,n,i,s,o){let a=await this.resolveOrCreateLocalDeviceRef();if(!a)return;let c=this.options.getLocalDeviceId(),l=Date.now(),d=o?.trim()||this.options.getDefaultDeviceName(),u=this.options.getCurrentUserId(),p=n?l+Math.max(0,Math.trunc(i)):l+2592e6,h=await getDoc(a).catch(()=>null),f={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:p};u&&(f.userId=u),h?.exists()||(f.createdAt=serverTimestamp$1()),await setDoc(a,f,{merge:true});}async setOffline(e){let t=await this.resolveOrCreateLocalDeviceRef();if(!t)return;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:Date.now()+2592e6},i=this.options.getCurrentUserId();i&&(n.userId=i);try{await updateDoc(t,n);}catch(s){if(!jt(s))throw s}}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");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 deleteDoc(t);}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}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=b(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 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)}};function ue(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 ct(r){switch(r.kind){case "user-scoped":return `presence/${r.appTag}/users/${r.userId}/devices`;case "space":return `presence/spaces/${r.namespaceId}/devices`}}function dt(r,e,t){return `presence/${r}/rooms/${e}/members/${t}`}function nn(r,e){return `presence/${r}/rooms/${e}/members`}function G(r){let e={},t=(n,i)=>{if(typeof i!="string")return;let s=i.trim();s&&(e[n]=s);};return t("ticket",r?.ticket),t("nodeId",r?.nodeId),t("deviceName",r?.deviceName),t("metadata",r?.metadata),e}function Re(r,e){return {online:true,lastSeenAt:serverTimestamp(),ticketVersion:r,...G(e)}}function De(r,e){return {online:false,lastSeenAt:serverTimestamp(),ticketVersion:r,...G(e)}}function pe(r){return {...r}}var he=class{constructor(e){this.desiredOnlineNodes=new Map;this.connected=null;this.connectedUnsubscribe=null;this.db=getDatabase(e);try{let t=globalThis?.__OPENRTC_RTDB_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??9001);try{connectDatabaseEmulator(this.db,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_RTDB_EMULATOR_PORT??9001);try{connectDatabaseEmulator(this.db,o,a);}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;let n=ref(this.db,e);await onDisconnect(n).set(t.offline),await set(n,t.online);}async registerOnlineNode(e,t,n){this.ensureReconnectWatch(),this.desiredOnlineNodes.set(e,{online:t,offline:n}),await this.publishDesiredOnline(e);}async markNodeOffline(e,t){this.desiredOnlineNodes.delete(e);let n=ref(this.db,e);await onDisconnect(n).cancel(),await set(n,t);}subscribeIncremental(e,t,n,i){let s=ref(this.db,e),o={},a=()=>n({...o}),c=u=>{let p=typeof u.key=="string"?u.key:"";if(!p)return;let h=t(p,u.val());h?o[p]=h:delete o[p],a();},l=u=>{console.warn(`[RtdbPresence] ${i} presence subscription error:`,u);},d=[onChildAdded(s,c,l),onChildChanged(s,c,l),onChildRemoved(s,u=>{let p=typeof u.key=="string"?u.key:"";p&&(delete o[p],a());},l)];return ()=>{for(let u of d)u();}}async registerDevice(e,t,n=0,i){await this.registerOnlineNode(ue(e,t),pe(Re(n,i)),pe(De(n,i)));}async bumpTicketVersion(e,t,n,i){let s=ref(this.db,ue(e,t)),o=ue(e,t),a=this.desiredOnlineNodes.get(o),c=G(i);if(a){let l=a.online;c=G({ticket:i?.ticket??l.ticket,nodeId:i?.nodeId??l.nodeId,deviceName:i?.deviceName??l.deviceName,metadata:i?.metadata??l.metadata}),a.online=pe(Re(n,c)),a.offline=pe(De(n,c));}await onDisconnect(s).set(De(n,c)),await set(s,Re(n,c));}async markOffline(e,t,n=0){await this.markNodeOffline(ue(e,t),{online:false,lastSeenAt:serverTimestamp(),ticketVersion:n});}async registerRoomMember(e,t,n){await this.registerOnlineNode(dt(e,t,n),{online:true,lastSeenAt:serverTimestamp()},{online:false,lastSeenAt:serverTimestamp()});}async markRoomMemberOffline(e,t,n){await this.markNodeOffline(dt(e,t,n),{online:false,lastSeenAt:serverTimestamp()});}onRoomPresenceChange(e,t,n){return this.subscribeIncremental(nn(e,t),(i,s)=>!s||typeof s!="object"?null:{online:s.online===true},n,"room")}onPresenceChange(e,t){return this.subscribeIncremental(ct(e),(n,i)=>{if(!i||typeof i!="object")return null;let s=i,o=G({ticket:s.ticket,nodeId:s.nodeId,deviceName:s.deviceName,metadata:s.metadata});return {online:s.online===true,ticketVersion:typeof s.ticketVersion=="number"?s.ticketVersion:0,...o}},t,"device")}async readPresenceMap(e){let n=(await get(ref(this.db,ct(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=o,c=G({ticket:a.ticket,nodeId:a.nodeId,deviceName:a.deviceName,metadata:a.metadata});i[s]={online:a.online===true,ticketVersion:typeof a.ticketVersion=="number"?a.ticketVersion:0,...c};}return i}};function rn(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 Ae(r){let e=typeof r=="string"?r.trim():"";if(!e)return null;let t=0;for(let n=0;n<e.length;n+=1)t=t*31+e.charCodeAt(n)>>>0;return t.toString(16).padStart(8,"0").slice(0,8)}function K(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?rn(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:Ae(n),tokenFingerprint:Ae(o),tokenSuffixFingerprint:Ae(i),scope:a,maxConnections:c}}var I=class I{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.autoConnectStartsInFlight=new Set;this.browserAutoConnectUnsubscribe=null;this.browserAutoConnectLastAttemptAt=new Map;this.browserAutoConnectInFlight=new Set;this.browserAutoConnectWaitStartedAt=new Map;this.browserAutoConnectEscalationCount=new Map;this.browserAutoConnectFailureCount=new Map;this.browserAutoConnectBackoffUntilMs=new Map;this.browserAutoConnectObservedSignatures=new Map;this.browserAutoConnectRecoveryTimers=new Map;this.browserAutoConnectApplicationEscalatedAt=new Map;this.browserAutoConnectPendingDevices=new Map;this.browserAutoConnectScanTimer=null;this.presenceState=null;this.presenceStartGeneration=0;this.rtdbPresenceRetryTimer=null;this.rtdbPresenceRetryAttempt=0;}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get pendingDevices(){return this.browserAutoConnectPendingDevices}set pendingDevices(e){this.browserAutoConnectPendingDevices=e;}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=this.deps.resolveWebLogicalDeviceId(),i=`${e}::${n}`;(async()=>{let s=this.presenceState,o=typeof s?.localNodeId=="string"&&s.localNodeId.trim()||null;if(!(this.startedAutoConnectKey===i||this.autoConnectStartsInFlight.has(i))){this.autoConnectStartsInFlight.add(i);try{this.stopAutoConnect(),this.startedAutoConnectKey=i,this.browserAutoConnectUnsubscribe=this.deps.getBrowserFirestoreSignaling().onDevicesChange(a=>{this.scheduleBrowserAutoConnectScan(a,o,n);});}finally{this.autoConnectStartsInFlight.delete(i);}}})().catch(()=>{this.startedAutoConnectKey===i&&(this.startedAutoConnectKey=null),this.autoConnectStartsInFlight.delete(i);});}notifyDisconnectRequested(e){if(!this.startedAutoConnectKey||this.browserAutoConnectPendingDevices.size===0)return;let t=e.trim();if(!t)return;let n=[...this.browserAutoConnectPendingDevices.values()].find(i=>(typeof i.nodeId=="string"?i.nodeId.trim():"")===t);n?.deviceId&&this.queueBrowserAutoConnectRecoveryForDevice(n,{resetWaitStartedAt:true});}triggerBrowserAutoConnectRecovery(e){if(!this.startedAutoConnectKey||this.browserAutoConnectPendingDevices.size===0)return;let t=[...this.browserAutoConnectPendingDevices.values()].find(n=>{let i=typeof n.deviceId=="string"?n.deviceId.trim():"",s=typeof n.nodeId=="string"?n.nodeId.trim():"";return !!e.deviceId&&i===e.deviceId||!!e.deviceIdHint&&i===e.deviceIdHint||!!e.remoteNodeId&&s===e.remoteNodeId});t?.deviceId&&this.queueBrowserAutoConnectRecoveryForDevice(t);}forceBrowserAutoConnectSnapshot(){if(this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey)return false;let e=[...this.browserAutoConnectPendingDevices.values()];if(!this.browserAutoConnectUnsubscribe){let t=this.startedAutoConnectKey.indexOf("::"),n=t>=0?this.startedAutoConnectKey.slice(0,t):"",i=this.deps.resolveWebLogicalDeviceId();if(n&&i){let s=this.startedAutoConnectKey;this.browserAutoConnectUnsubscribe=this.deps.getBrowserFirestoreSignaling().onDevicesChange(o=>{let a=this.presenceState,c=typeof a?.localNodeId=="string"&&a.localNodeId.trim()||null;this.scheduleBrowserAutoConnectScan(o,c,i);}),this.startedAutoConnectKey=s;}}for(let t of e){let n=typeof t.deviceId=="string"?t.deviceId.trim():"";n&&(this.browserAutoConnectInFlight.delete(n),this.browserAutoConnectObservedSignatures.delete(n),this.browserAutoConnectLastAttemptAt.delete(n),this.browserAutoConnectBackoffUntilMs.delete(n),this.browserAutoConnectFailureCount.delete(n));}if(e.length>0){let t=this.presenceState,n=typeof t?.localNodeId=="string"&&t.localNodeId.trim()||null;this.browserAutoConnectScanTimer&&(clearTimeout(this.browserAutoConnectScanTimer),this.browserAutoConnectScanTimer=null),this.browserAutoConnectPendingDevices=new Map(e.filter(i=>!!i.deviceId).map(i=>[i.deviceId,i])),this.processBrowserAutoConnectSnapshot(n,this.deps.resolveWebLogicalDeviceId());}return true}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);}startPresenceLoop(e,t,n,i,s){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let o=++this.presenceStartGeneration;this.presenceState={localNodeId:t,ticket:i,metadata:s,deviceName:n};let a=this.deps.resolveWebLogicalDeviceId(),c=l=>{let d=this.deps.withWebPresenceMetadata(s,a),u=()=>o===this.presenceStartGeneration&&this.presenceState!==null;if(!this.deps.isRtdbPresenceDisabledForSession()&&l&&a){let p=false,h=false,f=null,v=null,m=(S,w)=>{u()&&(this.deps.isRtdbPresenceDisabledForSession()||this.scheduleRtdbPresenceRetry(l,a,o,S,w));};f=setTimeout(()=>{p||console.warn("[WasmBridge] initial roster write timed out; RTDB liveness will retry after the write settles");},I.INITIAL_PRESENCE_WRITE_TIMEOUT_MS),v=setTimeout(()=>{h||m("RTDB presence register timed out");},I.RTDB_PRESENCE_REGISTER_TIMEOUT_MS),this.deps.updatePresence(t,i,false,10080*60*1e3,d,n).then(()=>{p=true,f&&(clearTimeout(f),f=null);}).catch(S=>{f&&(clearTimeout(f),f=null),console.warn("[WasmBridge] initial roster write failed; browser presence is not discoverable until the roster write succeeds:",S);}),this.deps.registerRtdbPresence(l,a,this.deps.getRtdbTicketVersion(),{ticket:i,nodeId:t,deviceName:n,metadata:d}).then(()=>{h=true,this.rtdbPresenceRetryAttempt=0,this.clearRtdbPresenceRetryTimer(),v&&(clearTimeout(v),v=null);}).catch(S=>{v&&(clearTimeout(v),v=null),m("RTDB presence register failed",S);});return}this.deps.updatePresence(t,i,false,_.browserIdentity.ephemeralDeviceIdTtlMs,d,n).catch(p=>{console.warn("[WasmBridge] durable roster write failed without RTDB presence:",p);});};if(this.deps.resolveRtdbScope){this.deps.resolveRtdbScope(e).then(c);return}c(this.deps.buildRtdbScope(e));}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(I.RTDB_PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,o-1),I.RTDB_PRESENCE_RETRY_MAX_DELAY_MS),c=(o*29%21-10)/100,l=Math.max(I.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())&&this.deps.registerRtdbPresence(e,t,this.deps.getRtdbTicketVersion(),{ticket:this.presenceState.ticket,nodeId:this.presenceState.localNodeId,deviceName:this.presenceState.deviceName,metadata:this.deps.withWebPresenceMetadata(this.presenceState.metadata,t)}).then(()=>{this.rtdbPresenceRetryAttempt=0;}).catch(d=>{this.scheduleRtdbPresenceRetry(e,t,n,"RTDB presence retry failed",d);});},l);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.browserAutoConnectScanTimer&&(clearTimeout(this.browserAutoConnectScanTimer),this.browserAutoConnectScanTimer=null),this.browserAutoConnectPendingDevices.clear(),this.startedAutoConnectKey=null,this.autoConnectStartsInFlight.clear(),this.browserAutoConnectInFlight.clear(),this.browserAutoConnectLastAttemptAt.clear(),this.browserAutoConnectWaitStartedAt.clear(),this.browserAutoConnectEscalationCount.clear(),this.browserAutoConnectFailureCount.clear(),this.browserAutoConnectBackoffUntilMs.clear(),this.browserAutoConnectObservedSignatures.clear(),this.browserAutoConnectApplicationEscalatedAt.clear();for(let e of this.browserAutoConnectRecoveryTimers.values())clearTimeout(e);this.browserAutoConnectRecoveryTimers.clear();}clearBrowserAutoConnectDeviceState(e){this.browserAutoConnectWaitStartedAt.delete(e),this.browserAutoConnectEscalationCount.delete(e),this.browserAutoConnectFailureCount.delete(e),this.browserAutoConnectBackoffUntilMs.delete(e),this.browserAutoConnectLastAttemptAt.delete(e);let t=this.browserAutoConnectRecoveryTimers.get(e);t&&(clearTimeout(t),this.browserAutoConnectRecoveryTimers.delete(e));}queueBrowserAutoConnectRecoveryForDevice(e,t){if(!e?.deviceId)return;let n=e.deviceId;this.browserAutoConnectInFlight.delete(n),t?.preserveRecentDialState||(this.browserAutoConnectObservedSignatures.delete(n),this.browserAutoConnectApplicationEscalatedAt.delete(n),this.browserAutoConnectLastAttemptAt.delete(n)),this.browserAutoConnectBackoffUntilMs.delete(n),this.browserAutoConnectFailureCount.delete(n),t?.resetWaitStartedAt&&this.browserAutoConnectWaitStartedAt.delete(n);let i=this.presenceState,s=typeof i?.localNodeId=="string"&&i.localNodeId.trim()||null,o=this.deps.resolveWebLogicalDeviceId();this.scheduleBrowserAutoConnectScan([...this.browserAutoConnectPendingDevices.values()],s,o);let a=this.browserAutoConnectRecoveryTimers.get(n);a&&clearTimeout(a);let c=setTimeout(()=>{if(this.browserAutoConnectRecoveryTimers.delete(n),!this.browserAutoConnectPendingDevices.has(n))return;this.browserAutoConnectInFlight.delete(n),this.browserAutoConnectObservedSignatures.delete(n),this.browserAutoConnectLastAttemptAt.delete(n);let l=this.presenceState,d=typeof l?.localNodeId=="string"&&l.localNodeId.trim()||null;this.scheduleBrowserAutoConnectScan([...this.browserAutoConnectPendingDevices.values()],d,this.deps.resolveWebLogicalDeviceId());},I.BROWSER_AUTO_CONNECT_SETTLE_GUARD_MS+100);this.browserAutoConnectRecoveryTimers.set(n,c);}browserAutoConnectLifecycleFresh(e){return typeof e=="number"&&e>0&&Date.now()-e<I.BROWSER_AUTO_CONNECT_SETTLE_GUARD_MS}isStaleTransportReplacementSignal(e){if(!e||!e.replacementInProgress&&!e.replacementPending)return false;let t=[e.readinessReason,e.lastDisconnectReason,e.lastReconnectReason,e.error].filter(n=>typeof n=="string"&&n.length>0).join(" ");return /stale transport/i.test(t)}isDeviceExcludedByPeer(e,t){let n=t.trim().toLowerCase();return !!n&&Array.isArray(e.excludedPeers)&&e.excludedPeers.some(i=>String(i??"").trim().toLowerCase()===n)}hasManualDisconnectProjection(e){let t=String(e.deviceId??"").trim().toLowerCase(),n=String(e.nodeId??"").trim().toLowerCase();if(!t&&!n)return false;for(let i of this.deps.getLastDeliveredConnectionStates()){let s=[i.deviceId,i.deviceIdHint,i.remoteNodeId,i.connectionId].map(d=>String(d??"").trim().toLowerCase()).filter(Boolean),o=!!t&&s.includes(t),a=!!n&&s.includes(n);if(!o&&!a)continue;let c=i.state==="closed"||i.state==="failed"||i.transportState==="closed"||i.protocolState==="closed",l=[i.error,i.lastDisconnectReason].filter(d=>typeof d=="string"&&d.length>0).join(" ");if(c&&/manual disconnect/i.test(l))return true}return false}async shouldSuppressBrowserAutoConnectDevice(e,t,n){let i=typeof e.deviceId=="string"?e.deviceId.trim():"";if(!i)return false;if(this.isDeviceExcludedByPeer(e,t))return A(`[WasmPresenceManager][auto-connect-dial] BAIL \u2014 ${n}peer excluded this device for this session deviceKey=${i}`),this.clearBrowserAutoConnectDeviceState(i),true;let s=await this.deps.waitForWasmClient(0).catch(()=>null);return s&&typeof s.is_auto_connect_excluded=="function"&&s.is_auto_connect_excluded(i)===true?(A(`[WasmPresenceManager][auto-connect-dial] BAIL \u2014 ${n}peer auto-connect suppressed for this session deviceKey=${i}`),this.clearBrowserAutoConnectDeviceState(i),true):this.hasManualDisconnectProjection(e)?(A(`[WasmPresenceManager][auto-connect-dial] BAIL \u2014 ${n}peer manually disconnected for this browser session deviceKey=${i}`),this.clearBrowserAutoConnectDeviceState(i),true):false}getRustOwnedAutoConnectGate(e){let t=typeof e.deviceId=="string"?e.deviceId.trim():"",n=typeof e.nodeId=="string"?e.nodeId.trim():"";if(!t&&!n)return "none";let i=false;for(let s of this.deps.getLastDeliveredConnectionStates()){let o=t.length>0&&(s.deviceId===t||s.deviceIdHint===t),a=n.length>0&&s.remoteNodeId===n;if(!(!o&&!a)&&!this.isStaleTransportReplacementSignal(s)){if(s.replacementInProgress){this.browserAutoConnectLifecycleFresh(s.lastLifecycleTransitionAtMs)&&(i=true);continue}if(s.state==="connecting"){if(s.routable===true)return "healthy";this.browserAutoConnectLifecycleFresh(s.lastLifecycleTransitionAtMs)&&(i=true);continue}if(s.state==="connected"){if(s.routable===true)return "healthy";this.browserAutoConnectLifecycleFresh(s.lastLifecycleTransitionAtMs)&&(i=true);continue}s.state==="pending"&&(i=true);}}return i?"transitional":"none"}browserAutoConnectNonInitiatorGraceMs(e){let t=Math.max(0,Math.min(3,Math.trunc(e))),n=_.browserAutoConnect.nonInitiatorBaseGraceMs,i=Math.min(n*(1<<t),_.browserAutoConnect.nonInitiatorMaxGraceMs),s=(t*37+7)%41-20;return Math.max(1e3,i+Math.trunc(i*s/100))}queueBrowserAutoConnectGraceExpiryRecheck(e,t){if(!e)return;let n=this.browserAutoConnectRecoveryTimers.get(e);n&&clearTimeout(n);let i=setTimeout(()=>{if(this.browserAutoConnectRecoveryTimers.delete(e),!this.browserAutoConnectPendingDevices.has(e))return;this.browserAutoConnectObservedSignatures.delete(e);let s=this.presenceState,o=typeof s?.localNodeId=="string"&&s.localNodeId.trim()||null;this.scheduleBrowserAutoConnectScan([...this.browserAutoConnectPendingDevices.values()],o,this.deps.resolveWebLogicalDeviceId());},Math.max(50,Math.trunc(t)));this.browserAutoConnectRecoveryTimers.set(e,i);}applyBrowserAutoConnectFailureBackoff(e){let t=(this.browserAutoConnectFailureCount.get(e)??0)+1;this.browserAutoConnectFailureCount.set(e,t);let n=I.BROWSER_AUTO_CONNECT_RETRY_COOLDOWN_MS*Math.max(1,2**Math.min(4,t-1)),i=Math.min(I.BROWSER_AUTO_CONNECT_RETRY_MAX_MS,n),s=Math.trunc(i*(t*31%21-10)/100),o=Math.max(I.BROWSER_AUTO_CONNECT_RETRY_COOLDOWN_MS,i+s),a=Date.now()+o;this.browserAutoConnectBackoffUntilMs.set(e,a),this.queueBrowserAutoConnectGraceExpiryRecheck(e,o+25);}async shouldAttemptBrowserAutoConnectDial(e,t,n){if(!e.online||!e.ticket||!e.deviceId||e.deviceId===n)return false;let i=e.deviceId,s=typeof e.nodeId=="string"?e.nodeId.trim():"";if(t&&s&&s===t)return A(`[WasmPresenceManager][auto-connect-dial] BAIL \u2014 peer node is local node deviceKey=${i}`),this.clearBrowserAutoConnectDeviceState(i),false;let o=s.length>0&&await this.deps.isConnected(s).catch(()=>false);if(await this.shouldSuppressBrowserAutoConnectDevice(e,n,""))return false;let a=this.getRustOwnedAutoConnectGate(e);if(a!=="none")if(a==="healthy"&&!o)A(`[WasmPresenceManager][auto-connect-dial] rust-owned healthy gate ignored; transport disconnected deviceKey=${i}`);else return a==="healthy"&&s.length>0&&this.clearBrowserAutoConnectDeviceState(i),false;let c=e.deviceId||s,l=c?await this.deps.getPeerSession(c).catch(()=>null):null;if(l?.settledReady)return this.clearBrowserAutoConnectDeviceState(i),false;let d=typeof l?.lastLifecycleTransitionAtMs=="number"?l.lastLifecycleTransitionAtMs:0,u=this.browserAutoConnectLifecycleFresh(d),p=l?.activeTransportStableId!=null,h=this.isStaleTransportReplacementSignal(l);A(`[WasmPresenceManager][auto-connect-dial] evaluating deviceKey=${i} remoteNodeId=${s.slice(0,8)} localNodeId=${(t??"").slice(0,8)} transportConnected=${o} sessionStatus=${l?.status??"none"} withinSettleGuard=${u} sessionHasActiveTransport=${p}`);let f=l?.settledReady===true||u&&!h;if(o&&f)return A(`[WasmPresenceManager][auto-connect-dial] BAIL \u2014 transport already connected deviceKey=${i}`),this.browserAutoConnectWaitStartedAt.delete(i),this.browserAutoConnectEscalationCount.delete(i),false;if(o&&A(`[WasmPresenceManager][auto-connect-dial] stale transport observed; allowing redial evaluation deviceKey=${i}`),l?.replacementPending&&u&&!h||l?.status==="connecting"&&u&&!h||l?.status==="connected"&&u&&!h)return l?.settledReady&&this.clearBrowserAutoConnectDeviceState(i),false;if(!t||!s)return A(`[WasmPresenceManager][auto-connect-dial] PROCEED \u2014 no tiebreak info deviceKey=${i}`),true;if(t>s)return A(`[WasmPresenceManager][auto-connect-dial] PROCEED \u2014 tiebreak WIN (localNodeId > remoteNodeId) deviceKey=${i}`),this.browserAutoConnectWaitStartedAt.delete(i),true;let v=Date.now(),m=this.browserAutoConnectEscalationCount.get(i)??0,S=this.browserAutoConnectWaitStartedAt.get(i)??v;this.browserAutoConnectWaitStartedAt.has(i)||this.browserAutoConnectWaitStartedAt.set(i,S);let w=v-S,b=this.browserAutoConnectNonInitiatorGraceMs(m);return w<b?(A(`[WasmPresenceManager][auto-connect-dial] WAIT \u2014 non-initiator grace not elapsed deviceKey=${i} waitedMs=${w} graceMs=${b} escalation=${m}`),this.queueBrowserAutoConnectGraceExpiryRecheck(i,b-w+25),false):(A(`[WasmPresenceManager][auto-connect-dial] PROCEED \u2014 grace expired, escalating deviceKey=${i} escalation=${m+1}`),this.browserAutoConnectWaitStartedAt.delete(i),this.browserAutoConnectEscalationCount.set(i,m+1),true)}async hasHealthyBrowserAutoConnectSession(e){let t=typeof e.nodeId=="string"?e.nodeId.trim():"",n=t.length>0&&await this.deps.isConnected(t).catch(()=>false),i=this.getRustOwnedAutoConnectGate(e);if(i!=="none")return !(i==="healthy"&&!n);let s=e.deviceId||t;if(!s)return false;let o=await this.deps.getPeerSession(s).catch(()=>null),a=this.isStaleTransportReplacementSignal(o);return !!(o?.settledReady||this.browserAutoConnectLifecycleFresh(o?.lastLifecycleTransitionAtMs)&&((o?.status==="connecting"||o?.status==="connected")&&o.activeTransportStableId!=null&&!a||n))}async ensureBrowserAutoConnectApplicationConnection(e){let t=typeof e.deviceId=="string"?e.deviceId.trim():"";if(!t||!e.ticket)return;let n=typeof e.nodeId=="string"?e.nodeId.trim():void 0;if(this.deps.hasApplicationRouteForPeer(n)){this.browserAutoConnectApplicationEscalatedAt.delete(t);return}let i=Date.now(),s=this.browserAutoConnectApplicationEscalatedAt.get(t)??0;if(i-s<I.BROWSER_AUTO_CONNECT_RETRY_COOLDOWN_MS){this.queueBrowserAutoConnectGraceExpiryRecheck(t,I.BROWSER_AUTO_CONNECT_RETRY_COOLDOWN_MS-(i-s)+25);return}this.browserAutoConnectApplicationEscalatedAt.set(t,i),D("[WasmPresenceManager][auto-connect] establishing application route over healthy transport",{deviceId:t,nodeId:e.nodeId??null,ticket:K(e.ticket)}),await this.deps.connectToDevice({deviceId:t,endpointTicket:e.ticket}),this.deps.hasApplicationRouteForPeer(n)||(D("[WasmPresenceManager][auto-connect] application route still pending after escalation; requeueing recovery",{deviceId:t,nodeId:e.nodeId??null}),this.queueBrowserAutoConnectRecoveryForDevice(e,{preserveRecentDialState:true}));}browserAutoConnectSignature(e){let t=typeof e.updatedAt=="number"?e.updatedAt:typeof e.updatedAt?.toMillis=="function"?e.updatedAt.toMillis():typeof e.lastSeenAt=="number"?e.lastSeenAt:typeof e.lastSeenAt?.toMillis=="function"?e.lastSeenAt.toMillis():0,n=Array.isArray(e.excludedPeers)?e.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean).sort():[];return JSON.stringify({deviceId:e.deviceId,nodeId:e.nodeId??null,online:!!e.online,ticket:e.ticket??null,excludedPeers:n,updatedAt:t})}deviceFreshnessMs(e){let t=n=>typeof n=="number"&&Number.isFinite(n)?n:n&&typeof n=="object"&&typeof n.toMillis=="function"?n.toMillis():n instanceof Date?n.getTime():null;return t(e.updatedAt)??t(e.lastSeenAt)??t(e.createdAt)}isBrowserAutoConnectCandidate(e,t,n){let i=typeof e.deviceId=="string"?e.deviceId.trim():"";if(!i||i===n||e.connectable===false||e.presenceStatus==="idle"||e.presenceStatus==="offline"||e.online!==true||!e.ticket)return false;let s=typeof e.nodeId=="string"?e.nodeId.trim():"";if(t&&s&&s===t)return false;let o=this.deviceFreshnessMs(e);if(o===null)return true;let a=this.deps.isRtdbPresenceDisabledForSession()?3e5:3e4;return o+a>Date.now()}async refreshBrowserAutoConnectDeviceForDial(e){let t=typeof e.deviceId=="string"?e.deviceId.trim():"";if(!t)return e;let i=await this.deps.getBrowserFirestoreSignaling().refreshDeviceForAutoConnect(t).catch(a=>(console.warn("[WasmSignaling][auto-connect][dial-refresh] failed to refresh device ticket before dial",{deviceId:t,error:a,cachedTicket:K(e.ticket)}),null))??e,s=(i.ticket??null)!==(e.ticket??null),o=(i.nodeId??null)!==(e.nodeId??null);return D("[WasmSignaling][auto-connect][dial-ticket]",{deviceId:t,ticketChanged:s,nodeChanged:o,cachedTicket:K(e.ticket),effectiveTicket:K(i.ticket),cachedNodeId:e.nodeId??null,effectiveNodeId:i.nodeId??null}),i}scheduleBrowserAutoConnectScan(e,t,n){this.browserAutoConnectPendingDevices=new Map(e.filter(i=>this.isBrowserAutoConnectCandidate(i,t,n)).map(i=>[i.deviceId,i])),!this.browserAutoConnectScanTimer&&(this.browserAutoConnectScanTimer=setTimeout(()=>{this.browserAutoConnectScanTimer=null,this.processBrowserAutoConnectSnapshot(t,n);},I.BROWSER_AUTO_CONNECT_SCAN_DEBOUNCE_MS));}async processBrowserAutoConnectSnapshot(e,t){let n=new Map(this.browserAutoConnectPendingDevices),i=new Set(n.keys());for(let s of Array.from(this.browserAutoConnectObservedSignatures.keys()))i.has(s)||(this.browserAutoConnectObservedSignatures.delete(s),this.clearBrowserAutoConnectDeviceState(s));for(let s of n.values()){if(!s.deviceId)continue;let o=s.deviceId;if(!this.isBrowserAutoConnectCandidate(s,e,t)){this.clearBrowserAutoConnectDeviceState(o),this.browserAutoConnectPendingDevices.delete(o);continue}let a=this.browserAutoConnectSignature(s),c=this.browserAutoConnectObservedSignatures.get(o)??null,l=this.browserAutoConnectLastAttemptAt.get(o)??0,d=this.browserAutoConnectBackoffUntilMs.get(o)??0,u=Math.max(d,l+I.BROWSER_AUTO_CONNECT_RETRY_COOLDOWN_MS),p=u>0&&Date.now()>=u;if(c===a&&!p){u>Date.now()&&this.queueBrowserAutoConnectGraceExpiryRecheck(o,u-Date.now()+25);continue}this.browserAutoConnectObservedSignatures.set(o,a),!this.browserAutoConnectInFlight.has(o)&&(this.browserAutoConnectInFlight.add(o),(async()=>{try{if(await this.shouldSuppressBrowserAutoConnectDevice(s,t,""))return;if(await this.hasHealthyBrowserAutoConnectSession(s)){await this.ensureBrowserAutoConnectApplicationConnection(s);let b=typeof s.nodeId=="string"?s.nodeId.trim():void 0;this.deps.hasApplicationRouteForPeer(b)&&this.clearBrowserAutoConnectDeviceState(o);return}if(!await this.shouldAttemptBrowserAutoConnectDial(s,e,t))return;let f=Date.now(),v=this.browserAutoConnectLastAttemptAt.get(o)??0;if(f-v<I.BROWSER_AUTO_CONNECT_RETRY_COOLDOWN_MS)return;if(await this.hasHealthyBrowserAutoConnectSession(s)){await this.ensureBrowserAutoConnectApplicationConnection(s);let b=typeof s.nodeId=="string"?s.nodeId.trim():void 0;this.deps.hasApplicationRouteForPeer(b)&&this.clearBrowserAutoConnectDeviceState(o);return}let m=await this.refreshBrowserAutoConnectDeviceForDial(s);if(!m?.ticket){console.warn("[WasmSignaling][auto-connect][dial] skipped because the refreshed device has no ticket",{deviceId:s.deviceId,cachedTicket:K(s.ticket)});return}if(!this.isBrowserAutoConnectCandidate(m,e,t)){A(`[WasmPresenceManager][auto-connect-dial] BAIL \u2014 refreshed peer is not connectable deviceKey=${o}`),this.clearBrowserAutoConnectDeviceState(o);return}let S=typeof m.nodeId=="string"?m.nodeId.trim():"";if(await this.shouldSuppressBrowserAutoConnectDevice(m,t,"refreshed "))return;if(e&&S&&S===e){A(`[WasmPresenceManager][auto-connect-dial] BAIL \u2014 refreshed peer node is local node deviceKey=${o}`),this.clearBrowserAutoConnectDeviceState(o);return}let w=this.browserAutoConnectSignature(m);if(this.browserAutoConnectPendingDevices.set(o,m),this.browserAutoConnectObservedSignatures.set(o,w),await this.hasHealthyBrowserAutoConnectSession(m)){await this.ensureBrowserAutoConnectApplicationConnection(m);let b=typeof m.nodeId=="string"?m.nodeId.trim():void 0;this.deps.hasApplicationRouteForPeer(b)&&this.clearBrowserAutoConnectDeviceState(o);return}this.browserAutoConnectLastAttemptAt.set(o,f),await this.deps.connectToDevice({deviceId:m.deviceId,endpointTicket:m.ticket});{let b=typeof m.nodeId=="string"?m.nodeId.trim():void 0;if(!this.deps.hasApplicationRouteForPeer(b)){D("[WasmPresenceManager][auto-connect] application route still pending after dial; requeueing recovery",{deviceId:o,nodeId:m.nodeId??null}),this.queueBrowserAutoConnectRecoveryForDevice(m,{preserveRecentDialState:!0});return}}this.browserAutoConnectFailureCount.delete(o),this.browserAutoConnectBackoffUntilMs.delete(o);}catch(h){let f=typeof s.nodeId=="string"?s.nodeId.trim():void 0;if(await this.hasHealthyBrowserAutoConnectSession(s).catch(()=>false)&&this.deps.hasApplicationRouteForPeer(f)){this.clearBrowserAutoConnectDeviceState(o);return}this.applyBrowserAutoConnectFailureBackoff(o),console.warn("[WasmSignaling] browser auto-connect attempt failed:",{deviceId:s.deviceId,ticket:K(s.ticket),failureCount:this.browserAutoConnectFailureCount.get(o)??0,backoffUntilMs:this.browserAutoConnectBackoffUntilMs.get(o)??null,error:h});}finally{this.browserAutoConnectInFlight.delete(o);}})());}}stopPresenceLoop(){this.presenceStartGeneration+=1,this.clearRtdbPresenceRetryTimer(),this.rtdbPresenceRetryAttempt=0,this.presenceState=null;}};I.RTDB_PRESENCE_REGISTER_TIMEOUT_MS=5e3,I.INITIAL_PRESENCE_WRITE_TIMEOUT_MS=5e3,I.RTDB_PRESENCE_RETRY_MIN_DELAY_MS=2e3,I.RTDB_PRESENCE_RETRY_MAX_DELAY_MS=6e4,I.BROWSER_AUTO_CONNECT_SCAN_DEBOUNCE_MS=_.browserAutoConnect.scanDebounceMs,I.BROWSER_AUTO_CONNECT_RETRY_COOLDOWN_MS=_.browserAutoConnect.retryCooldownMs,I.BROWSER_AUTO_CONNECT_SETTLE_GUARD_MS=_.browserAutoConnect.settleGuardMs,I.BROWSER_AUTO_CONNECT_RETRY_MAX_MS=_.browserAutoConnect.retryMaxMs;var fe=I;function j(r){return !r||typeof r!="object"?{}:r instanceof Map?Object.fromEntries(r):r}function J(r){let e=j(r),t=j(e.device);if(!Object.keys(t).length)return e;let n={...t,...e};return delete n.device,n}function g(r,...e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return n}}function F(r,...e){for(let t of e){let n=r[t];if(typeof n=="boolean")return n}}function C(r,...e){for(let t of e){let n=r[t];if(typeof n=="number"&&Number.isFinite(n))return n}}function k(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 Te(...r){let e=r.map(k).filter(t=>typeof t=="number"&&Number.isFinite(t));return e.length?Math.max(...e):void 0}function Pe(r){if(typeof r!="string")return;let e=r.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function lt(r){let e=Pe("presenceStatus"in r?r.presenceStatus:void 0),t="presenceUpdatedAt"in r?k(r.presenceUpdatedAt):void 0,n="presenceExpiresAt"in r?k(r.presenceExpiresAt):void 0,i=t??Te(r.lastSeenAt,r.updatedAt,r.createdAt),s=n??k(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 ut(r){return b$1(r)}function z(r,...e){return ut(g(r,...e))}function X(r){if(!Array.isArray(r))return;let e=Array.from(new Set(r.map(ut).filter(t=>!!t)));return e.length?e:void 0}function pt(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 ht(r,e,t){return t?true:(typeof r.appTag=="string"?r.appTag:typeof r.tag=="string"?r.tag:void 0)===e}function _e(r,e){let t=J(r),n=g(t,"deviceId","device_id")||e||"",i=g(t,"nodeId","node_id")||"",s=g(t,"ticket")||"";return {deviceId:n,deviceName:g(t,"deviceName","device_name")||"Unknown Device",online:!!t.online,ticket:s,presenceStatus:Pe(g(t,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:C(t,"presenceUpdatedAt","presence_updated_at")??Te(t.presenceUpdatedAt,t.presence_updated_at,t.lastSeenAt,t.last_seen_at,t.updatedAt,t.updated_at,t.createdAt,t.created_at),presenceExpiresAt:C(t,"presenceExpiresAt","presence_expires_at")??k(t.presenceExpiresAt??t.presence_expires_at)??k(t.expiresAt??t.expires_at),connectable:F(t,"connectable"),kind:g(t,"kind"),nodeId:i||void 0,platformType:g(t,"platformType","platform_type"),capabilities:t.capabilities||void 0,sessionId:g(t,"sessionId","session_id"),userId:g(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:g(t,"metadata"),excludedPeers:Ee(t.excludedPeers??t.excluded_peers),availableTransports:X(t.availableTransports??t.available_transports),transports:X(t.transports)}}function Ee(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"):[]}function sn(r){let e=lt(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?Ee(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,activeTransport:"activeTransport"in r?r.activeTransport:void 0,parallelTransport:"parallelTransport"in r?r.parallelTransport:void 0,availableTransports:"availableTransports"in r?X(r.availableTransports):"transports"in r?X(r.transports):void 0}}function on(r,e,t){let n=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(!n)return {...r,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:n,scopes:e.scopes?.length?[...e.scopes]:r.scopes,connectionId:e.activeConnectionId??r.connectionId,deviceIdHint:e.deviceIdHint??r.deviceIdHint,activeTransportStableId:e.activeTransportStableId??r.activeTransportStableId,transportGeneration:e.transportGeneration??r.transportGeneration,activeTransport:e.activeTransport??r.activeTransport,parallelTransport:e.parallelTransport===void 0?r.parallelTransport:e.parallelTransport,readinessReason:e.readinessReason??r.readinessReason};let i=e.status??r.connectionStatus,s=typeof i=="string"?i.trim().toLowerCase():"",o=s==="failed"||s==="closed"||s==="disconnected",a=[e.activeTransport,e.parallelTransport].map(f=>typeof f=="string"?f.trim().toLowerCase():"").filter(Boolean),c=!o&&!!e.activeConnectionId&&e.activeTransportStableId!==null&&e.activeTransportStableId!==void 0&&(s==="connected"||s==="connecting")&&e.health==="healthy"&&a.some(f$1),l=e.readinessState==="routable"||c;if(!o&&r.readinessState==="routable"&&(r.connectionStatus==="connected"||r.settledReady)&&!l)return {...r,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:n,scopes:e.scopes?.length?[...e.scopes]:r.scopes,connectionId:e.activeConnectionId??r.connectionId,deviceIdHint:e.deviceIdHint??r.deviceIdHint,activeTransportStableId:e.activeTransportStableId??r.activeTransportStableId,transportGeneration:e.transportGeneration??r.transportGeneration,activeTransport:e.activeTransport??r.activeTransport,parallelTransport:e.parallelTransport===void 0?r.parallelTransport:e.parallelTransport,readinessReason:e.readinessReason??r.readinessReason};let d=o?false:l||r.readinessState==="routable",u=l&&!o&&(s==="connecting"||s==="connected")?"connected":i,p=l?"routable":e.readinessState??r.readinessState,h=d?c&&e.readinessState!=="routable"?"healthy-webrtc-data-plane":e.readinessReason??r.readinessReason??"peer-session-settled":e.readinessReason??r.readinessReason;return {...r,connectionStatus:u,settledReady:d,readinessState:p,readinessReason:h,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:n,scopes:e.scopes?.length?[...e.scopes]:r.scopes,connectionId:e.activeConnectionId??r.connectionId,deviceIdHint:e.deviceIdHint??r.deviceIdHint,activeTransportStableId:e.activeTransportStableId??r.activeTransportStableId,transportGeneration:e.transportGeneration??r.transportGeneration,activeTransport:e.activeTransport??r.activeTransport,parallelTransport:e.parallelTransport===void 0?r.parallelTransport:e.parallelTransport}}function an(r,e){if(e.promotionEligible===false)return {...r,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:false,connectionId:e.connectionId??r.connectionId,deviceIdHint:e.deviceIdHint??r.deviceIdHint,activeTransportStableId:e.activeTransportStableId??r.activeTransportStableId,transportGeneration:e.transportGeneration??r.transportGeneration,activeTransport:e.activeTransport??r.activeTransport,parallelTransport:e.parallelTransport===void 0?r.parallelTransport:e.parallelTransport,scopes:e.scopes?.length?[...e.scopes]:r.scopes};let t=e.status??r.connectionStatus,n=typeof t=="string"?t.trim().toLowerCase():"",i=n==="failed"||n==="closed"||n==="disconnected",s=e.routable===true||e.protocolState==="routable"||r.readinessState==="routable",o=e.transportState==="connected"&&e.health==="healthy",a=i?false:s,c=!i&&(s||o)&&(n==="connecting"||n==="connected"||e.transportState==="connected")?"connected":t,l=a?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??r.readinessState??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),d=a?r.readinessReason??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??r.readinessReason??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...r,connectionStatus:c,settledReady:a,readinessState:l,readinessReason:d,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:e.promotionEligible??r.promotionEligible??true,connectionId:e.connectionId??r.connectionId,deviceIdHint:e.deviceIdHint??r.deviceIdHint,activeTransportStableId:e.activeTransportStableId??r.activeTransportStableId,transportGeneration:e.transportGeneration??r.transportGeneration,activeTransport:e.activeTransport??r.activeTransport,parallelTransport:e.parallelTransport===void 0?r.parallelTransport:e.parallelTransport,scopes:e.scopes?.length?[...e.scopes]:r.scopes}}function cn(r){let{device:e,session:t=null,peer:n=null,isPromotionEligible:i}=r,s=sn(e);return t&&(s=on(s,t,i)),n&&(s=an(s,n)),s}function ft(r){let e=J(r),t=_e(e),n=Pe(g(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),i=lt({...t,...n?{presenceStatus:n}:{},presenceUpdatedAt:C(e,"presenceUpdatedAt","presence_updated_at")??Te(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:C(e,"presenceExpiresAt","presence_expires_at")??k(e.presenceExpiresAt??e.presence_expires_at)??k(e.expiresAt??e.expires_at),connectable:F(e,"connectable")}),s={...t,...i,connectionStatus:g(e,"connectionStatus","connection_status")||"disconnected",settledReady:F(e,"settledReady","settled_ready")??false,readinessState:g(e,"readinessState","readiness_state")??void 0,readinessReason:g(e,"readinessReason","readiness_reason")??void 0,peerHealth:g(e,"peerHealth","peer_health")||"unknown",peerId:g(e,"peerId","peer_id"),scopes:Ee(e.scopes),connectionId:g(e,"connectionId","connection_id"),deviceIdHint:g(e,"deviceIdHint","device_id_hint"),activeTransportStableId:C(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:C(e,"transportGeneration","transport_generation")??void 0,activeTransport:z(e,"activeTransport","active_transport"),parallelTransport:z(e,"parallelTransport","parallel_transport")??null,availableTransports:X(e.availableTransports??e.available_transports)};return cn({device:s})}function gt(r){let e=J(r);return {peerId:g(e,"peerId","peer_id")||"",deviceId:g(e,"deviceId","device_id"),deviceIdHint:g(e,"deviceIdHint","device_id_hint"),nodeId:g(e,"nodeId","node_id"),activeConnectionId:g(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:g(e,"status")||"disconnected",health:g(e,"health")||"unknown",settledReady:F(e,"settledReady","settled_ready")??false,readinessState:g(e,"readinessState","readiness_state")??void 0,activeTransportStableId:C(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:C(e,"transportGeneration","transport_generation")??void 0,activeTransport:z(e,"activeTransport","active_transport"),parallelTransport:z(e,"parallelTransport","parallel_transport")??null,replacementPending:F(e,"replacementPending","replacement_pending")??void 0,lastLifecycleTransitionAtMs:C(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:g(e,"readinessReason","readiness_reason")??void 0,transitionCount:C(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:C(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:C(e,"replacementCount","replacement_count")??void 0,retireCount:C(e,"retireCount","retire_count")??void 0,lastDisconnectReason:g(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:g(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:g(e,"error")}}function jn(r){let e=j(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,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs: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 Xn(r){let e=j(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 dn(r){switch(r){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function vt(r){let e=r.activeConnectionId||r.candidateConnectionIds[0]||null;if(!e)return null;let t=dn(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,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 mt(r){let e=j(r),t=g(e,"connectionId","connection_id");if(!t)return null;let n=g(e,"state")||"connecting",i=C(e,"createdAt","created_at")??C(e,"updatedAt","updated_at")??Date.now(),s=C(e,"updatedAt","updated_at")??i;return {connectionId:t,deviceId:g(e,"deviceId","device_id"),deviceIdHint:g(e,"deviceIdHint","device_id_hint"),remoteNodeId:g(e,"remoteNodeId","remote_node_id"),state:n,transportState:g(e,"transportState","transport_state")??(n==="connected"?"connected":n==="connecting"?"connecting":"closed"),protocolState:g(e,"protocolState","protocol_state")??(n==="connected"?"routable":n==="connecting"?"connecting":"closed"),routable:F(e,"routable")??false,readinessState:g(e,"readinessState","readiness_state")??void 0,readinessReason:g(e,"readinessReason","readiness_reason")??void 0,transportGeneration:C(e,"transportGeneration","transport_generation")??void 0,activeTransportStableId:C(e,"activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:z(e,"activeTransport","active_transport"),parallelTransport:z(e,"parallelTransport","parallel_transport")??null,replacementInProgress:F(e,"replacementInProgress","replacement_in_progress")??void 0,lastLifecycleTransitionAtMs:C(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:C(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:C(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:C(e,"replacementCount","replacement_count")??void 0,retireCount:C(e,"retireCount","retire_count")??void 0,lastDisconnectReason:g(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:g(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:g(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.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 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 un(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:E(n),tokenFingerprint:E(o),tokenSuffixFingerprint:E(i),scope:a,maxConnections:c}}var y=class y{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserFirestoreSignaling=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.autoConnectRecoveryUnsubscribe=null;this.coreClient=null;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=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.presenceManager=new fe({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)=>this.registerRtdbPresence(n,i,s),isRtdbPresenceDisabledForSession:()=>this.rtdbPresenceDisabledForSession,getRtdbTicketVersion:()=>this.rtdbTicketVersion,getPeerSession:n=>this.getPeerSession(n),isConnected:n=>this.isConnected(n),hasApplicationRouteForPeer:n=>this.coreClient?.hasApplicationRouteForPeer?.(void 0,n)??false,connectToDevice:n=>this.connectToDevice(n),getBrowserFirestoreSignaling:()=>this.getBrowserFirestoreSignaling(),getLastDeliveredConnectionStates:()=>this.lastDeliveredConnectionStates.values(),forceReconnectSnapshot:()=>this.forceReconnectSnapshot()}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()){this.app=null,this.auth=null;return}let t=D$1();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.browserFirestoreSignaling?.handleScopeChange(),this.authListeners.forEach(o=>o(this.toRuntimeIdentity(n)));});}get rtdbPresence(){return this._rtdbPresence}get tag(){return this.appTag}getRuntimeCapabilities(){return V(te)}getDeviceIdentityStorageKey(){let e=f(this.options);return `${y.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getNodeIdPersistenceMode(){return 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.getNodeIdPersistenceMode();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+y.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:o,expiresAt:d})),o}let c=this.createRandomDeviceId(),l=i+y.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.browserFirestoreSignaling||(this.browserFirestoreSignaling=new le({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.browserFirestoreSignaling}withWebPresenceMetadata(e,t){if(!e||!e.trim())return JSON.stringify({deviceId:t});try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return JSON.stringify({...n,deviceId:t})}catch{}return JSON.stringify({deviceId:t,metadata:e})}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.browserFirestoreSignaling?.handleScopeChange(),this.authListeners.forEach(n=>n(this.currentUser));}async ensureBrowserFirestoreAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await D$1().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 pt(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 ht(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.browserFirestoreSignaling?.stopRtdbPresence();}async registerRtdbPresence(e,t,n,i){if(this.isTicketOnlyMode())return;if(!this._rtdbPresence)try{this._rtdbPresence=new he(this.app);}catch(a){throw this.disableRtdbPresenceForSession("RTDB service unavailable",a),a}this.rtdbPresenceScope=e;let s=n??this.rtdbTicketVersion;this.getBrowserFirestoreSignaling().setRtdbPresence(this._rtdbPresence,e);try{await this._rtdbPresence.registerDevice(e,t,s,i);}catch(a){throw this.disableRtdbPresenceForSession("registerDevice failed",a),a}}async stopAuthScopedActivity(e){ze("WasmBridge.stopAuthScopedActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1;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.stopAutoConnectRecoverySubscription(),this.presenceManager.stop(),this.rtdbPresenceDisabledForSession=false,this.rtdbPresenceScope=null,this.rtdbTicketVersion=0,this.browserFirestoreSignaling?.stopAuthScopedActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.hasSyncedAuthToWasmClient=false,this.lastDeliveredConnectionStates.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 r(t);return this.wasmClient??null}normalizeDevice(e,t){return _e(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}normalizeDeviceStatusSnapshot(e){return ft(e)}normalizePeerSessionSnapshot(e){return gt(e)}toBackendConnectionStateFromPeerSession(e){return vt(e)}normalizeConnectionStateSnapshot(e){return mt(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.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 browserAutoConnectPendingDevices(){return this.presenceManager.pendingDevices}set browserAutoConnectPendingDevices(e){this.presenceManager.pendingDevices=e;}async processBrowserAutoConnectSnapshot(e,t){await this.presenceManager.processBrowserAutoConnectSnapshot(e,t);}async hasHealthyBrowserAutoConnectSession(e){return this.presenceManager.hasHealthyBrowserAutoConnectSession(e)}get startedAutoConnectKey(){return this.presenceManager.autoConnectKey}set startedAutoConnectKey(e){this.presenceManager.autoConnectKey=e;}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}triggerBrowserAutoConnectRecovery(e){this.presenceManager.triggerBrowserAutoConnectRecovery(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 D$1().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await D$1().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 D$1().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await D$1().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.getNodeIdPersistenceMode()==="ephemeral"?y.EPHEMERAL_DEVICE_ID_TTL_MS:i,l=this.withWebPresenceMetadata(s,a);if(this.presenceManager.updatePresenceLoopState({localNodeId:e,ticket:t,metadata:l,deviceName:o?.trim()||this.getDefaultBrowserDeviceName()}),await this.getBrowserFirestoreSignaling().updatePresence(e,t,n,c,l,o),this._rtdbPresence&&this.rtdbPresenceScope){let d=this.resolveWebLogicalDeviceId();d&&(this.rtdbTicketVersion+=1,this._rtdbPresence.bumpTicketVersion(this.rtdbPresenceScope,d,this.rtdbTicketVersion,{ticket:t,nodeId:e,deviceName:o?.trim()||this.getDefaultBrowserDeviceName(),metadata:l}).catch(u=>console.warn("[WasmBridge] RTDB ticketVersion bump failed:",u)));}}async setOffline(e){if(this.presenceManager.stopPresence(),!this.isTicketOnlyMode()){if(this._rtdbPresence&&this.rtdbPresenceScope){let t=this.resolveWebLogicalDeviceId();t&&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 [];let e=this.getDiscoveryScopeId();if(!e)return [];let t=await this.waitForWasmClient(500);if(t&&typeof t.devices_with_status=="function"){let i=await t.devices_with_status(e);return (Array.isArray(i)?i:[]).filter(a=>this.matchesTag(J(a))).map(a=>this.normalizeDeviceStatusSnapshot(a))}return (await this.getBrowserFirestoreSignaling().listDevices()).map(i=>this.normalizeDeviceStatusSnapshot({...i,connectionStatus:i.online?"online":"disconnected"}))}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(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.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: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: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: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);if(!i)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:i}}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,transportStableId:typeof i.transportStableId=="number"?i.transportStableId:null,transportSource:typeof i.transportSource=="string"?i.transportSource:null,lastTransportChangeAtMs:typeof i.lastTransportChangeAtMs=="number"?i.lastTransportChangeAtMs: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()}startAutoConnect(e,t){this.presenceManager.startAutoConnect(e,t),this.startAutoConnectRecoverySubscription();let n=this.authScopedRuntimeGeneration;(async()=>{let i=await this.waitForWasmClient();if(n===this.authScopedRuntimeGeneration&&!(!i||typeof i.start_auto_connect!="function"))try{await i.start_auto_connect(e,t);}catch(s){console.warn("[WasmBridge] failed to record auto-connect context on wasm client",{userId:e,localDeviceId:t,error:s});}})();}async startAutoConnectOnce(e,t){this.startAutoConnect(e,t),this.forceReconnectSnapshot();}startAutoConnectRecoverySubscription(){if(this.autoConnectRecoveryUnsubscribe)return;let e=this.onConnectionStateChange(t=>{let n=typeof t.state=="string"?t.state:"";(n==="closed"||n==="failed")&&this.presenceManager.triggerBrowserAutoConnectRecovery(t);});typeof e=="function"?this.autoConnectRecoveryUnsubscribe=e:e.then(t=>{typeof t=="function"&&(this.autoConnectRecoveryUnsubscribe=t);});}stopAutoConnectRecoverySubscription(){if(this.autoConnectRecoveryUnsubscribe){try{this.autoConnectRecoveryUnsubscribe();}catch(e){console.warn("[WasmBridge] auto-connect recovery unsubscribe failed",e);}this.autoConnectRecoveryUnsubscribe=null;}}notifyDisconnectRequested(e){this.presenceManager.notifyDisconnectRequested(e);}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}let n=this.browserAutoConnectPendingDevices.get(e),i=typeof n?.nodeId=="string"&&n.nodeId.trim().length>0?n.nodeId.trim():null;try{await t.disconnect_device(e,i);}catch(s){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,nodeIdHint:i,error:s?.message??String(s)}),s}}setCoreClient(e){e&&typeof e.connect=="function"?this.coreClient=e:this.coreClient=null;}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();D("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:un(e.endpointTicket),hasCoreClient:!!this.coreClient});let i=await t.connect_device(e.deviceId??null,e.endpointTicket);D("[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{D("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:i?.remoteNodeId??null,connectionId:i?.connectionId??null});let a=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});D("[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(){if(!this.isTicketOnlyMode()&&!(!this.app||!this.auth)){this.startAutoConnectRecoverySubscription();try{this.presenceManager.forceBrowserAutoConnectSnapshot();}catch{}}}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=b(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):false}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&&ve("[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&&ve("[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=false,i=a=>{let c=a.detail,l=typeof c?.connectionId=="string"?c.connectionId.trim():"";!l||n||(async()=>{let d=this.normalizeConnectionStateSnapshot(c),u=await this.waitForWasmClient(500);if(!n){if(u&&typeof u.connection_state=="function"){let p=await u.connection_state(l),h=this.normalizeConnectionStateSnapshot(p);if(!n&&h){this.deliverConnectionState(h,e,"rust-event",t);return}}!n&&d&&this.deliverConnectionState(d,e,"rust-event-detail",t);}})().catch(d=>{n||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:l,error:d});});},s=typeof window<"u"?window:null,o=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return o&&s.addEventListener("connection-state-changed",i),this.getConnectionStates().then(a=>{n||a.forEach(c=>this.deliverConnectionState(c,e,"replay",t));}).catch(a=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",a);}),()=>{n=true,o&&s.removeEventListener("connection-state-changed",i);}}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 y.FALLBACK_EXPLICIT_FILE_NAME;let i="";for(let o of n){if([...i].length>=y.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===".."?y.FALLBACK_EXPLICIT_FILE_NAME:s}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return y.FALLBACK_EXPLICIT_MIME_TYPE;let n="";for(let i of t){if(n.length>=y.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:y.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>y.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}async sendExplicitFileData(e){let t=e.connection,n=e.file,i=e.applicationCrypto??this.options.applicationCrypto,s=e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true;if(s&&!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=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(D("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:a??null,fileName:n.name,fileSize:n.size,transferId:o}),!a)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let c=await this.waitForWasmClient();if(!c)throw new Error("WASM explicit transfer requires an initialized WASM client");let l=new TextEncoder,d={transfer_id:o,filename:this.sanitizeExplicitFileName(n.name),size:n.size,mime_type:this.sanitizeExplicitMimeType(n.type)},u=l.encode(JSON.stringify(d));this.assertExplicitTransferHeaderSize(u);let p=new Uint8Array(4);new DataView(p.buffer).setUint32(0,u.byteLength,false);let h=new Uint8Array(p.byteLength+u.byteLength);h.set(p,0),h.set(u,p.byteLength);let f=async()=>{let S=c.open_peer_bi_explicit_file_sender;if(typeof S!="function")return false;let w=await S.call(c,a,5e3),b=w?.writable??w?.send;if(!b||typeof b.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");D("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:a,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let R=b.getWriter();try{await R.write(h);let P=new Uint8Array(await n.arrayBuffer());for(let T=0;T<P.byteLength;T+=y.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let M=P.slice(T,Math.min(T+y.EXPLICIT_FILE_CHUNK_SIZE_BYTES,P.byteLength));await R.write(M);}}finally{await R.close().catch(()=>{}),R.releaseLock();}return true},v=async()=>{if(typeof c.open_bi!="function")throw new Error("WASM explicit transfer requires open_bi support");let S=await c.open_bi(a);D("[WasmBridge] sendExplicitFileData open_bi resolved",{remoteNodeId:a,transferId:e.transferId??null});let w=S.send.getWriter();try{await w.write(new Uint8Array([y.EXPLICIT_FILE_PROTOCOL_TYPE])),await w.write(p),await w.write(u);let b=new Uint8Array(await n.arrayBuffer());for(let R=0;R<b.byteLength;R+=y.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let P=b.slice(R,Math.min(R+y.EXPLICIT_FILE_CHUNK_SIZE_BYTES,b.byteLength));await w.write(P);}}finally{await w.close().catch(()=>{}),w.releaseLock();}},m=async()=>{if(typeof c.open_bi!="function")throw new Error("WASM explicit transfer requires open_bi support");if(!i)throw new Error("WASM encrypted explicit transfer requires application crypto");let S=await c.open_bi(a);D("[WasmBridge] sendExplicitFileData encrypted fallback open_bi resolved",{remoteNodeId:a,transferId:e.transferId??null});let w=Ke(i),b=P=>{let T=w.protectFrame(P),M=new Uint8Array(4+T.byteLength);return new DataView(M.buffer).setUint32(0,T.byteLength,false),M.set(T,4),M},R=S.send.getWriter();try{await R.write(new Uint8Array([y.EXPLICIT_FILE_PROTOCOL_TYPE])),await R.write(b(h));let P=new Uint8Array(await n.arrayBuffer());for(let T=0;T<P.byteLength;T+=y.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let M=P.slice(T,Math.min(T+y.EXPLICIT_FILE_CHUNK_SIZE_BYTES,P.byteLength));await R.write(b(M));}}finally{await R.close().catch(()=>{}),R.releaseLock();}};try{if(await f())return;if(s)throw new Error("[WasmBridge] Explicit transfer requires the crypto-wrapped open_peer_bi_explicit_file_sender path under mandatory application crypto, but it is unavailable on this WASM build. Rebuild the openrtc WASM (pnpm --filter openrtc build:wasm) \u2014 a raw open_bi fallback is intentionally not used for mandatory-crypto app data.");i?await m():await v();}finally{D("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:a,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);}};y.EXPLICIT_FILE_PROTOCOL_TYPE=2,y.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,y.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,y.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",y.MAX_EXPLICIT_FILE_NAME_CHARS=180,y.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",y.MAX_EXPLICIT_MIME_TYPE_CHARS=255,y.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",y.EPHEMERAL_DEVICE_ID_TTL_MS=_.browserIdentity.ephemeralDeviceIdTtlMs;var bt=y;var St=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 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 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 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():V(te)}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);}};export{he as a,It as b,ve as c,D as d,A as e,Pt as f,gn as g,Ke as h,ze as i,J as j,cn as k,ft as l,gt as m,jn as n,Xn as o,mt as p,_ as q,yn as r,te as s,Mt as t,V as u,Sn as v,In as w,E as x,bt as y,St as z};
@@ -1,6 +1,6 @@
1
- import { A as AuthContext, R as RuntimeCapabilities, a as RuntimeCapabilityProfile } from './DelegatingRuntimeAdapter-CjHzBEBA.js';
2
- import { J as ConnectionOptions, q as ApplicationPayloadCrypto, v as ApplicationPayloadReadinessOptions, w as ApplicationPayloadRouteOptions, n as ProtocolName, x as ApplicationPayloadSendOptions, K as ChannelDescriptor$1, L as LocalDeviceInfo, O as IncomingStreamChannelMetadata, C as ClientOptions, a as Device, f as SignalingSession, R as RuntimeIdentity, b as DeviceStatusSnapshot, Q as ManagedDeviceConnectOptions, T as PeerState, U as PeerHealth, V as JoinRoomOptions, W as RoomMember, X as PeerScope, j as BackendConnectionState, Y as PeerLifecycleStatus, P as PeerSessionSnapshot, G as GrantScope, I as ISignalingBackend, l as ConnectDeviceHooks, m as ConnectDeviceOptions, k as ConnectDeviceResult, M as ManagedConnectionRecord, c as ResolvedPeerIdentity, t as AppLimits, i as NativeConnectResult, E as ExplicitFileDataSendParams } from './types-DyCGvj9l.js';
3
- import { P as PlutoIpcBridge, I as IpcRuntimeAdapter } from './IpcRuntimeAdapter-CtckyMol.js';
1
+ import { A as AuthContext, R as RuntimeCapabilities, a as RuntimeCapabilityProfile } from './DelegatingRuntimeAdapter-BxOcVIx_.js';
2
+ import { a2 as ConnectionOptions, q as ApplicationPayloadCrypto, v as ApplicationPayloadReadinessOptions, w as ApplicationPayloadRouteOptions, n as ProtocolName, x as ApplicationPayloadSendOptions, a0 as ChannelDescriptor$1, L as LocalDeviceInfo, T as IncomingStreamChannelMetadata, C as ClientOptions, a as Device, f as SignalingSession, R as RuntimeIdentity, b as DeviceStatusSnapshot, a3 as ManagedDeviceConnectOptions, Z as PeerState, $ as PeerHealth, O as JoinRoomOptions, Q as RoomMember, _ as PeerScope, j as BackendConnectionState, y as DevicePresenceStatus, a4 as PeerLifecycleStatus, P as PeerSessionSnapshot, G as GrantScope, I as ISignalingBackend, l as ConnectDeviceHooks, m as ConnectDeviceOptions, k as ConnectDeviceResult, M as ManagedConnectionRecord, c as ResolvedPeerIdentity, t as AppLimits, i as NativeConnectResult, E as ExplicitFileDataSendParams } from './types-D0fRvUbN.js';
3
+ import { P as PlutoIpcBridge, I as IpcRuntimeAdapter } from './IpcRuntimeAdapter-U5AEH0jn.js';
4
4
  import { WasmRuntimeAdapter } from './runtime/WasmRuntimeAdapter.js';
5
5
 
6
6
  interface ITransport {
@@ -324,6 +324,7 @@ declare class Connection {
324
324
  * this predicate, not bypass it.
325
325
  */
326
326
  isMoQApplicationRouteReady(): boolean;
327
+ private isMoQDataRouteReady;
327
328
  private sendInternalSignal;
328
329
  receiveInternalSignal(content: any): void;
329
330
  private handleInternalSignal;
@@ -442,6 +443,7 @@ interface RuntimeScopedLogicalChannel {
442
443
  */
443
444
  type RuntimeDeviceStatusSnapshot = Omit<DeviceStatusSnapshot, 'nodeId'>;
444
445
  type RuntimeDeviceStatus = RuntimeDeviceStatusSnapshot;
446
+ type RuntimeDevicePresenceStatus$1 = DevicePresenceStatus;
445
447
  type RuntimeIncomingStream = {
446
448
  type: 'bi' | 'uni';
447
449
  stream: any;
@@ -832,6 +834,7 @@ declare class RuntimeClient {
832
834
  private readonly managedReconciliationTasks;
833
835
  private managedReconciliationTimer;
834
836
  private readonly managedReconciliationFollowupTimers;
837
+ private nativeIncomingMessageSubscriptionAttached;
835
838
  /**
836
839
  * The one per-`{scope, peerNodeId}` observer-side dial coalescer. It is
837
840
  * intentionally separate from the peer lifecycle read model: it requests a
@@ -880,6 +883,9 @@ declare class RuntimeClient {
880
883
  getRuntimePolicy(): RuntimePolicySnapshot;
881
884
  getRuntimeCapabilities(): RuntimeCapabilities;
882
885
  getCapabilityProfile(): RuntimeCapabilityProfile;
886
+ private attachNativeIncomingMessageSubscription;
887
+ private attachNativeIncomingStreamSource;
888
+ private resolveNativeIncomingStreamSource;
883
889
  start(options?: {
884
890
  clearSessionTokens?: boolean;
885
891
  }): Promise<void>;
@@ -1224,4 +1230,65 @@ declare function createWasmClient(options: RuntimeFactoryOptions): PlutoRuntimeA
1224
1230
  */
1225
1231
  declare function createIpcClient(options: RuntimeFactoryOptions, bridge: PlutoIpcBridge): PlutoRuntimeAssembly<IpcRuntimeAdapter>;
1226
1232
 
1227
- export { type RuntimeSession as $, type PeerReadiness as A, type PeerStreamOptions as B, Connection as C, type DeviceProfile as D, type PresenceLoopOptions as E, type RawConnection as F, type RuntimeAuthContext as G, type RuntimeAuthIdentity as H, type ITransport as I, type RuntimeAutoConnectPolicy as J, type RuntimeConnectionTarget as K, type RuntimeDeviceStatus as L, type RuntimeJoinRoomOptions as M, type RuntimeLogicalChannelFraming as N, OPENRTC_RUNTIME_POLICY as O, type PeerReconciliationStats as P, type RuntimeManagedSession as Q, type RuntimeClientOptions as R, type RuntimeManagedSessionKind as S, type RuntimeManagedSessionOptions as T, type RuntimeManagedSessionPlatform as U, type RuntimePeerLifecycleStatus as V, type RuntimePeerScope as W, type RuntimePeerSessionSnapshot as X, type RuntimePresenceLoopOptions as Y, type RuntimePresencePolicy as Z, type RuntimeRoomMember as _, RuntimeClient as a, type RuntimeUiConnectionStatus as a0, type ScopedChannelOptions as a1, type ScopedLogicalChannel as a2, ScopedSession as a3, type Session as a4, type SessionOptions as a5, getRuntimePolicy as a6, type RuntimeFactoryOptions as a7, DriveGrantActorError as a8, type DriveGrantActorErrorKind as a9, DriveGrantActorHandle as aa, type DriveGrantActorHandleOptions as ab, DriveGrantActorRegistry as ac, type DriveGrantActorState as ad, type DriveGrantClose as ae, type DriveGrantDial as af, type DriveGrantConnectionKey as ag, type DriveGrantLogicalChannelHandle as ah, type DriveGrantPreferredTransport as ai, type Session$1 as aj, type SessionOptions$1 as ak, createIpcClient as al, createWasmClient as am, driveGrantConnectionKey as an, driveGrantConnectionKeyToString as ao, type RuntimeDevice as b, type RuntimeDeviceStatusSnapshot as c, type RuntimeDeviceConnectOptions as d, type RuntimeLocalDeviceInfo as e, type RuntimeLocalDeviceProfile as f, type RuntimePeerState as g, type RuntimePeerConnectOptions as h, type RuntimePeerReadinessSnapshot as i, type RuntimePeerHealth as j, type RuntimeChannelDescriptor as k, type RuntimePeerStreamOptions as l, type RuntimeIncomingStream as m, type RuntimeScopedChannelOptions as n, type RuntimeScopedLogicalChannel as o, type RuntimePolicySnapshot as p, type RuntimeConnectionStateSnapshot as q, type RuntimeApplicationPayloadReadinessOptions as r, type RuntimeConnectionEvent as s, type PlutoRuntimeAssembly as t, type RuntimeRawConnection as u, type ChannelDescriptor as v, type ConnectionEvent as w, type ConnectionTarget as x, type IncomingStream as y, type PeerConnectOptions as z };
1233
+ interface RuntimeDeviceActiveOptions {
1234
+ now?: number;
1235
+ /**
1236
+ * Optional local freshness window for durable roster rows. Leave undefined
1237
+ * when the caller only wants to honor explicit online/expiresAt state.
1238
+ */
1239
+ staleAfterMs?: number;
1240
+ }
1241
+ type RuntimeDeviceActivityStatus = Pick<Partial<RuntimeDevice>, 'online' | 'lastSeenAt' | 'updatedAt' | 'createdAt' | 'expiresAt'>;
1242
+ type RuntimeDeviceRouteStatus = Pick<Partial<RuntimeDeviceStatusSnapshot>, 'settledReady' | 'readinessState' | 'connectionStatus'>;
1243
+ type RuntimeDevicePresenceStatus = Pick<RuntimeDevice, 'online' | 'ticket'> & Pick<Partial<RuntimeDeviceStatusSnapshot>, 'connectable' | 'presenceStatus' | 'online' | 'ticket'>;
1244
+ /**
1245
+ * True when a runtime device row is currently live enough to display or
1246
+ * consider for app-level routing. This is deliberately separate from
1247
+ * `isRuntimeDeviceConnectable`: a peer can be active/present before it has a
1248
+ * usable ticket, and a stale durable row should not keep app UIs alive.
1249
+ */
1250
+ declare function isRuntimeDeviceActive(device: RuntimeDeviceActivityStatus, options?: RuntimeDeviceActiveOptions): boolean;
1251
+ /**
1252
+ * True once OpenRTC has a routable peer projection for normal app payloads.
1253
+ *
1254
+ * This intentionally does not inspect discovery metadata or device
1255
+ * capabilities. Those fields describe the remote endpoint roster entry; they
1256
+ * are not proof that an application-level protocol has exchanged its own
1257
+ * ready/capability message over the mesh.
1258
+ */
1259
+ declare function isRuntimeDeviceRoutable(device: RuntimeDeviceRouteStatus): boolean;
1260
+ /**
1261
+ * True when the discovery row currently has enough fresh presence to attempt
1262
+ * a dial. This is a discovery gate, not a connected/readiness gate.
1263
+ */
1264
+ declare function isRuntimeDeviceConnectable(device: RuntimeDevicePresenceStatus): boolean;
1265
+
1266
+ /**
1267
+ * Pure byte / stream / timing helpers.
1268
+ *
1269
+ * Extracted from the `Client` god object (see
1270
+ * `docs/plans/client-ts-decomposition.md` Phase 1). These functions are
1271
+ * deliberately pure — no `Client` state, no `this`, no logging side effects — so
1272
+ * the same helper is reused everywhere instead of being re-implemented inline
1273
+ * (e.g. `concatBytes` previously existed both here and in `applicationCrypto.ts`,
1274
+ * and three near-identical exponential-backoff helpers existed across the class).
1275
+ */
1276
+
1277
+ type ByteArray = Uint8Array<ArrayBuffer>;
1278
+ type ByteArrayLike = Uint8Array<ArrayBufferLike>;
1279
+
1280
+ type RuntimeU32BEFrameHandler = (payload: ByteArray) => void;
1281
+ type RuntimeJsonFrameHandler<T = unknown> = (value: T, payload: ByteArray) => void;
1282
+ interface RuntimeJsonFrameDecoderOptions {
1283
+ onInvalidJson?: (error: unknown, payload: ByteArray) => void;
1284
+ }
1285
+ declare function encodeRuntimeU32BEFrame(payload: ByteArrayLike): ByteArray;
1286
+ declare function createRuntimeU32BEFrameDecoder(onFrame: RuntimeU32BEFrameHandler): (chunk: ByteArrayLike) => void;
1287
+ declare function encodeRuntimeJsonPayload(value: unknown): ByteArray;
1288
+ declare function decodeRuntimeJsonPayload<T = unknown>(payload: ByteArrayLike): T;
1289
+ declare function encodeRuntimeJsonFrame(value: unknown): ByteArray;
1290
+ declare function createRuntimeJsonFrameDecoder<T = unknown>(onValue: RuntimeJsonFrameHandler<T>, options?: RuntimeJsonFrameDecoderOptions): (chunk: ByteArrayLike) => void;
1291
+ declare function concatRuntimeBytes(a: ByteArrayLike, b: ByteArrayLike): ByteArray;
1292
+ declare function readRuntimeU32BE(bytes: ByteArrayLike, offset: number): number;
1293
+
1294
+ export { type RuntimePresenceLoopOptions as $, type ConnectionEvent as A, type ConnectionTarget as B, Connection as C, type DeviceProfile as D, type IncomingStream as E, type PeerConnectOptions as F, type PeerReadiness as G, type PeerStreamOptions as H, type ITransport as I, type PresenceLoopOptions as J, type RawConnection as K, type RuntimeAuthContext as L, type RuntimeAuthIdentity as M, type RuntimeAutoConnectPolicy as N, OPENRTC_RUNTIME_POLICY as O, type PeerReconciliationStats as P, type RuntimeConnectionTarget as Q, type RuntimeClientOptions as R, type RuntimeDevicePresenceStatus$1 as S, type RuntimeDeviceStatus as T, type RuntimeJsonFrameHandler as U, type RuntimeLogicalChannelFraming as V, type RuntimeManagedSessionKind as W, type RuntimeManagedSessionPlatform as X, type RuntimePeerLifecycleStatus as Y, type RuntimePeerScope as Z, type RuntimePeerSessionSnapshot as _, RuntimeClient as a, type RuntimePresencePolicy as a0, type RuntimeSession as a1, type RuntimeU32BEFrameHandler as a2, type RuntimeUiConnectionStatus as a3, type ScopedChannelOptions as a4, type ScopedLogicalChannel as a5, ScopedSession as a6, type Session as a7, type SessionOptions as a8, createRuntimeJsonFrameDecoder as a9, createIpcClient as aA, createWasmClient as aB, readRuntimeU32BE as aC, driveGrantConnectionKey as aD, driveGrantConnectionKeyToString as aE, createRuntimeU32BEFrameDecoder as aa, decodeRuntimeJsonPayload as ab, encodeRuntimeJsonFrame as ac, encodeRuntimeJsonPayload as ad, encodeRuntimeU32BEFrame as ae, getRuntimePolicy as af, isRuntimeDeviceActive as ag, isRuntimeDeviceConnectable as ah, isRuntimeDeviceRoutable as ai, type RuntimeDeviceActiveOptions as aj, type RuntimeFactoryOptions as ak, type RuntimeJsonFrameDecoderOptions as al, DriveGrantActorError as am, type DriveGrantActorErrorKind as an, DriveGrantActorHandle as ao, type DriveGrantActorHandleOptions as ap, DriveGrantActorRegistry as aq, type DriveGrantActorState as ar, type DriveGrantClose as as, type DriveGrantDial as at, type DriveGrantConnectionKey as au, type DriveGrantLogicalChannelHandle as av, type DriveGrantPreferredTransport as aw, type Session$1 as ax, type SessionOptions$1 as ay, concatRuntimeBytes as az, type RuntimeManagedSessionOptions as b, type RuntimeManagedSession as c, type RuntimeDevice as d, type RuntimeDeviceStatusSnapshot as e, type RuntimeDeviceConnectOptions as f, type RuntimeLocalDeviceInfo as g, type RuntimeLocalDeviceProfile as h, type RuntimePeerState as i, type RuntimePeerConnectOptions as j, type RuntimePeerReadinessSnapshot as k, type RuntimePeerHealth as l, type RuntimeChannelDescriptor as m, type RuntimePeerStreamOptions as n, type RuntimeIncomingStream as o, type RuntimeScopedChannelOptions as p, type RuntimeScopedLogicalChannel as q, type RuntimeJoinRoomOptions as r, type RuntimeRoomMember as s, type RuntimePolicySnapshot as t, type RuntimeConnectionStateSnapshot as u, type RuntimeApplicationPayloadReadinessOptions as v, type RuntimeConnectionEvent as w, type PlutoRuntimeAssembly as x, type RuntimeRawConnection as y, type ChannelDescriptor as z };