openrtc 1.0.15 → 1.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ import {h,b as b$1}from'./chunk-QT2ASNI3.js';import {v,b,d,c,G,e,u,a,w,t,E as E$1,x as x$1}from'./chunk-HBMXO563.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';import {getFirestore,connectFirestoreEmulator,Timestamp,getDoc,serverTimestamp as serverTimestamp$1,setDoc,updateDoc,deleteDoc,collection,doc,getDocs,query,where,limit,onSnapshot,getDocFromServer}from'firebase/firestore';import {getAuth}from'firebase/auth';import {getDatabase,connectDatabaseEmulator,onValue,ref,onDisconnect,set,onChildAdded,onChildChanged,onChildRemoved,serverTimestamp,get}from'firebase/database';import {httpsCallable,getFunctions}from'firebase/functions';import*as Ee from'tweetnacl';function en(){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 ke(r,e,t){if(en()){if(typeof t>"u"){console[r](e);return}console[r](e,t);}}function ue(r,e){ke("debug",r,e);}function R(r,e){ke("info",r,e);}function Oi(r,e){ke("log",r,e);}var B=new Uint8Array([79,82,84,67,69,49]),pe=2,K=8,X=24,at=32,tn=3,nn=16*1024*1024,rn=4096;function sn(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 on(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 an(r,e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return `${r}:${t}`}function ct(r){if(!sn(r,B))return null;let e=r[B.byteLength];return e===pe?e:null}function cn(r){return ct(r)===pe&&r.byteLength>B.byteLength+1+K+X}function Gi(r,e={}){if(!(r instanceof Uint8Array)||r.byteLength!==at)throw new Error(`[OpenRTC] application payload crypto key must be ${at} bytes`);let t=new Uint8Array(r),n=e.requireEncrypted??true,i=e.randomBytes??on,s=e.replayProtection??true,o=0,a=new Set,c=[];return {requireEncrypted:n,protectPayload(d,l){let u=i(X);if(!(u instanceof Uint8Array)||u.byteLength!==X)throw new Error(`[OpenRTC] application payload crypto nonce must be ${X} bytes`);let h=new Uint8Array(1+l.byteLength);h[0]=d,h.set(l,1);let p=xchacha20poly1305(t,u).encrypt(h);if(!s)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let f=new Uint8Array(B.byteLength+1+K+u.byteLength+p.byteLength),g=0;f.set(B,g),g+=B.byteLength,f[g]=pe,g+=1;let b=o;return o+=1,new DataView(f.buffer,f.byteOffset+g,K).setBigUint64(0,BigInt(b),false),g+=K,f.set(u,g),g+=u.byteLength,f.set(p,g),f},openPayload(d,l){if(!cn(l))return n?null:l;if(ct(l)!==pe)return null;let h=B.byteLength+1,p=Number(new DataView(l.buffer,l.byteOffset+h,K).getBigUint64(0,false));if(!Number.isFinite(p))return null;let f=h+K,g=f+X,b=l.slice(f,g),v=s?an(p,b):null;if(v&&a.has(v))return null;let w=l.slice(g),I;try{I=xchacha20poly1305(t,b).decrypt(w);}catch{return null}if(I.byteLength<1||I[0]!==d)return null;if(v)for(a.add(v),c.push(v);c.length>rn;){let T=c.shift();T&&a.delete(T);}return I.slice(1)}}}function dn(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 dt(r,e={}){let t=e.typeId??tn,n=e.maxFrameBytes??nn;if(!Number.isInteger(t)||t<0||t>255)throw new Error("[OpenRTC] raw application crypto stream typeId must be an integer from 0 to 255");if(!Number.isInteger(n)||n<=0)throw new Error("[OpenRTC] raw application crypto maxFrameBytes must be a positive integer");let i=l=>r.protectPayload(t,l),s=l=>r.openPayload(t,l),o=()=>new TransformStream({transform(l,u){u.enqueue(dn(i(new Uint8Array(l))));}}),a=()=>{let l=new Uint8Array(0);return new TransformStream({transform(u,h){for(l=w([l,new Uint8Array(u)]);l.byteLength>=4;){let p=new DataView(l.buffer,l.byteOffset,l.byteLength).getUint32(0,false);if(p===0||p>n)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(l.byteLength<4+p)return;let f=l.slice(4,4+p);l=l.slice(4+p);let g=s(f);if(!g)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");h.enqueue(g);}},flush(){if(l.byteLength!==0)throw new Error("[OpenRTC] encrypted raw stream ended mid-frame")}})},c=l=>l.pipeThrough(a()),d=l=>{let u=o();return u.readable.pipeTo(l).catch(()=>{}),u.writable};return {typeId:t,protectFrame:i,openFrame:s,createOutboundTransform:o,createInboundTransform:a,wrapReadable:c,wrapWritable:d,wrapBiStream(l){return {...l,send:d(l.send),recv:c(l.recv)}}}}var ln="[OpenRTC][teardown-trace]";function un(){try{let r=globalThis;if(r.OPENRTC_TEARDOWN_TRACE===!0||r.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function lt(r,e={}){console.info(ln,{kind:r,ts:new Date().toISOString(),...e}),un()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:r,stack:new Error(`teardown: ${r}`).stack});}var Q={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,reconciliationIntervalMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:8e3,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,defaultBoundedCommandTimeoutMs:15e3,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function zi(){return Q}var pn={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}},hn={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 ut(r){return {adapter:r.adapter,signaling:{...r.signaling},transport:{...r.transport},nativeProtocols:{...r.nativeProtocols},lifecycle:{...r.lifecycle},transfers:{...r.transfers},fallback:{...r.fallback}}}function he(r=globalThis){let e=ut(pn),t=typeof r?.RTCPeerConnection=="function";return e.transport.webRtcUpgrade=t,e.transport.webRtcLan=t,e}function U(r){return r?.compiled===true&&r.enabled===true}function qi(r,e=false){let t=ut(hn),n=r?.transport;return n&&(t.transport.irohQuic=U(n.irohQuic),t.transport.irohLan=U(n.irohLan),t.transport.webRtcUpgrade=U(n.webRtc),t.transport.nativeWebRtc=U(n.webRtc),t.transport.webRtcLan=U(n.webRtcLan),t.transport.moq=U(n.moq),t.transport.ble=U(n.ble)),t.transport.wasm=false,t.fallback.wasm=e,t}function $i(r){return {environment:r.adapter==="native-ipc"||r.adapter==="tauri-ipc"?"native":r.adapter==="browser-wasm"?"web":"unknown",transports:{quic:r.transport.irohQuic,irohRelay:r.transport.irohQuic,irohLan:r.transport.irohLan,webRtc:r.transport.webRtcUpgrade||r.transport.nativeWebRtc,webRtcLan:r.transport.webRtcLan,moq:r.transport.moq,ble:r.transport.ble},lifecycle:{...r.lifecycle},storage:{localFileSystem:r.transfers.explicitFilePath,transferHistory:r.transfers.history},nativeProtocols:{...r.nativeProtocols}}}function M(r){if(!r)return null;let e=2166136261;for(let t=0;t<r.length;t+=1)e^=r.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var mn=1e4,vn=5e3,k=class{constructor(e,t,n,i,s){this.app=e;this.operationId=t;this.leaseId=n;this.route=i;this.onLeaseLost=s;this.timer=null;this.stopped=true;this.pending=null;}async start(){return !this.stopped&&this.pending?this.pending:(this.stopped=false,this.app?.options?.projectId?(this.pending=this.renew(),this.pending):(this.pending=Promise.resolve(),this.pending))}stop(){this.stopped=true,this.pending=null,this.timer&&(clearTimeout(this.timer),this.timer=null);}async renew(){try{let t=await httpsCallable(getFunctions(this.app),"renewUsageLease")({operationId:this.operationId,leaseId:this.leaseId,route:this.route});if(!t?.data||!Number.isFinite(t.data.validUntilMs)){if(globalThis.process?.env?.OPENRTC_DETERMINISTIC_TESTS==="1"){this.pending=Promise.resolve();return}throw new Error("renewUsageLease returned an invalid response")}if(this.stopped)return;let n=Math.max(vn,t.data.validUntilMs-Date.now()-mn);this.timer=setTimeout(()=>{let i=this.renew();this.pending=i,i.catch(()=>{});},n);}catch(e){throw this.stop(),this.onLeaseLost?.(e),e}}};var Tn=9e4,Dn=3e4;function Fe(r=Date.now()){return r+Tn}function P(r,e=Date.now()){return !r||r.online!==true?false:typeof r.leaseExpiresAt!="number"?true:r.leaseExpiresAt>e}function Cn(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 Me(r,e,t){return `${Cn(r,e)}/instances/${t}`}function ht(r){switch(r.kind){case "user-scoped":return `presence/${r.appTag}/users/${r.userId}/devices`;case "space":return `presence/spaces/${r.namespaceId}/devices`}}function ft(r,e,t){return `presence/${r}/rooms/${e}/members/${t}`}function En(r,e){return `presence/${r}/rooms/${e}/members`}function Z(r){let e={},t=(n,i)=>{if(typeof i!="string")return;let s=i.trim();s&&(e[n]=s);};if(t("ticket",r?.ticket),t("nodeId",r?.nodeId),t("deviceName",r?.deviceName),t("platformType",r?.platformType),t("metadata",r?.metadata),Array.isArray(r?.excludedPeers)){let n=r.excludedPeers.map(i=>typeof i=="string"?i.trim().toLowerCase():"").filter(Boolean).filter((i,s,o)=>o.indexOf(i)===s).sort();n.length>0&&(e.excludedPeers=n);}return e}function kn(r,e){if(!r||typeof r!="object")return null;let t=r,n=Z({ticket:t.ticket,nodeId:t.nodeId,deviceName:t.deviceName,platformType:t.platformType,metadata:t.metadata,excludedPeers:t.excludedPeers});return {online:P({online:t.online===true,leaseExpiresAt:typeof t.leaseExpiresAt=="number"?t.leaseExpiresAt:void 0},e),ticketVersion:typeof t.ticketVersion=="number"?t.ticketVersion:0,leaseExpiresAt:typeof t.leaseExpiresAt=="number"?t.leaseExpiresAt:void 0,...n}}function gt(r,e=Date.now()){if(!r||typeof r!="object")return null;let t=r.instances;if(!t||typeof t!="object")return null;let n=Object.entries(t).map(([i,s])=>({instanceId:i,state:kn(s,e)})).filter(i=>!!i.state).sort((i,s)=>s.instanceId.localeCompare(i.instanceId));return n.length===0?null:n.find(i=>i.state.online)?.state??n[0].state}function An(){let r=Date.now().toString().padStart(13,"0"),e=globalThis.crypto?.randomUUID?.().replace(/-/g,"")??Math.random().toString(36).slice(2);return `${r}-${e}`}function xe(r,e){return {online:true,lastSeenAt:serverTimestamp(),ticketVersion:r,leaseExpiresAt:Fe(),...Z(e)}}function Ne(r,e){return {online:false,lastSeenAt:serverTimestamp(),ticketVersion:r,leaseExpiresAt:Date.now(),...Z(e)}}function fe(r){return {...r}}function Le(r,e){return {...r,lastSeenAt:serverTimestamp(),leaseExpiresAt:e?Fe():Date.now()}}var ge=class{constructor(e,t=An()){this.desiredOnlineNodes=new Map;this.connected=null;this.connectedUnsubscribe=null;this.leaseRefreshTimer=null;this.activeSubscriptions=new Set;this.app=e,this.auth=getAuth(e),this.db=getDatabase(e);let n=t.trim().replace(/[^a-zA-Z0-9_-]/g,"-");if(!n)throw new Error("runtimeInstanceId is required");this.runtimeInstanceId=n,this.economicPresenceLease=new k(this.app,"presence.lease",this.runtimeInstanceId,"rtdb-presence",i=>{this.leaseRefreshTimer&&(clearInterval(this.leaseRefreshTimer),this.leaseRefreshTimer=null),this.connectedUnsubscribe?.(),this.connectedUnsubscribe=null;for(let s of this.activeSubscriptions)s();this.activeSubscriptions.clear(),this.desiredOnlineNodes.clear(),console.warn("[RtdbPresence] economic usage lease was lost; presence refresh stopped",{message:i instanceof Error?i.message:String(i)});});try{let i=globalThis?.__OPENRTC_RTDB_EMULATOR_HOST__,s=typeof i=="string"?i.trim():"";if(s){let[o,a]=s.split(":"),c=(o??"").trim()||"127.0.0.1",d=Number(a??9001);try{connectDatabaseEmulator(this.db,c,d);}catch{}}else {let o=import.meta?.env;if(!!o?.DEV&&String(o?.VITE_USE_EMULATORS)==="true"){let c=String(o?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",d=Number(o?.VITE_OPENRTC_RTDB_EMULATOR_PORT??9001);try{connectDatabaseEmulator(this.db,c,d);}catch{}}}}catch{}}ensureReconnectWatch(){this.connectedUnsubscribe||(this.connectedUnsubscribe=onValue(ref(this.db,".info/connected"),e=>{let t=e.val()===true,n=t&&this.connected===false;if(this.connected=t,!!n)for(let i of this.desiredOnlineNodes.keys())this.publishDesiredOnline(i).catch(s=>{console.warn("[RtdbPresence] failed to republish presence after reconnect:",{path:i,error:s});});}));}async publishDesiredOnline(e){let t=this.desiredOnlineNodes.get(e);if(!t)return;t.online=Le(t.online,true),t.offline=Le(t.offline,false);let n=ref(this.db,e);await onDisconnect(n).set(t.offline),await set(n,t.online);}ensureLeaseRefresh(){this.leaseRefreshTimer||(this.leaseRefreshTimer=setInterval(()=>{for(let e of this.desiredOnlineNodes.keys())this.publishDesiredOnline(e).catch(t=>{console.warn("[RtdbPresence] failed to refresh RTDB presence lease:",{path:e,error:t});});},Dn));}stopLeaseRefreshIfIdle(){this.desiredOnlineNodes.size>0||!this.leaseRefreshTimer||(clearInterval(this.leaseRefreshTimer),this.leaseRefreshTimer=null,this.economicPresenceLease.stop());}async registerOnlineNode(e,t,n){this.auth.currentUser&&await this.economicPresenceLease.start(),this.ensureReconnectWatch(),this.desiredOnlineNodes.set(e,{online:t,offline:n}),this.ensureLeaseRefresh(),await this.publishDesiredOnline(e);}async markNodeOffline(e,t){this.desiredOnlineNodes.delete(e),this.stopLeaseRefreshIfIdle();let n=ref(this.db,e);await onDisconnect(n).cancel(),await set(n,Le(t,false));}subscribeIncremental(e,t,n,i){let s=ref(this.db,e),o={},a=()=>n({...o}),c=p=>{let f=typeof p.key=="string"?p.key:"";if(!f)return;let g=t(f,p.val());g?o[f]=g:delete o[f],a();},d=p=>{console.warn(`[RtdbPresence] ${i} presence subscription error:`,p);},l=[onChildAdded(s,c,d),onChildChanged(s,c,d),onChildRemoved(s,p=>{let f=typeof p.key=="string"?p.key:"";f&&(delete o[f],a());},d)],u=true,h=()=>{if(u){u=false;for(let p of l)p();this.activeSubscriptions.delete(h);}};return this.activeSubscriptions.add(h),h}async registerDevice(e,t,n=0,i){let s=Me(e,t,this.runtimeInstanceId);try{await this.registerOnlineNode(s,fe(xe(n,i)),fe(Ne(n,i))),R("[RtdbPresence] registered device presence",{path:s,scopeKind:e.kind,deviceId:t,ticketVersion:n,hasTicket:typeof i?.ticket=="string"&&i.ticket.length>0,hasNodeId:typeof i?.nodeId=="string"&&i.nodeId.length>0});}catch(o){let a=o;throw console.warn("[RtdbPresence] registerDevice failed",{path:s,scopeKind:e.kind,deviceId:t,ticketVersion:n,code:typeof a?.code=="string"?a.code:null,message:typeof a?.message=="string"?a.message:String(o)}),o}}async bumpTicketVersion(e,t,n,i){let s=Me(e,t,this.runtimeInstanceId),o=ref(this.db,s),a=this.desiredOnlineNodes.get(s),c=Z(i);if(a){let d=a.online;c=Z({ticket:i?.ticket??d.ticket,nodeId:i?.nodeId??d.nodeId,deviceName:i?.deviceName??d.deviceName,platformType:i?.platformType??d.platformType,metadata:i?.metadata??d.metadata,excludedPeers:i?.excludedPeers??d.excludedPeers}),a.online=fe(xe(n,c)),a.offline=fe(Ne(n,c));}await onDisconnect(o).set(Ne(n,c)),await set(o,xe(n,c));}async markOffline(e,t,n=0){await this.markNodeOffline(Me(e,t,this.runtimeInstanceId),{online:false,lastSeenAt:serverTimestamp(),ticketVersion:n,leaseExpiresAt:Date.now()});}async registerRoomMember(e,t,n){await this.registerOnlineNode(ft(e,t,n),{online:true,lastSeenAt:serverTimestamp(),leaseExpiresAt:Fe()},{online:false,lastSeenAt:serverTimestamp(),leaseExpiresAt:Date.now()});}async markRoomMemberOffline(e,t,n){await this.markNodeOffline(ft(e,t,n),{online:false,lastSeenAt:serverTimestamp(),leaseExpiresAt:Date.now()});}onRoomPresenceChange(e,t,n){return this.subscribeIncremental(En(e,t),(i,s)=>{if(!s||typeof s!="object")return null;let o=s;return {online:P({online:o.online===true,leaseExpiresAt:typeof o.leaseExpiresAt=="number"?o.leaseExpiresAt:void 0}),leaseExpiresAt:typeof o.leaseExpiresAt=="number"?o.leaseExpiresAt:void 0}},n,"room")}onPresenceChange(e,t){return this.subscribeIncremental(ht(e),(n,i)=>gt(i),t,"device")}async readPresenceMap(e){let n=(await get(ref(this.db,ht(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=gt(o);a&&(i[s]=a);}return i}};var We=100;function It(r,e){return !r||r.kind!==e.kind?false:r.kind==="user-scoped"&&e.kind==="user-scoped"?r.appTag===e.appTag&&r.userId===e.userId:r.kind==="space"&&e.kind==="space"&&r.namespaceId===e.namespaceId}function Ln(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,n=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(n));let i=globalThis.Buffer;if(i)return JSON.parse(i.from(n,"base64").toString("utf8"))}catch{return null}return null}function j(r){let e=typeof r=="string"?r.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),n=t>=0?e.slice(0,t):e,i=t>=0?e.slice(t+1):null,s=i?Ln(i):null,o=s&&typeof s.t=="string"&&s.t.trim().length>0?s.t.trim():null,a=s&&typeof s.s=="string"&&s.s.trim().length>0?s.s.trim():null,c=s&&typeof s.m=="number"&&Number.isFinite(s.m)?s.m:null;return {present:true,irohFingerprint:M(n),tokenFingerprint:M(o),tokenSuffixFingerprint:M(i),scope:a,maxConnections:c}}var q=class q{constructor(e){this.hooks=e;this.deviceListeners=new Map;this.devicesById=new Map;this.staleDeviceOfflineWrites=new Set;this.nextListenerIdSeed={value:1};this.activeDeviceScopeKey=null;this.activeDeviceUnsubscribe=null;this.deviceWatchSetup=null;this.deviceWatchGeneration=0;this.hasDeviceRosterSnapshot=false;this.durableRosterRead=null;this.freshnessRecheckTimer=null;this.rtdbPresence=null;this.rtdbScope=null;this.rtdbPresenceMap={};this.rtdbUnsubscribe=null;this.hasRtdbPresenceSnapshot=false;this.rtdbPresenceRead=null;this.knownTicketVersions=new Map;this.autoConnectRefreshes=new Map;let t=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`discovery-${Date.now()}-${Math.random().toString(16).slice(2)}`;this.economicDiscoveryLease=new k(e.firestore.app,"discovery.roster.lease",t,"firestore-device-roster",n=>{console.warn("[BrowserDeviceDiscovery] economic usage lease was lost; roster watch stopped",{message:n instanceof Error?n.message:String(n)}),this.stopDeviceWatch({clearDevices:false});});}get options(){return this.hooks.options}async ensureEconomicUsageLease(){this.options.auth.currentUser&&await this.economicDiscoveryLease.start();}stopEconomicUsageLease(){this.economicDiscoveryLease.stop();}setRtdbPresence(e,t){let n=this.rtdbPresence===e,i=It(this.rtdbScope,t);if(n&&i)return;let s=this.deviceListeners.size>0;R("[BrowserDeviceDiscovery][rtdb] adapter or scope changed",{sameAdapter:n,sameScope:i,hasActiveListeners:s,scopeKind:t.kind}),this.rtdbUnsubscribe&&(this.rtdbUnsubscribe(),this.rtdbUnsubscribe=null),this.rtdbPresence=e,this.rtdbScope=t,this.rtdbPresenceMap={},this.hasRtdbPresenceSnapshot=false,this.rtdbPresenceRead=null,this.knownTicketVersions.clear(),s&&this.handleScopeChange().catch(o=>{console.warn("[BrowserDeviceDiscovery] failed to restart device watch after RTDB scope change:",o);});}stopRtdbPresence(){this.rtdbUnsubscribe?.(),this.rtdbUnsubscribe=null,this.rtdbPresence=null,this.rtdbScope=null,this.rtdbPresenceMap={},this.hasRtdbPresenceSnapshot=false,this.rtdbPresenceRead=null,this.knownTicketVersions.clear();}stopAuthScopedActivity(){this.stopRtdbPresence(),this.stopDeviceWatch({clearDevices:true});}async searchDevices(e){let n=(this.rtdbPresence&&this.rtdbScope?await this.readLiveRtdbDeviceSnapshot():await this.readCurrentDeviceSnapshot()).filter(i=>i.online);return e?this.filterDevices(n,e):n}async listDevices(e){let t=await this.readCurrentDeviceSnapshot();return e?this.filterDevices(t,e):t}async subscribeDevices(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return new ReadableStream({start(s){s.close();}});let t=null,n=null,i=new k(this.hooks.firestore.app,"discovery.roster.lease",typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`stream-${Date.now()}-${Math.random().toString(16).slice(2)}`,"firestore-device-stream",s=>{t?.(),t=null;try{n?.error(s);}catch{}n=null;});return this.options.auth.currentUser&&await i.start(),new ReadableStream({start:s=>{n=s,t=onSnapshot(query(e,limit(We)),o=>{let a=Date.now(),c=[];for(let d of o.docChanges()){let l=this.toDevice(d.doc,a);if(d.type==="removed"){c.push({type:"removed",deviceId:d.doc.id});continue}if(!l){c.push({type:"removed",deviceId:d.doc.id});continue}c.push({type:d.type==="added"?"added":"modified",device:l});}c.length>0&&s.enqueue(c);},o=>{console.warn("[BrowserDeviceDiscovery] subscribeDevices snapshot error:",{message:o?.message,code:o?.code});try{s.close();}catch{}});},cancel:()=>{t?.(),t=null,n=null,i.stop();}})}onDevicesChange(e,t){let n=this.nextListenerIdSeed.value++;return this.deviceListeners.set(n,{callback:e,excludeNodeId:t}),this.emitDevicesToListener(n),this.ensureDeviceWatch(),()=>{this.deviceListeners.delete(n),this.deviceListeners.size===0&&this.stopDeviceWatch({clearDevices:true});}}async handleScopeChange(){let e=this.deviceListeners.size>0;this.stopDeviceWatch({clearDevices:true}),e&&await this.ensureDeviceWatch();}async cleanupStaleDevices(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return;this.options.auth.currentUser&&await this.economicDiscoveryLease.start();let t=Date.now(),n=!!(this.rtdbPresence&&this.rtdbScope),i=await getDocs(query(e,where("online","==",false),where("expiresAt","<",t),limit(100)));if(await Promise.allSettled(i.docs.map(async c=>{let d=c.data(),l=typeof d.deviceId=="string"&&d.deviceId.trim()?d.deviceId.trim():c.id,u=n&&this.hasRtdbPresenceSnapshot&&P(this.rtdbPresenceMap[l]),h=n&&!this.hasRtdbPresenceSnapshot;d.online===false&&this.isDeviceExpired(d,t)&&!u&&!h&&await deleteDoc(c.ref);})),n)return;let s=this.rtdbPresence&&this.rtdbScope?await this.rtdbPresence.readPresenceMap(this.rtdbScope).catch(()=>this.rtdbPresenceMap):this.rtdbPresenceMap,o=await getDocs(query(e,where("online","==",true),limit(100))),a=new Map;for(let c of o.docs)a.set(c.ref.path,c);await Promise.allSettled([...a.values()].map(async c=>{let d=c.data();this.isDeviceExpired(d,t);let u=d.online===true,h=this.toMillis(d.updatedAt)??this.toMillis(d.lastSeenAt)??0,p=this.rtdbPresence&&this.rtdbScope?3e4:3e5;if(!(!u||!h||h+p>t)){if(this.rtdbPresence&&this.rtdbScope){let f=typeof d.deviceId=="string"&&d.deviceId.trim()?d.deviceId.trim():c.id;if(P(s[f]))return}await updateDoc(c.ref,{online:false,updatedAt:serverTimestamp$1(),expiresAt:Timestamp.fromMillis(t+2592e6)});}}));}async refreshDeviceForAutoConnect(e){let t=e.trim();if(!t)return null;let n=this.autoConnectRefreshes.get(t);if(n)return n;let i=this.refreshDeviceForAutoConnectOnce(t);this.autoConnectRefreshes.set(t,i);try{return await i}finally{this.autoConnectRefreshes.get(t)===i&&this.autoConnectRefreshes.delete(t);}}async refreshDeviceForAutoConnectOnce(e){if(this.rtdbPresence&&this.rtdbScope){let p=false,f=await this.readRtdbPresenceSnapshot().then(g=>g[e]).catch(g=>(p=true,console.warn("[BrowserDeviceDiscovery][auto-connect][refresh] RTDB read failed; refusing Firestore liveness fallback",{deviceId:e,error:g}),this.rtdbPresenceMap[e]));if(P(f)&&(f.ticket||f.nodeId)){let g=this.devicesById.get(e)??null,b=this.mergeRtdbPresenceIntoDevice(e,g,f)??this.deviceFromRtdbPresence(e,f);if(b){let v=this.upsertDeviceProjection(e,b);return R("[BrowserDeviceDiscovery][auto-connect][refresh]",{deviceId:e,source:"rtdb",ticketChanged:(g?.ticket??null)!==(b.ticket??null),previousTicket:j(g?.ticket),refreshedTicket:j(b.ticket),previousNodeId:g?.nodeId??null,refreshedNodeId:b.nodeId??null}),v&&this.emitDevicesToAll(),this.devicesById.get(e)??b}}if(p||!P(f))return null}let t=await this.hooks.getDevicesCollectionRef();if(!t)return this.devicesById.get(e)??null;let n=doc(t,e),i=this.devicesById.get(e)??null;this.options.auth.currentUser&&await this.economicDiscoveryLease.start();let s="server",o=null;try{o=await getDocFromServer(n);}catch(p){s="cache",console.warn("[BrowserDeviceDiscovery][auto-connect][refresh] getDocFromServer failed; falling back to getDoc",{deviceId:e,error:p}),o=await getDoc(n).catch(()=>null);}if(!o?.exists()){let p=this.devicesById.delete(e);return R("[BrowserDeviceDiscovery][auto-connect][refresh] device doc missing during refresh",{deviceId:e,source:s,previousTicket:j(i?.ticket)}),p&&this.emitDevicesToAll(),null}let a=typeof o.data=="function"?o.data():null,c=this.deviceFromSnapshot(e,a,Date.now());if(!c){let p=this.devicesById.delete(e);return R("[BrowserDeviceDiscovery][auto-connect][refresh] refreshed device doc was filtered out",{deviceId:e,source:s,previousTicket:j(i?.ticket)}),p&&this.emitDevicesToAll(),null}let d=this.rtdbPresenceMap[e],l=d?this.mergeRtdbPresenceIntoDevice(e,c,d)??c:c,u=this.upsertDeviceProjection(e,l),h=(i?.ticket??null)!==(l.ticket??null);return R("[BrowserDeviceDiscovery][auto-connect][refresh]",{deviceId:e,source:s,ticketChanged:h,previousTicket:j(i?.ticket),refreshedTicket:j(l.ticket),previousNodeId:i?.nodeId??null,refreshedNodeId:l.nodeId??null}),u&&this.emitDevicesToAll(),this.devicesById.get(e)??l}resolveKnownDeviceId(e){let t=e.trim();if(!t)return null;let n=this.devicesById.get(t);if(n?.deviceId)return n.deviceId;for(let i of this.devicesById.values())if(i.deviceId===t||i.nodeId===t||i.ticket===t)return i.deviceId;return null}stopDeviceWatch(e){this.deviceWatchGeneration+=1,this.deviceWatchSetup=null,this.clearFreshnessRecheckTimer(),this.activeDeviceUnsubscribe?.(),this.activeDeviceUnsubscribe=null,this.activeDeviceScopeKey=null,this.economicDiscoveryLease.stop(),e?.clearDevices&&(this.devicesById.clear(),this.hasDeviceRosterSnapshot=false,this.emitDevicesToAll());}clearFreshnessRecheckTimer(){this.freshnessRecheckTimer&&(clearTimeout(this.freshnessRecheckTimer),this.freshnessRecheckTimer=null);}scheduleFreshnessRecheck(e){this.deviceListeners.size===0||this.freshnessRecheckTimer||(this.freshnessRecheckTimer=setTimeout(()=>{if(this.freshnessRecheckTimer=null,e!==this.deviceWatchGeneration||this.deviceListeners.size===0)return;let t=Date.now(),n=false;for(let[i,s]of this.devicesById){let o=s;if(this.isStaleOnlineDevice(o,t)){this.shouldRetainStaleDevice(o)?this.devicesById.set(i,this.retainedStaleDevice(s,i,t)):this.devicesById.delete(i),n=true;continue}this.isDeviceExpired(o,t)&&(this.devicesById.delete(i),n=true);}n&&this.emitDevicesToAll(),this.scheduleFreshnessRecheck(e);},q.DEVICE_FRESHNESS_RECHECK_MS));}emitDevicesToAll(){for(let e of this.deviceListeners.keys())this.emitDevicesToListener(e);}emitDevicesToListener(e){let t=this.deviceListeners.get(e);if(!t)return;let n=Array.from(this.devicesById.values()),i=t.excludeNodeId?this.filterDevices(n,t.excludeNodeId):n;t.callback(i);}filterDevices(e,t){return e.filter(n=>n.ticket!==t&&n.deviceId!==t&&n.nodeId!==t)}deviceProjectionKey(e){return JSON.stringify({deviceId:e.deviceId,deviceName:e.deviceName,online:e.online,ticket:e.ticket,nodeId:e.nodeId??null,userId:e.userId??null,metadata:e.metadata??null,capabilities:e.capabilities??null,excludedPeers:[...e.excludedPeers??[]].sort()})}upsertDeviceProjection(e,t){let n=this.devicesById.get(e);return n&&this.deviceProjectionKey(n)===this.deviceProjectionKey(t)?false:(this.devicesById.set(e,t),true)}watchedDeviceSnapshot(e){return this.activeDeviceScopeKey!==e||!this.hasDeviceRosterSnapshot||!this.activeDeviceUnsubscribe&&!this.deviceWatchSetup?null:Array.from(this.devicesById.values())}async readDurableRosterDocuments(e,t){this.options.auth.currentUser&&await this.economicDiscoveryLease.start();let n=this.durableRosterRead;if(n?.scopeKey===t)return n.promise;let i=getDocs(query(e,limit(We))).then(s=>s.docs);this.durableRosterRead={scopeKey:t,promise:i};try{return await i}finally{this.durableRosterRead?.promise===i&&(this.durableRosterRead=null);}}async readRtdbPresenceSnapshot(){if(!this.rtdbPresence||!this.rtdbScope)return {};if(this.rtdbUnsubscribe&&this.hasRtdbPresenceSnapshot)return this.rtdbPresenceMap;if(this.rtdbPresenceRead)return this.rtdbPresenceRead;let e=this.rtdbPresence,t=this.rtdbScope,n=e.readPresenceMap(t).then(i=>(this.rtdbPresence===e&&It(this.rtdbScope,t)&&(this.rtdbPresenceMap=i,this.hasRtdbPresenceSnapshot=true),i));this.rtdbPresenceRead=n;try{return await n}finally{this.rtdbPresenceRead===n&&(this.rtdbPresenceRead=null);}}async readCurrentDeviceSnapshot(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return [];let t=e.path,n=this.deviceWatchSetup;n?.scopeKey===t&&await n.promise;let i=this.watchedDeviceSnapshot(t);if(i)return i;let s=this.rtdbPresenceMap;if(this.rtdbPresence&&this.rtdbScope)try{s=await this.readRtdbPresenceSnapshot();}catch(l){console.warn("[BrowserDeviceDiscovery] RTDB direct presence read failed:",l);}let o=await this.readDurableRosterDocuments(e,t),a=Date.now(),c=[],d=new Set;for(let l of o){let u=l.data();if(!this.options.matchesTag(u))continue;let h=typeof u.deviceId=="string"&&u.deviceId.trim().length>0?u.deviceId.trim():l.id;d.add(h);let p=s[h],f=P(p);if(this.isStaleFirestoreOnlyRtdbDevice(h,u,a))continue;if((this.isStaleOnlineDevice(u,a)||u.online===true&&this.isDeviceExpired(u,a))&&!f){if((!this.rtdbPresence||!this.rtdbScope)&&await this.markStaleDeviceOffline(l,u,a),this.shouldRetainStaleDevice(u)){let w=this.retainedStaleDevice(this.options.normalizeDevice({...u,deviceId:u.deviceId??l.id,online:false},l.id),l.id,a);w.deviceId&&c.push(w);}continue}if(this.isDeviceExpired(u,a)&&!f)continue;let b=this.options.normalizeDevice({...u,deviceId:u.deviceId??l.id},l.id);if(!b?.deviceId)continue;let v=p?this.mergeRtdbPresenceIntoDevice(b.deviceId,b,p):b;v&&c.push(v);}if(this.rtdbPresence&&this.rtdbScope)for(let[l,u]of Object.entries(s)){if(d.has(l)||!P(u))continue;let h=this.deviceFromRtdbPresence(l,u);h&&c.push(h);}this.devicesById.clear();for(let l of c)this.devicesById.set(l.deviceId,l);return this.hasDeviceRosterSnapshot=true,c}async readLiveRtdbDeviceSnapshot(){if(!this.rtdbPresence||!this.rtdbScope)return this.readCurrentDeviceSnapshot();let e;try{e=await this.readRtdbPresenceSnapshot();}catch(n){return console.warn("[BrowserDeviceDiscovery] RTDB live search read failed; refusing Firestore liveness fallback:",n),[]}let t=[];for(let[n,i]of Object.entries(e)){if(!P(i))continue;let s=this.devicesById.get(n),o=this.mergeRtdbPresenceIntoDevice(n,s,i)??this.deviceFromRtdbPresence(n,i);o?.deviceId&&(this.devicesById.set(o.deviceId,o),t.push(o));}return t}toDevice(e,t){return this.deviceFromSnapshot(e.id,e.data(),t,e)}deviceFromSnapshot(e,t,n,i){if(!t||!this.options.matchesTag(t))return null;let s=typeof t.deviceId=="string"&&t.deviceId.trim().length>0?t.deviceId.trim():e,o=this.rtdbPresenceMap[s],a=P(o);if(this.isStaleFirestoreOnlyRtdbDevice(s,t,n))return null;if((this.isStaleOnlineDevice(t,n)||t.online===true&&this.isDeviceExpired(t,n))&&!a){if(i&&(!this.rtdbPresence||!this.rtdbScope)&&this.markStaleDeviceOffline(i,t,n),!this.shouldRetainStaleDevice(t))return null;let l=this.retainedStaleDevice(this.options.normalizeDevice({...t,deviceId:t.deviceId??e,online:false},e),e,n);return l.deviceId?l:null}if(this.isDeviceExpired(t,n)&&!a)return null;let d=this.options.normalizeDevice({...t,deviceId:t.deviceId??e},e);return d.deviceId?o?this.mergeRtdbPresenceIntoDevice(s,d,o)??d:d:null}shouldRetainStaleDevice(e){return this.options.discoveryMode!=="user-scoped"||this.rtdbPresence&&this.rtdbScope&&e.online===true?false:(typeof e.kind=="string"?e.kind.trim().toLowerCase():"device")!=="ephemeral"}retainedStaleDevice(e,t,n){let i=this.toMillis(e.lastSeenAt)??this.toMillis(e.updatedAt)??this.toMillis(e.createdAt)??n;return {...e,deviceId:e.deviceId||t,online:false,presenceStatus:"idle",presenceUpdatedAt:i,presenceExpiresAt:this.toMillis(e.expiresAt)??n+2592e6,connectable:false}}isStaleOnlineDevice(e,t){if(e.online!==true)return false;if(this.rtdbPresence&&this.rtdbScope){let s=typeof e.deviceId=="string"&&e.deviceId.trim().length>0?e.deviceId.trim():"";if(s&&P(this.rtdbPresenceMap[s]))return false}let n=this.toMillis(e.updatedAt)??this.toMillis(e.lastSeenAt)??this.toMillis(e.createdAt);if(typeof n!="number")return false;let i=this.rtdbPresence&&this.rtdbScope?3e4:3e5;return n+i<=t}isStaleFirestoreOnlyRtdbDevice(e,t,n){if(!this.rtdbPresence||!this.rtdbScope||t.online!==true||P(this.rtdbPresenceMap[e]))return false;let i=this.toMillis(t.updatedAt)??this.toMillis(t.lastSeenAt)??this.toMillis(t.createdAt);return typeof i!="number"?false:i+3e4<=n}async markStaleDeviceOffline(e,t,n){let i=typeof t.deviceId=="string"&&t.deviceId.trim().length>0?t.deviceId:e.id,s=e.ref?.path||i;if(!(!s||this.staleDeviceOfflineWrites.has(s))){this.staleDeviceOfflineWrites.add(s);try{let o=await this.hooks.resolveDeviceRef(i);if(!o)return;this.options.auth.currentUser&&await this.economicDiscoveryLease.start(),await updateDoc(o,{online:!1,updatedAt:serverTimestamp$1(),expiresAt:Timestamp.fromMillis(n+2592e6)});}catch(o){console.warn("[BrowserDeviceDiscovery] failed to mark stale device offline:",o);}finally{this.staleDeviceOfflineWrites.delete(s);}}}isDeviceExpired(e,t){let n=this.toMillis(e.expiresAt);if(typeof n=="number")return n<=t;let i=e.online===true?3e5:2592e6,s=this.toMillis(e.updatedAt);if(typeof s=="number")return s+i<=t;let o=this.toMillis(e.lastSeenAt);return typeof o=="number"?o+i<=t:false}toMillis(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Date.parse(e);return Number.isNaN(t)?void 0:t}if(e instanceof Date)return e.getTime();if(e&&typeof e=="object"&&typeof e.toMillis=="function")return e.toMillis()}async ensureDeviceWatch(){if(this.deviceListeners.size===0)return;let e=await this.hooks.getDevicesCollectionRef(),t=e?.path??null;if(!e||!t){this.devicesById.clear(),this.emitDevicesToAll();return}if(this.activeDeviceUnsubscribe&&this.activeDeviceScopeKey===t)return;let n=this.deviceWatchSetup;if(n?.scopeKey===t)return n.promise;if(this.stopDeviceWatch({clearDevices:true}),this.rtdbPresence&&this.rtdbScope){let i=this.ensureDeviceWatchRtdb(e,t);this.deviceWatchSetup={scopeKey:t,promise:i};try{await i;}finally{this.deviceWatchSetup?.promise===i&&(this.deviceWatchSetup=null);}return}await this.startFirestoreDeviceWatch(e,t);}async startFirestoreDeviceWatch(e,t){this.options.auth.currentUser&&await this.economicDiscoveryLease.start();let n=++this.deviceWatchGeneration;this.activeDeviceScopeKey=t,this.activeDeviceUnsubscribe=onSnapshot(query(e,limit(We)),i=>{if(n!==this.deviceWatchGeneration)return;let s=Date.now();this.devicesById.clear();for(let o of i.docs){let a=this.toDevice(o,s);a&&this.devicesById.set(a.deviceId,a);}this.hasDeviceRosterSnapshot=true,this.emitDevicesToAll(),this.scheduleFreshnessRecheck(n);},i=>{if(n!==this.deviceWatchGeneration)return;let s=i?.code,o=String(i?.message??"");if((s==="permission-denied"||s==="PERMISSION_DENIED"||/permission.?denied/i.test(o)||/missing or insufficient permissions/i.test(o))&&!this.options.auth.currentUser){console.warn("[BrowserDeviceDiscovery] device watch permission-denied before auth; retrying after auth establishes"),this.stopDeviceWatch({clearDevices:false}),setTimeout(()=>{n===this.deviceWatchGeneration&&this.options.auth.currentUser&&this.ensureDeviceWatch();},500);return}console.warn("[BrowserDeviceDiscovery] device watch failed:",i);});}async ensureDeviceWatchRtdb(e,t){let n=++this.deviceWatchGeneration;this.activeDeviceScopeKey=t;let i=null,s=null;for(let d=0;d<3;d+=1)try{i=await E$1(this.readDurableRosterDocuments(e,t),q.RTDB_ROSTER_READ_TIMEOUT_MS,()=>new Error("RTDB-backed device roster read timed out")),s=null;break}catch(l){if(s=l,n!==this.deviceWatchGeneration)return;await u(x$1(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,o),this.hasDeviceRosterSnapshot=true;let a=this.rtdbPresence,c=this.rtdbScope;this.rtdbUnsubscribe&&this.rtdbUnsubscribe();try{this.rtdbUnsubscribe=a.onPresenceChange(c,d=>{if(n!==this.deviceWatchGeneration)return;R("[BrowserDeviceDiscovery][rtdb] presence update",{generation:n,devices:Object.keys(d).length,online:Object.values(d).filter(u=>P(u)).length}),this.rtdbPresenceMap=d,this.hasRtdbPresenceSnapshot=!0;let l=[];for(let[u,h]of Object.entries(d)){let p=this.knownTicketVersions.get(u)??-1,f=this.devicesById.has(u),g=!!(h.ticket||h.nodeId);h.ticketVersion!==p?(this.knownTicketVersions.set(u,h.ticketVersion),!g&&(p!==-1||!f&&P(h))&&l.push(u)):!g&&!f&&P(h)&&l.push(u);}this.applyRtdbOverlay(),this.scheduleFreshnessRecheck(n),l.length>0&&this.refetchDeviceTickets(l,n);});}catch(d){if(n!==this.deviceWatchGeneration)return;throw new Error(`[BrowserDeviceDiscovery] RTDB presence subscription setup failed; refusing Firestore-only liveness fallback: ${d instanceof Error?d.message:String(d)}`)}this.activeDeviceUnsubscribe=()=>{this.rtdbUnsubscribe?.(),this.rtdbUnsubscribe=null;},this.emitDevicesToAll(),this.scheduleFreshnessRecheck(n);}replaceDevicesFromDocuments(e,t){this.devicesById.clear();for(let n of e){let i=this.toDevice(n,t);i&&this.devicesById.set(i.deviceId,i);}}applyRtdbOverlay(){let e=false;for(let[t,n]of this.devicesById){let i=this.rtdbPresenceMap[t];if(!i)continue;let s=this.mergeRtdbPresenceIntoDevice(t,n,i);s&&(e=this.upsertDeviceProjection(t,s)||e);}for(let[t,n]of Object.entries(this.rtdbPresenceMap)){if(this.devicesById.has(t)||!P(n))continue;let i=this.deviceFromRtdbPresence(t,n);i&&(e=this.upsertDeviceProjection(t,i)||e);}e&&this.emitDevicesToAll();}mergeRtdbPresenceIntoDevice(e,t,n){if(!n)return t??null;let i=P(n),s={...t??{},appTag:this.options.appTag,tag:this.options.appTag,deviceId:e,deviceName:n.deviceName??t?.deviceName??"Device",online:i,ticket:n.ticket??t?.ticket??"",nodeId:n.nodeId??t?.nodeId,platformType:n.platformType??t?.platformType,metadata:n.metadata??t?.metadata,excludedPeers:n.excludedPeers??t?.excludedPeers,userId:t?.userId??this.options.getCurrentUserId()??void 0,updatedAt:Date.now(),lastSeenAt:Date.now()};if(!this.options.matchesTag(s))return null;let o=this.options.normalizeDevice(s,e);return o.deviceId?{...t??o,...o,online:i,ticket:n.ticket??o.ticket??t?.ticket??"",nodeId:n.nodeId??o.nodeId??t?.nodeId,deviceName:n.deviceName??o.deviceName??t?.deviceName??"Device",platformType:n.platformType??o.platformType??t?.platformType,metadata:n.metadata??o.metadata??t?.metadata,excludedPeers:n.excludedPeers??o.excludedPeers??t?.excludedPeers}:null}deviceFromRtdbPresence(e,t){if(!t.ticket&&!t.nodeId)return null;let n={appTag:this.options.appTag,tag:this.options.appTag,deviceId:e,deviceName:t.deviceName||"Device",online:P(t),ticket:t.ticket||"",nodeId:t.nodeId,platformType:t.platformType,metadata:t.metadata,excludedPeers:t.excludedPeers,userId:this.options.getCurrentUserId()??void 0,updatedAt:Date.now(),lastSeenAt:Date.now()};if(!this.options.matchesTag(n))return null;let i=this.options.normalizeDevice(n,e);return i.deviceId?i:null}async refetchDeviceTickets(e,t){await Promise.allSettled(e.map(async n=>{try{if(await this.refreshDeviceForAutoConnect(n),t!==this.deviceWatchGeneration)return}catch(i){console.warn("[BrowserDeviceDiscovery] refetch device ticket failed:",i);}}));}};q.RTDB_ROSTER_READ_TIMEOUT_MS=5e3,q.DEVICE_FRESHNESS_RECHECK_MS=3e4;var me=q;var ve=class{constructor(e){this.ctx=e;this.friendDeviceUnsubscribes=new Map;this.firestore=getFirestore(e.app);}watchFriendDevices(e,t){if(this.usesSpaceMode())return ()=>{};let n=new Map,i=new Set(e),s=false;for(let[o,a]of this.friendDeviceUnsubscribes)i.has(o)||(a(),this.friendDeviceUnsubscribes.delete(o),n.delete(o));for(let o of e){if(this.friendDeviceUnsubscribes.has(o))continue;let a=`apps/${this.ctx.appTag}/users/${o}/devices`,c=collection(this.firestore,a),d=null,l=()=>d?.();this.friendDeviceUnsubscribes.set(o,l),this.ctx.ensureUsageLease().then(()=>{s||!i.has(o)||this.friendDeviceUnsubscribes.get(o)!==l||(d=onSnapshot(query(c,limit(100)),u=>{let h=[];u.forEach(p=>{let f=p.data();if(!f||f.kind!=="device"||!this.ctx.matchesTag(f))return;let g=this.ctx.normalizeDevice(f,p.id);g.online&&h.push(g);}),n.set(o,h),t(new Map(n));},u=>{console.warn("[BrowserFriendDiscovery] friend device watch failed:",{friendUid:o,message:u?.message,code:u?.code});}),this.friendDeviceUnsubscribes.set(o,l));}).catch(u=>{this.friendDeviceUnsubscribes.get(o)===l&&this.friendDeviceUnsubscribes.delete(o),console.warn("[BrowserFriendDiscovery] friend usage lease failed:",{friendUid:o,message:u instanceof Error?u.message:String(u)});});}return ()=>{s=true;for(let[,o]of this.friendDeviceUnsubscribes)o();this.friendDeviceUnsubscribes.clear();}}async updateFriendTicket(e){let t=await this.ctx.resolveOrCreateLocalDeviceRef();t&&(await this.ctx.ensureUsageLease(),await updateDoc(t,{friendTicket:e??null}));}usesSpaceMode(){return this.ctx.usesSpaceMode?this.ctx.usesSpaceMode():(this.ctx.discoveryMode??"space")==="space"&&typeof this.ctx.apiKey=="string"&&this.ctx.apiKey.trim().length>0&&typeof this.ctx.spaceKey=="string"&&this.ctx.spaceKey.trim().length>0}};var Vn="createSignalingSession",Pt=50,Se=class{constructor(e){this.ctx=e;this.activeEconomicWatchStops=new Set;this.economicSignalingLease=new k(e.app,"signaling.exchange",typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`signaling-${Date.now()}-${Math.random().toString(16).slice(2)}`,"firestore-signaling",t=>{for(let n of this.activeEconomicWatchStops)n(t);this.activeEconomicWatchStops.clear();});}async ensureEconomicUsageLease(){getAuth(this.ctx.app).currentUser&&await this.economicSignalingLease.start();}async createSession(e){if(this.shouldUseHostedSessionCallable()){await this.createHostedSession(e);return}let t=await this.ctx.getSessionsCollectionRef();if(!t)throw new Error("createSession requires an active browser signaling namespace");await this.ensureEconomicUsageLease();let n=doc(t,e.connectionId),i=Date.now(),s=600*1e3;await setDoc(n,{appTag:e.appTag??this.ctx.appTag,connectionId:e.connectionId,initiator:e.initiator??this.ctx.getCurrentUserId(),target:e.target??this.ctx.getCurrentUserId(),initiatorDeviceId:e.initiatorDeviceId,targetDeviceId:e.targetDeviceId,connectionType:e.connectionType??null,state:e.state,offer:e.offer?JSON.stringify(e.offer):null,offerE2ee:e.offerE2ee?JSON.stringify(e.offerE2ee):null,answer:e.answer?JSON.stringify(e.answer):null,answerE2ee:e.answerE2ee?JSON.stringify(e.answerE2ee):null,iceCandidates:Array.isArray(e.iceCandidates)?JSON.stringify(e.iceCandidates):null,initiatorNodeId:e.initiatorNodeId??null,targetNodeId:e.targetNodeId??null,initiatorEndpointAddr:e.initiatorEndpointAddr??null,targetEndpointAddr:e.targetEndpointAddr??null,intent:e.intent??null,createdAt:e.createdAt??i,updatedAt:i,expiresAt:i+s},{merge:true});}async updateSession(e,t){let n=await this.ctx.getSessionsCollectionRef();if(!n)throw new Error("updateSession requires an active browser signaling namespace");let i=doc(n,this.ctx.parseScopedId(e)),s={};if(t&&typeof t=="object"){for(let[o,a]of Object.entries(t))if(a!==void 0){if(a===null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"){s[o]=a;continue}s[o]=JSON.stringify(a);}}Object.keys(s).length!==0&&(await this.ensureEconomicUsageLease(),s.updatedAt=Date.now(),await updateDoc(i,s));}async sendMessage(e,t,n,i){let s=await this.ctx.getMessagesCollectionRef();if(!s)throw new Error("sendMessage requires an active browser signaling namespace");await this.ensureEconomicUsageLease();let o=this.createDocumentId(),a=doc(s,o),c=this.ctx.getCurrentUserId()??this.ctx.getLocalDeviceId(),d=this.ctx.getCurrentUserId();if(!d&&(this.ctx.discoveryMode??"space")!=="space")throw new Error("sendMessage requires an authenticated user in app-scoped signaling mode");let l=Date.now(),u=1440*60*1e3,h={appTag:this.ctx.appTag,senderId:c,targetId:e,payload:t,state:n??null,replyPayload:i??null,timestamp:l,expiresAt:l+u};return d&&(h.senderUserId=d,h.targetUserId=d),await setDoc(a,h),a.path}async pollMessages(e){let t=await this.ctx.getMessagesCollectionRef();if(!t)return [];let n=this.ctx.getCurrentUserId();if(!n&&(this.ctx.discoveryMode??"space")!=="space")return [];let i=n?[where("targetId","==",e),where("targetUserId","==",n),limit(50)]:[where("targetId","==",e),limit(50)];await this.ensureEconomicUsageLease();let s=await getDocs(query(t,...i)),o=[];for(let a of s.docs){let c=a.data(),d=typeof c.senderId=="string"?c.senderId:"",l=typeof c.targetId=="string"?c.targetId:"",u=typeof c.payload=="string"?c.payload:"";!d||!l||!u||o.push({appTag:typeof c.appTag=="string"?c.appTag:this.ctx.appTag,senderId:d,targetId:l,senderUserId:typeof c.senderUserId=="string"?c.senderUserId:void 0,targetUserId:typeof c.targetUserId=="string"?c.targetUserId:void 0,payload:u,state:typeof c.state=="string"?c.state:void 0,replyPayload:typeof c.replyPayload=="string"?c.replyPayload:void 0,timestamp:this.ctx.toMillis(c.timestamp),expiresAt:this.ctx.toMillis(c.expiresAt),_documentId:a.id});}return o.sort((a,c)=>(a.timestamp??0)-(c.timestamp??0)),await Promise.allSettled(o.map(async a=>{await deleteDoc(doc(t,a._documentId));})),o.map(({_documentId:a,...c})=>c)}async subscribeSessions(e){let t=await this.ctx.getSessionsCollectionRef(),n=this.ctx.parseScopedId(e);if(!t||!n)return new ReadableStream({start(d){d.close();}});await this.ensureEconomicUsageLease();let i=null,s=null,o=false,a=null,c=d=>{if(!o){if(o=true,i?.(),s?.(),i=null,s=null,this.activeEconomicWatchStops.delete(c),d!==void 0)try{a?.error(d);}catch{}a=null;}};return new ReadableStream({start:d=>{a=d,this.activeEconomicWatchStops.add(c);let l={initiator:new Set,target:new Set},u=new Map,h=(p,f)=>{if(o)return;let g=[];for(let b of f.docChanges()){let v=b.doc.id;if(b.type==="removed"){l[p].delete(v),!(l.initiator.has(v)||l.target.has(v))&&u.delete(v)&&g.push({type:"removed",sessionId:v});continue}let w=this.toSession(b.doc.id,b.doc.data());if(!w)continue;l[p].add(v);let I=u.has(v);u.set(v,w),g.push({type:I?"modified":"added",session:w});}g.length>0&&d.enqueue(g);};i=onSnapshot(query(t,where("initiatorDeviceId","==",n),limit(Pt)),p=>h("initiator",p),p=>{o||d.error(p);}),s=onSnapshot(query(t,where("targetDeviceId","==",n),limit(Pt)),p=>h("target",p),p=>{o||d.error(p);});},cancel:()=>{c(),this.economicSignalingLease.stop();}})}shouldUseHostedSessionCallable(){return (this.ctx.discoveryMode??"space")!=="space"&&!!this.ctx.getCurrentUserId()}async createHostedSession(e){await httpsCallable(getFunctions(this.ctx.app),Vn)({...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 Qn(r){return typeof r=="object"&&r!==null&&"code"in r&&r.code==="not-found"}var we=class{constructor(e){this.options=e;this.rtdbPresence=null;this.namespaceRootPromise=null;this.resolvedDeviceDocIds=new Map;this.initializedLocalDevicePaths=new Set;this.firestore=getFirestore(e.app);try{let t=globalThis?.__OPENRTC_FIRESTORE_EMULATOR_HOST__,n=typeof t=="string"?t.trim():"";if(n){let[i,s]=n.split(":"),o=(i??"").trim()||"127.0.0.1",a=Number(s??8082);try{connectFirestoreEmulator(this.firestore,o,a);}catch{}}else {let i=import.meta?.env;if(!!i?.DEV&&String(i?.VITE_USE_EMULATORS)==="true"){let o=String(i?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",a=Number(i?.VITE_OPENRTC_FIRESTORE_EMULATOR_PORT??8082);try{connectFirestoreEmulator(this.firestore,o,a);}catch{}}}}catch{}this.discovery=new me({options:this.options,firestore:this.firestore,getDevicesCollectionRef:()=>this.getDevicesCollectionRef(),resolveDeviceRef:t=>this.resolveDeviceRef(t)}),this.friendDiscovery=new ve({app:e.app,appTag:e.appTag,discoveryMode:e.discoveryMode,apiKey:e.apiKey,spaceKey:e.spaceKey,matchesTag:e.matchesTag,normalizeDevice:e.normalizeDevice,resolveOrCreateLocalDeviceRef:()=>this.resolveOrCreateLocalDeviceRef(),ensureUsageLease:()=>this.discovery.ensureEconomicUsageLease(),usesSpaceMode:()=>this.usesSpaceMode()}),this.sessionSignaling=new Se({app:e.app,appTag:e.appTag,discoveryMode:e.discoveryMode,getCurrentUserId:()=>e.getCurrentUserId(),getLocalDeviceId:()=>e.getLocalDeviceId(),getSessionsCollectionRef:()=>this.getSessionsCollectionRef(),getMessagesCollectionRef:()=>this.getMessagesCollectionRef(),parseScopedId:t=>this.parseScopedId(t),toMillis:t=>this.toMillis(t)});}setRtdbPresence(e,t){this.rtdbPresence=e,this.discovery.setRtdbPresence(e,t);}getRtdbPresence(){return this.rtdbPresence}stopRtdbPresence(){this.rtdbPresence=null,this.discovery.stopRtdbPresence();}searchDevices(e){return this.discovery.searchDevices(e)}listDevices(e){return this.discovery.listDevices(e)}subscribeDevices(){return this.discovery.subscribeDevices()}onDevicesChange(e,t){return this.discovery.onDevicesChange(e,t)}async handleScopeChange(){this.clearScopeCaches(),await this.discovery.handleScopeChange();}stopAuthScopedActivity(){this.clearScopeCaches(),this.discovery.stopAuthScopedActivity(),this.discovery.stopEconomicUsageLease();}async updatePresence(e,t,n,i,s,o){let a=await this.resolveOrCreateLocalDeviceRef();if(!a)return;await this.discovery.ensureEconomicUsageLease();let c=this.options.getLocalDeviceId(),d=Date.now(),l=o?.trim()||this.options.getDefaultDeviceName(),u=this.options.getCurrentUserId(),h=Timestamp.fromMillis(n?d+Math.max(0,Math.trunc(i)):d+2592e6),p=a.path,f=this.initializedLocalDevicePaths.has(p)?null:await getDoc(a).catch(()=>null),g={appTag:this.options.appTag,tag:this.options.appTag,kind:"device",deviceId:c,deviceName:l,nodeId:e,platformType:"web",online:n,ticket:t,metadata:s??null,capabilities:{canHost:false,canSync:false,readOnly:false},lastSeenAt:serverTimestamp$1(),updatedAt:serverTimestamp$1(),expiresAt:h};u&&(g.userId=u),!this.initializedLocalDevicePaths.has(p)&&f&&!f.exists()&&(g.createdAt=serverTimestamp$1()),await setDoc(a,g,{merge:true}),this.initializedLocalDevicePaths.add(p);}async setOffline(e){let t=await this.resolveOrCreateLocalDeviceRef();if(!t)return;await this.discovery.ensureEconomicUsageLease();let n={appTag:this.options.appTag,tag:this.options.appTag,kind:"device",deviceId:this.options.getLocalDeviceId(),deviceName:this.options.getDefaultDeviceName(),nodeId:e,platformType:"web",online:false,updatedAt:serverTimestamp$1(),lastSeenAt:serverTimestamp$1(),expiresAt:Timestamp.fromMillis(Date.now()+2592e6)},i=this.options.getCurrentUserId();i&&(n.userId=i);try{await updateDoc(t,n);}catch(s){if(!Qn(s))throw s;this.initializedLocalDevicePaths.delete(t.path);}}async cleanupStaleDevices(){await this.discovery.cleanupStaleDevices();}async updateDevice(e,t){let n=await this.resolveDeviceRef(e);if(!n)throw new Error("updateDevice requires a known device record");await this.discovery.ensureEconomicUsageLease();let i={updatedAt:serverTimestamp$1()};typeof t.deviceName=="string"&&(i.deviceName=t.deviceName),t.capabilities&&(i.capabilities={canHost:t.capabilities.canHost??t.capabilities.can_host??false,canSync:t.capabilities.canSync??t.capabilities.can_sync??false,readOnly:t.capabilities.readOnly??t.capabilities.read_only??false}),typeof t.metadata=="string"&&(i.metadata=t.metadata),await updateDoc(n,i);}async deleteDevice(e){let t=await this.resolveDeviceRef(e);t&&(await this.discovery.ensureEconomicUsageLease(),await deleteDoc(t),this.clearScopeCaches());}async createSession(e){await this.sessionSignaling.createSession(e);}async updateSession(e,t){await this.sessionSignaling.updateSession(e,t);}async sendMessage(e,t,n,i){return this.sessionSignaling.sendMessage(e,t,n,i)}async pollMessages(e){return this.sessionSignaling.pollMessages(e)}async subscribeSessions(e){return this.sessionSignaling.subscribeSessions(e)}refreshDeviceForAutoConnect(e){return this.discovery.refreshDeviceForAutoConnect(e)}toMillis(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Date.parse(e);return Number.isNaN(t)?void 0:t}if(e instanceof Date)return e.getTime();if(e&&typeof e=="object"&&typeof e.toMillis=="function")return e.toMillis()}async getDevicesCollectionRef(){let e=await this.getDevicesCollectionPath();return e?collection(this.firestore,e):null}clearScopeCaches(){this.resolvedDeviceDocIds.clear(),this.initializedLocalDevicePaths.clear();}async getSessionsCollectionRef(){let e=await this.getNamespaceRoot();return e?collection(this.firestore,`${e}/sessions`):null}async getMessagesCollectionRef(){let e=await this.getNamespaceRoot();return e?collection(this.firestore,`${e}/messages`):null}async getDevicesCollectionPath(){let e=await this.getNamespaceRoot();if(!e)return null;if(this.usesSpaceMode())return `${e}/devices`;let t=this.options.getDiscoveryScopeId();return t?`${e}/users/${t}/devices`:null}async getNamespaceRoot(){if(this.usesSpaceMode()){if(!this.namespaceRootPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";this.namespaceRootPromise=a(e,t).then(n=>`spaces/${n}`);}return this.namespaceRootPromise}return `apps/${this.options.appTag}`}usesSpaceMode(){return (this.options.discoveryMode??"space")==="space"&&typeof this.options.apiKey=="string"&&this.options.apiKey.trim().length>0&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0}parseScopedId(e){let t=e.split("::");return t.length===2?t[1]:e}async resolveOrCreateLocalDeviceRef(){let e=await this.getDevicesCollectionRef();return e?doc(e,this.options.getLocalDeviceId()):null}async resolveDeviceRef(e){let t=await this.getDevicesCollectionRef();if(!t)return null;let n=e.trim();if(!n)return null;let i=this.resolvedDeviceDocIds.get(n);if(i)return doc(t,i);let s=this.discovery.resolveKnownDeviceId(n);if(s)return this.resolvedDeviceDocIds.set(n,s),doc(t,s);let o=doc(t,n);if(await this.discovery.ensureEconomicUsageLease(),(await getDoc(o)).exists())return this.resolvedDeviceDocIds.set(n,n),o;let a=await getDocs(query(t,where("deviceId","==",n),limit(1)));if(!a.empty){let d=a.docs[0].id;return this.resolvedDeviceDocIds.set(n,d),a.docs[0].ref}let c=await getDocs(query(t,where("nodeId","==",n),limit(1)));if(!c.empty){let d=c.docs[0].id;return this.resolvedDeviceDocIds.set(n,d),c.docs[0].ref}return null}watchFriendDevices(e,t){return this.friendDiscovery.watchFriendDevices(e,t)}updateFriendTicket(e){return this.friendDiscovery.updateFriendTicket(e)}};var ni=3e4,ii=3e4,xt=15e3,ri=1e3;function A(r){return typeof crypto.randomUUID=="function"?`${r}:${crypto.randomUUID()}`:`${r}:${Date.now()}:${Math.random().toString(16).slice(2)}`}async function si(r){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)),t="";for(let n of new Uint8Array(e))t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function oi(r,e){let t=new URL(r);if(t.search||t.hash||t.username||t.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(t.protocol==="https:")t.protocol="wss:";else if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol!=="wss:"&&t.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return t.pathname=`${t.pathname.replace(/\/+$/,"")}/v1/connect/${e}`,t.toString()}function Nt(r){let e=new URL(r);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}function ai(r,e){let t=r.options.projectId?.trim();if(!t)throw new Error("[OpenRTC] Firebase project ID is required for the native gateway credential.");let n=typeof globalThis>"u"?"":String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim();return n?`http://${n}/${encodeURIComponent(t)}/us-central1/${encodeURIComponent(e)}`:`https://us-central1-${t}.cloudfunctions.net/${encodeURIComponent(e)}`}async function ci(r){let e=`request failed with status ${r.status}`;try{let t=await r.json(),n=typeof t.error?.message=="string"?t.error.message.trim():"";return n?n.slice(0,256):e}catch{return e}}var Re=class r{constructor(e){this.options=e;this.runtimeInstanceId=A("runtime");this.socket=null;this.socketReady=false;this.connectPromise=null;this.desiredPresence=null;this.devices=new Map;this.deviceListeners=new Set;this.deviceStreams=new Set;this.sessionStreams=new Set;this.pendingAcks=new Map;this.pendingMessages=[];this.roomConnections=new Map;this.friendConnections=new Map;this.reconnectTimer=null;this.authRefreshTimer=null;this.reconnectAttempt=0;this.stopped=false;if(e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let t=new URL(e.gateway.endpoint),n=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]",i=t.protocol==="https:"||t.protocol==="wss:",s=e.gateway.environment==="staging"&&n&&(t.protocol==="http:"||t.protocol==="ws:");if(!i&&!s)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}async updatePresence(e,t,n,i,s,o){this.desiredPresence={localNodeId:e,ticket:t,online:n,ttlMs:i,metadata:s,deviceName:o?.trim()||this.options.getDefaultDeviceName()},await this.ensureConnected(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:A("presence"),ttlMs:i,device:this.gatewayDevice(this.desiredPresence)});}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:A("offline")}));}async updateDevice(e,t){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:A("device-patch"),patch:t});}async deleteDevice(e){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can delete only its local device.");await this.ensureConnected(),await this.sendOperation({v:1,type:"device.delete",idempotencyKey:A("device-delete")});}async cleanupStaleDevices(){}async searchDevices(e){return this.snapshot(e)}async listDevices(e){return this.snapshot(e)}onDevicesChange(e,t){let n=i=>e(t?i.filter(s=>s.nodeId!==t):i);return this.deviceListeners.add(n),n(this.snapshot()),this.desiredPresence&&this.ensureConnected(),()=>this.deviceListeners.delete(n)}async subscribeDevices(){let e=null;return new ReadableStream({start:t=>{e=t,this.deviceStreams.add(t);let n=this.snapshot().map(i=>({type:"added",device:i}));n.length>0&&t.enqueue(n);},cancel:()=>{e&&this.deviceStreams.delete(e),e=null;}})}async createSession(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:A("session-put"),sessionId:e.connectionId,session:e,expiresAtMs:e.expiresAt??Date.now()+15*6e4});}async updateSession(e,t){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:A("session-update"),sessionId:this.unscopedId(e),session:t,expiresAtMs:typeof t.expiresAt=="number"?t.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let t=null;return new ReadableStream({start:n=>{t=n,this.sessionStreams.add(n);},cancel:()=>{t&&this.sessionStreams.delete(t),t=null;}})}async sendMessage(e,t,n,i){await this.ensureConnected();let s=A("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:s,targetDeviceId:this.unscopedId(e),payload:t,state:n,replyPayload:i}),s}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,t){let n={value:false},i=new Map,s=[];t(new Map);for(let o of [...new Set(e)]){let a=o.trim();!a||a===this.options.getCurrentUserId()||this.openFriendConnection(a).then(c=>{if(n.value){c.stopAuthScopedActivity();return}s.push(c.onDevicesChange(d=>{i.set(a,d.filter(l=>l.online)),t(new Map(i));}));}).catch(()=>{n.value||(i.set(a,[]),t(new Map(i)));});}return ()=>{n.value=true;for(let o of s)o();for(let o of e)this.friendConnections.get(o.trim())?.stopAuthScopedActivity(),this.friendConnections.delete(o.trim());}}async updateFriendTicket(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:A("friend-ticket"),patch:{friendTicket:e??""}});}async handleScopeChange(){this.stopSocket(),this.devices.clear(),this.emitDevices();}stopAuthScopedActivity(){this.stopped=true,this.stopSocket();for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.reject(new Error("Coordination session stopped."));this.pendingAcks.clear(),this.devices.clear(),this.pendingMessages.splice(0,this.pendingMessages.length),this.emitDevices();for(let e of this.roomConnections.values())e.stopAuthScopedActivity();this.roomConnections.clear();for(let e of this.friendConnections.values())e.stopAuthScopedActivity();this.friendConnections.clear();}stopRtdbPresence(){}usesCoordinationGateway(){return true}async joinCoordinationRoom(e,t,n){let i=e.trim().toUpperCase(),s=this.roomConnections.get(i);s||(s=new r({...this.options,avenueOverride:{kind:"room",id:i}}),this.roomConnections.set(i,s)),await s.updatePresence(t,n,true,5*6e4,void 0,this.options.getDefaultDeviceName());}async leaveCoordinationRoom(e){let t=e.trim().toUpperCase(),n=this.roomConnections.get(t);n&&(await n.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),n.stopAuthScopedActivity(),this.roomConnections.delete(t));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(n=>this.roomMember(n))}watchCoordinationRoomMembers(e,t){return this.requireRoomConnection(e).onDevicesChange(i=>t(i.map(s=>this.roomMember(s))))}async ensureConnected(){if(this.connectPromise)return this.connectPromise;if(!(this.socket?.readyState===WebSocket.OPEN&&this.socketReady)){if(!this.desiredPresence)throw new Error("Coordination presence must be initialized before the gateway can connect.");this.stopped=false,this.connectPromise=this.connect();try{await this.connectPromise;}finally{this.connectPromise=null;}}}async connect(){let e=this.desiredPresence,t=await this.resolveAvenue(),n=await si(e.ticket),i={avenue:t,deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:n},s=this.options.getPlatformType()==="web"?(await httpsCallable(getFunctions(this.options.app),"mintCoordinationCredential")(i)).data:await this.mintNativeCredential(i);if(s.protocolVersion!==1)throw new Error("Unsupported coordination gateway protocol.");let o=Nt(this.options.gateway.endpoint);if(Nt(s.gatewayUrl)!==o)throw new Error("Coordination credential returned an unexpected gateway origin.");await new Promise((a,c)=>{let d=new WebSocket(oi(s.gatewayUrl,s.routeKey));this.socket=d;let l=false,u=setTimeout(()=>{d.close(4408,"authentication timeout"),c(new Error("Coordination gateway authentication timed out."));},xt);d.onopen=()=>{d.send(JSON.stringify({v:1,type:"auth",token:s.token,device:this.gatewayDevice(e)}));},d.onmessage=h=>{let p;try{p=JSON.parse(String(h.data));}catch{d.close(4400,"invalid gateway frame"),l||(clearTimeout(u),c(new Error("Coordination gateway returned an invalid frame.")));return}p.type==="ready"&&!l&&(l=true,this.socketReady=true,clearTimeout(u),this.reconnectAttempt=0,this.scheduleAuthRefresh(s.expiresAtMs),a()),this.handleFrame(p);},d.onerror=()=>{l||(clearTimeout(u),c(new Error("Coordination gateway connection failed.")));},d.onclose=()=>{clearTimeout(u),this.socket===d&&(this.socket=null,this.socketReady=false),this.rejectPendingAcks("Coordination gateway connection closed."),!this.stopped&&this.desiredPresence&&this.scheduleReconnect();};});}async getNativeTrustToken(e=false){return (await this.options.nativeTrustTokens.get(e)).token}async mintNativeCredential(e){let t=getAuth(this.options.app).currentUser;if(!t)throw new Error("[OpenRTC] Native coordination requires an authenticated runtime.");let n=async a=>{let[c,d]=await Promise.all([t.getIdToken(a),this.getNativeTrustToken(a)]);return fetch(ai(this.options.app,"mintNativeCoordinationCredential"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`,"X-Firebase-AppCheck":d},body:JSON.stringify({data:e})})},i=await n(false);if((i.status===401||i.status===403)&&(this.options.nativeTrustTokens.invalidate(),i=await n(true)),!i.ok)throw new Error(`[OpenRTC] Native coordination credential denied: ${await ci(i)}`);let s=await i.json(),o=s.result??s.data;if(!o)throw new Error("[OpenRTC] Native coordination credential returned an invalid callable response.");return o}handleFrame(e){if(e.type==="roster.snapshot"){this.devices.clear();for(let t of e.devices)this.devices.set(t.deviceId,this.toDevice(t));this.emitDevices();}else if(e.type==="presence.changed"){if(e.operation==="delete")this.devices.delete(e.device.deviceId),this.emitDeviceEvents([{type:"removed",deviceId:e.device.deviceId}]);else {let t=this.devices.has(e.device.deviceId),n=this.toDevice(e.device);this.devices.set(n.deviceId,n),this.emitDeviceEvents([{type:t?"modified":"added",device:n}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=ri&&this.pendingMessages.shift(),this.pendingMessages.push({senderId:e.senderDeviceId,targetId:this.options.getLocalDeviceId(),payload:e.payload,state:e.state,replyPayload:e.replyPayload,timestamp:e.createdAtMs,appTag:this.options.appTag});else if(e.type==="session.changed"){let t=e.operation==="delete"?[{type:"removed",sessionId:e.sessionId}]:[{type:"modified",session:{...e.session??{},connectionId:e.sessionId}}];for(let n of this.sessionStreams)n.enqueue(t);}else if(e.type==="ack"){let t=this.pendingAcks.get(e.idempotencyKey);t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.resolve());}else if(e.type==="error"){let t=e.idempotencyKey?this.pendingAcks.get(e.idempotencyKey):null;t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.reject(new Error(`Coordination gateway ${e.code}: ${e.message}`)));}}async sendOperation(e){let t=this.socket;if(!t||t.readyState!==WebSocket.OPEN)throw new Error("Coordination gateway is not connected.");await new Promise((n,i)=>{let s=setTimeout(()=>{this.pendingAcks.delete(e.idempotencyKey),i(new Error("Coordination gateway acknowledgement timed out."));},xt);this.pendingAcks.set(e.idempotencyKey,{resolve:n,reject:i,timer:s}),t.send(JSON.stringify(e));});}async resolveAvenue(){if(this.options.avenueOverride)return this.options.avenueOverride;if((this.options.discoveryMode??"space")==="space"){let t=await this.options.resolveSpaceNamespaceId();if(!t)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:t}}let e=this.options.getCurrentUserId();if(!e)throw new Error("Authenticated user is required for coordination.");return {kind:"user",id:e}}gatewayDevice(e){return {deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,nodeId:e.localNodeId,deviceName:e.deviceName,platformType:this.options.getPlatformType(),ticket:e.ticket,metadata:e.metadata,online:e.online}}toDevice(e){return this.options.normalizeDevice({...e,appTag:this.options.appTag,lastSeenAt:e.updatedAtMs,expiresAt:e.expiresAtMs},e.deviceId)}snapshot(e){return [...this.devices.values()].filter(t=>!e||t.nodeId!==e).sort((t,n)=>t.deviceId.localeCompare(n.deviceId))}emitDevices(){let e=this.snapshot();for(let t of this.deviceListeners)t(e);}emitDeviceEvents(e){for(let t of this.deviceStreams)t.enqueue(e);}scheduleAuthRefresh(e){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.authRefreshTimer=setTimeout(()=>{this.stopSocket(false),this.stopped||this.ensureConnected();},Math.max(1e3,e-Date.now()-ni));}scheduleReconnect(){if(this.reconnectTimer)return;let e=Math.min(ii,250*2**Math.min(7,this.reconnectAttempt++));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(()=>this.scheduleReconnect());},e);}stopSocket(e=true){e&&this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.reconnectTimer=null,this.authRefreshTimer=null;let t=this.socket;this.socket=null,this.socketReady=false,t?.close(1e3,"coordination session stopped");}rejectPendingAcks(e){for(let t of this.pendingAcks.values())clearTimeout(t.timer),t.reject(new Error(e));this.pendingAcks.clear();}unscopedId(e){let t=e.split("::");return t.length===2?t[1]:e}requireRoomConnection(e){let t=e.trim().toUpperCase(),n=this.roomConnections.get(t);if(!n)throw new Error(`Room ${t} is not joined through the coordination gateway.`);return n}async openFriendConnection(e){let t=this.friendConnections.get(e);if(t||(t=new r({...this.options,avenueOverride:{kind:"user",id:e}}),this.friendConnections.set(e,t)),!t.desiredPresence){if(!this.desiredPresence)throw new Error("Local coordination presence must start before friend discovery.");t.desiredPresence={...this.desiredPresence};}return await t.ensureConnected(),t}roomMember(e){return {nodeId:e.nodeId??e.deviceId,userId:e.userId??"",ticket:e.ticket,joinedAt:Number(e.createdAt??e.lastSeenAt??Date.now()),lastSeenAt:Number(e.lastSeenAt??Date.now()),expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0}}};var Pe=class{constructor(e){this.provider=e;this.cached=null;this.inFlight=null;this.refreshTimer=null;this.refreshRetryUsed=false;this.listeners=new Set;}async get(e=false){if(!this.provider)throw new Error("[OpenRTC] Native coordination requires coordinationGateway.nativeTrustTokenProvider; obtain tokens through a trusted backend without shipping the developer secret.");let t=Date.now();if(!e&&this.cached&&this.cached.expiresAtMs>t+3e4)return this.cached;if(this.inFlight)return this.inFlight;let n=(async()=>{let i=await this.provider(e),s=i?.token?.trim()??"",o=Number(i?.expiresAtMs),a=Date.now();if(!s||!Number.isFinite(o)||o<=a+3e4)throw new Error("[OpenRTC] Native trust token provider returned no usable short-lived token.");let c={token:s,expiresAtMs:o};return this.cached=c,this.refreshRetryUsed=false,this.notify(c),this.scheduleRefresh(c),c})();this.inFlight=n;try{return await n}finally{this.inFlight===n&&(this.inFlight=null);}}invalidate(){this.cached=null,this.clearRefreshTimer(),this.notify(null);}clear(){this.invalidate(),this.listeners.clear();}subscribe(e,t){return this.listeners.add(e),this.cached&&this.cached.expiresAtMs>Date.now()&&(t?.emitCurrent!==false&&e(this.cached),this.scheduleRefresh(this.cached)),()=>{this.listeners.delete(e),this.listeners.size===0&&this.clearRefreshTimer();}}notify(e){for(let t of this.listeners)t(e);}scheduleRefresh(e){if(this.clearRefreshTimer(),this.listeners.size===0)return;let t=Math.max(0,e.expiresAtMs-Date.now()-3e4);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>{if(this.listeners.size===0||this.refreshRetryUsed){this.invalidate();return}this.refreshRetryUsed=true,this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>this.invalidate());},15e3);});},t);}clearRefreshTimer(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}};var D=class D{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.rtdbPresenceRetryTimer=null;this.rtdbPresenceRetryAttempt=0;this.durablePresenceRetryTimer=null;this.durablePresenceRetryAttempt=0;this.localExcludedPeers=new Set;}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let n=t.trim()||this.deps.resolveWebLogicalDeviceId(),i=`${e}::${n}`;this.startedAutoConnectKey===i&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.startedAutoConnectKey=i,this.browserAutoConnectUnsubscribe=this.deps.getBrowserFirestoreSignaling().onDevicesChange(s=>this.submitDesiredPeers(s),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let t=e.map(i=>({deviceId:String(i.deviceId??"").trim(),nodeId:typeof i.nodeId=="string"&&i.nodeId.trim()||null,ticket:typeof i.ticket=="string"&&i.ticket.trim()||null,online:i.online===true,sessionId:typeof i.sessionId=="string"&&i.sessionId.trim()||null,excludedPeers:Array.isArray(i.excludedPeers)?[...new Set(i.excludedPeers.map(s=>String(s??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(i=>i.deviceId.length>0).sort((i,s)=>i.deviceId.localeCompare(s.deviceId));this.desiredPeersByDeviceId=new Map(t.map(i=>[i.deviceId,i]));let n=JSON.stringify(t);n!==this.desiredPeerSignature&&(this.desiredPeerSignature=n,this.deps.onDesiredPeersChanged?.(),this.queuedDesiredPeers=t,this.flushDesiredPeerSubmission());}resolveDesiredPeer(e,t){let n=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(n){let s=this.desiredPeersByDeviceId.get(n);if(s&&(!i||!s.nodeId||s.nodeId===i))return s}return i?Array.from(this.desiredPeersByDeviceId.values()).find(s=>s.nodeId===i)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,n=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.deps.waitForWasmClient().then(async i=>{if(this.startedAutoConnectKey===e){if(!i||typeof i.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}await Promise.all(t.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(o){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:o});}})),await i.submit_browser_desired_peers(n,JSON.stringify(t));}}).catch(i=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:n,error:i});}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}async setAutoConnectExcluded(e,t){let n=await this.deps.waitForWasmClient();n&&typeof n.set_auto_connect_excluded=="function"&&await n.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async recordAutoConnectExcludedForPresence(e,t){let n=e.trim().toLowerCase();n&&(t?this.localExcludedPeers.add(n):this.localExcludedPeers.delete(n),await this.republishRtdbPresence("excluded-peers-updated"));}startPresenceLoop(e,t,n,i,s){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let o=++this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:i,metadata:s,deviceName:n};let a=this.deps.resolveWebLogicalDeviceId(),c=async d=>{let l=await this.deps.withWebPresenceMetadata(s,a),u=()=>o===this.presenceStartGeneration&&this.presenceState!==null;if(!u())return;if(!this.deps.isRtdbPresenceDisabledForSession()&&d&&a){let p=false,f=false,g=null,b=null,v=(I,T)=>{this.scheduleDurableRosterRetry(a,o,2592e6,I,T);},w=(I,T)=>{u()&&(this.deps.isRtdbPresenceDisabledForSession()||this.scheduleRtdbPresenceRetry(d,a,o,I,T));};g=setTimeout(()=>{p||v("initial durable roster write timed out");},D.INITIAL_PRESENCE_WRITE_TIMEOUT_MS),b=setTimeout(()=>{f||w("RTDB presence register timed out");},D.RTDB_PRESENCE_REGISTER_TIMEOUT_MS),this.deps.updatePresence(t,i,false,2592e6,l,n).then(()=>{p=true,g&&(clearTimeout(g),g=null),this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(I=>{g&&(clearTimeout(g),g=null),v("initial durable roster write failed",I);}),this.deps.registerRtdbPresence(d,a,this.deps.getRtdbTicketVersion(),{ticket:i,nodeId:t,deviceName:n,platformType:"web",metadata:l,excludedPeers:this.currentExcludedPeersSnapshot()}).then(()=>{f=true,this.rtdbPresenceRetryAttempt=0,this.clearRtdbPresenceRetryTimer(),b&&(clearTimeout(b),b=null);}).catch(I=>{b&&(clearTimeout(b),b=null),w("RTDB presence register failed",I);});return}let h=Q.browserIdentity.ephemeralDeviceIdTtlMs;this.deps.updatePresence(t,i,false,h,l,n).then(()=>{this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(p=>{this.scheduleDurableRosterRetry(a,o,h,"durable roster write failed without RTDB presence",p);});};if(this.deps.resolveRtdbScope){this.deps.resolveRtdbScope(e).then(d=>c(d));return}c(this.deps.buildRtdbScope(e));}clearDurablePresenceRetryTimer(){this.durablePresenceRetryTimer&&(clearTimeout(this.durablePresenceRetryTimer),this.durablePresenceRetryTimer=null);}scheduleDurableRosterRetry(e,t,n,i,s){if(t!==this.presenceStartGeneration||this.presenceState===null||this.durablePresenceRetryTimer)return;let o=this.durablePresenceRetryAttempt+1;this.durablePresenceRetryAttempt=o;let a=Math.min(D.RTDB_PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,o-1),D.RTDB_PRESENCE_RETRY_MAX_DELAY_MS),c=(o*17%21-10)/100,d=Math.max(D.RTDB_PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${i}; retrying durable roster registration in ${d}ms without Firestore heartbeat`,s),this.durablePresenceRetryTimer=setTimeout(()=>{this.durablePresenceRetryTimer=null,!(t!==this.presenceStartGeneration||this.presenceState===null)&&(async()=>{if(this.presenceState===null)return;let l=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,e);t!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(this.presenceState.localNodeId,this.presenceState.ticket,false,n,l,this.presenceState.deviceName);})().then(()=>{this.durablePresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer();}).catch(l=>{this.scheduleDurableRosterRetry(e,t,n,"durable roster registration retry failed",l);});},d);}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(D.RTDB_PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,o-1),D.RTDB_PRESENCE_RETRY_MAX_DELAY_MS),c=(o*29%21-10)/100,d=Math.max(D.RTDB_PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${i}; retrying RTDB presence in ${d}ms without Firestore heartbeat fallback`,s),this.rtdbPresenceRetryTimer=setTimeout(()=>{this.rtdbPresenceRetryTimer=null,!(n!==this.presenceStartGeneration||this.presenceState===null||this.deps.isRtdbPresenceDisabledForSession())&&(async()=>{if(this.presenceState===null)return;let l=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,t);n!==this.presenceStartGeneration||this.presenceState===null||this.deps.isRtdbPresenceDisabledForSession()||await this.deps.registerRtdbPresence(e,t,this.deps.getRtdbTicketVersion(),{ticket:this.presenceState.ticket,nodeId:this.presenceState.localNodeId,deviceName:this.presenceState.deviceName,platformType:"web",metadata:l,excludedPeers:this.currentExcludedPeersSnapshot()});})().then(()=>{this.rtdbPresenceRetryAttempt=0;}).catch(l=>{this.scheduleRtdbPresenceRetry(e,t,n,"RTDB presence retry failed",l);});},d);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}async republishRtdbPresence(e){let t=this.presenceState;if(!t||this.deps.isRtdbPresenceDisabledForSession())return;let n=this.deps.resolveWebLogicalDeviceId();if(!n)return;let i=this.deps.resolveRtdbScope?await this.deps.resolveRtdbScope(t.userId):this.deps.buildRtdbScope(t.userId);if(!i)return;let s=await this.deps.withWebPresenceMetadata(t.metadata,n);await this.deps.registerRtdbPresence(i,n,this.deps.getRtdbTicketVersion(),{ticket:t.ticket,nodeId:t.localNodeId,deviceName:t.deviceName,platformType:"web",metadata:s,excludedPeers:this.currentExcludedPeersSnapshot()});}stopPresenceLoop(){this.presenceStartGeneration+=1,this.clearRtdbPresenceRetryTimer(),this.rtdbPresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0,this.presenceState=null;}};D.RTDB_PRESENCE_REGISTER_TIMEOUT_MS=5e3,D.INITIAL_PRESENCE_WRITE_TIMEOUT_MS=5e3,D.RTDB_PRESENCE_RETRY_MIN_DELAY_MS=2e3,D.RTDB_PRESENCE_RETRY_MAX_DELAY_MS=6e4;var Te=D;var Ce="trustedDevice",di="plutonium:e2ee:identity:v1",li="plutonium:e2ee:identity:session:v1",ui="openrtc-trust",V="identity",Lt="transport-trust:v1",pi=1,E=null,ie=null;function _(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function re(r){let e="";for(let t=0;t<r.length;t+=1)e+=String.fromCharCode(r[t]);return btoa(e)}async function Ft(r){let e=await crypto.subtle.digest("SHA-256",r),t=new Uint8Array(e);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}function hi(){return typeof sessionStorage>"u"?null:sessionStorage}function fi(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(di);}catch{}}var De=null;async function Ot(){return De||(De=(async()=>{let r=globalThis.crypto?.subtle;if(!r||typeof r.generateKey!="function")return false;try{let e=await r.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),De)}async function gi(r){let e=await crypto.subtle.exportKey("raw",r);return new Uint8Array(e)}function mi(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function Bt(){let r=mi();return r?new Promise(e=>{let t;try{t=r.open(ui,1);}catch{e(null);return}t.onupgradeneeded=()=>{let n=t.result;n.objectStoreNames.contains(V)||n.createObjectStore(V);},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);}):Promise.resolve(null)}async function vi(){let r=await Bt();if(!r)return null;try{return await new Promise(e=>{let i=r.transaction(V,"readonly").objectStore(V).get(Lt);i.onsuccess=()=>{let s=i.result;e(s&&s.privateKey&&s.publicKey?s:null);},i.onerror=()=>e(null);})}catch{return null}finally{r.close();}}async function yi(r){let e=await Bt();if(!e)return false;try{return await new Promise(t=>{let n=e.transaction(V,"readwrite");n.objectStore(V).put(r,Lt),n.oncomplete=()=>t(!0),n.onerror=()=>t(!1),n.onabort=()=>t(!1);})}catch{return false}finally{e.close();}}async function Ut(r,e){let t=await gi(r.publicKey),n=await Ft(t),i=r.privateKey;return {publicKey:t,fingerprint:n,backend:"webcrypto-nonextractable",durable:e,privateKey:i,async signChallenge(s){let o=await crypto.subtle.sign({name:"Ed25519"},i,_(s));return re(new Uint8Array(o))}}}function bi(r,e,t){let n=r.secretKey;return {publicKey:r.publicKey,secretKey:n,fingerprint:e,backend:"tweetnacl",durable:t,async signChallenge(i){return Si(i,n)}}}function Fr(r=32){let e=crypto.getRandomValues(new Uint8Array(r));return re(e)}function Si(r,e){let t=Ee.sign.detached(_(r),e);return re(t)}function Ii(r,e,t){try{return Ee.sign.detached.verify(_(r),_(e),_(t))}catch{return false}}async function Or(r,e,t){let n=globalThis.crypto?.subtle;if(n&&typeof n.importKey=="function"&&typeof n.verify=="function")try{let i=await n.importKey("raw",_(t),{name:"Ed25519"},!1,["verify"]);return await n.verify({name:"Ed25519"},i,_(e),_(r))}catch{}return Ii(r,e,t)}function Br(r){return re(r)}function Ur(r){if(!r||!r.trim())return null;try{let e=JSON.parse(r),t=e&&typeof e=="object"&&!Array.isArray(e)?e[Ce]:null;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,i=typeof n.version=="number"?n.version:null,s=typeof n.identityPublicKey=="string"?n.identityPublicKey:null,o=typeof n.identityFingerprint=="string"?n.identityFingerprint:null;return !i||!s||!o?null:{version:i,identityPublicKey:s,identityFingerprint:o}}catch{return null}}async function wi(){let r=await Ci().catch(()=>null);return r?{version:pi,identityPublicKey:re(r.publicKey),identityFingerprint:r.fingerprint}:null}async function Ke(r){let e=await wi();if(!e)return r??void 0;let t=typeof r=="string"?r.trim():"";if(!t)return JSON.stringify({[Ce]:e});try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return JSON.stringify({...n,[Ce]:e})}catch{}return JSON.stringify({metadata:r,[Ce]:e})}function Ri(){if(typeof window>"u")return null;let r=window.__TAURI_INTERNALS__;return !r||typeof r.invoke!="function"?null:r.invoke.bind(r)}async function Pi(){if(!t()||typeof window>"u"||/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||""))return null;let r=Ri();if(!r)return null;try{let e=await r("openrtc_get_transport_trust_identity");return {publicKey:_(e.publicKeyBase64),fingerprint:e.fingerprint,backend:"native-keychain",durable:!0,async signChallenge(n){return r("openrtc_sign_transport_trust_challenge",{challenge:n})}}}catch{return null}}function Ti(){let r=hi();r&&r.removeItem(li);}async function Di(){if(fi(),Ti(),E)return E;let r=await Pi();if(r)return E=r,E;if(await Ot()){let e=await vi();if(e)return E=await Ut(e,true),E}return null}async function Ci(r={}){let e=await Di();if(e)return e;if(ie)return ie;let t=Ei(r);ie=t;try{return await t}finally{ie===t&&(ie=null);}}async function Ei(r){if(E)return E;let e=r.ephemeral===true;if(await Ot())try{let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),n=!1;return e||(n=await yi(t)),E=await Ut(t,n),E}catch{}if(!e)return console.warn("[OpenRTC][TRUST] Managed transport trust requires WebCrypto Ed25519 or native keychain; refusing extractable fallback storage"),null;try{let t=Ee.sign.keyPair(),n=await Ft(v(t.publicKey));return E=bi(t,n,!1),E}catch{return null}}function Y(r){return !r||typeof r!="object"?{}:r instanceof Map?Object.fromEntries(r):r}function ze(r){let e=Y(r),t=Y(e.device);if(!Object.keys(t).length)return e;let n={...t,...e};return delete n.device,n}function m(r,...e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return n}}function H(r,...e){for(let t of e){let n=r[t];if(typeof n=="boolean")return n}}function y(r,...e){for(let t of e){let n=r[t];if(typeof n=="number"&&Number.isFinite(n))return n}}function x(r){if(typeof r=="number"&&Number.isFinite(r))return r;if(r instanceof Date){let e=r.getTime();return Number.isFinite(e)?e:void 0}if(typeof r=="string"){let e=Date.parse(r);return Number.isFinite(e)?e:void 0}if(r&&typeof r=="object"){let e=r;if(typeof e.toMillis=="function"){let n=e.toMillis();return Number.isFinite(n)?n:void 0}let t=typeof e.seconds=="number"?e.seconds:typeof e._seconds=="number"?e._seconds:void 0;if(t!==void 0&&Number.isFinite(t)){let n=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return t*1e3+Math.floor((Number.isFinite(n)?n:0)/1e6)}}}function je(...r){let e=r.map(x).filter(t=>typeof t=="number"&&Number.isFinite(t));return e.length?Math.max(...e):void 0}function qe(r){if(typeof r!="string")return;let e=r.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Wt(r){let e=qe("presenceStatus"in r?r.presenceStatus:void 0),t="presenceUpdatedAt"in r?x(r.presenceUpdatedAt):void 0,n="presenceExpiresAt"in r?x(r.presenceExpiresAt):void 0,i=t??je(r.lastSeenAt,r.updatedAt,r.createdAt),s=n??x(r.expiresAt),o=e;o||(r.online?i!==void 0&&i+3e5<=Date.now()?o="idle":o="online":o="offline");let a=typeof r.ticket=="string"?r.ticket.trim():"",c="connectable"in r&&typeof r.connectable=="boolean"?r.connectable:o==="online"&&a.length>0;return {presenceStatus:o,presenceUpdatedAt:i,presenceExpiresAt:s,connectable:c}}function Gt(r){return b$1(r)}function J(r,...e){return Gt(m(r,...e))}function oe(r){if(!Array.isArray(r))return;let e=Array.from(new Set(r.map(Gt).filter(t=>!!t)));return e.length?e:void 0}function Ht(r){let e=Y(r),t={webrtc:y(e,"webrtc"),webrtcLan:y(e,"webrtcLan","webrtc_lan"),webrtcTurn:y(e,"webrtcTurn","webrtc_turn"),iroh:y(e,"iroh"),irohLan:y(e,"irohLan","iroh_lan"),irohRelay:y(e,"irohRelay","iroh_relay"),ble:y(e,"ble"),moq:y(e,"moq")};return Object.values(t).some(n=>n!==void 0)?t:void 0}function Kt(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 zt(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=ze(r),n=m(t,"deviceId","device_id")||e||"",i=m(t,"nodeId","node_id")||"",s=m(t,"ticket")||"";return {deviceId:n,deviceName:m(t,"deviceName","device_name")||"Unknown Device",online:!!t.online,ticket:s,friendTicket:m(t,"friendTicket","friend_ticket"),presenceStatus:qe(m(t,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:y(t,"presenceUpdatedAt","presence_updated_at")??je(t.presenceUpdatedAt,t.presence_updated_at,t.lastSeenAt,t.last_seen_at,t.updatedAt,t.updated_at,t.createdAt,t.created_at),presenceExpiresAt:y(t,"presenceExpiresAt","presence_expires_at")??x(t.presenceExpiresAt??t.presence_expires_at)??x(t.expiresAt??t.expires_at),connectable:H(t,"connectable"),kind:m(t,"kind"),nodeId:i||void 0,platformType:m(t,"platformType","platform_type"),capabilities:t.capabilities||void 0,sessionId:m(t,"sessionId","session_id"),userId:m(t,"userId","user_id"),lastSeenAt:t.lastSeenAt??t.last_seen_at,expiresAt:t.expiresAt??t.expires_at,createdAt:t.createdAt??t.created_at,updatedAt:t.updatedAt??t.updated_at,metadata:m(t,"metadata"),excludedPeers:Ve(t.excludedPeers??t.excluded_peers),availableTransports:oe(t.availableTransports??t.available_transports),transports:oe(t.transports)}}function Ve(r){return Array.isArray(r)?r.filter(e=>typeof e=="string"):[]}function ki(r){let e=Wt(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?Ve(r.scopes):[],connectionId:"connectionId"in r&&typeof r.connectionId=="string"?r.connectionId:void 0,deviceIdHint:"deviceIdHint"in r&&typeof r.deviceIdHint=="string"?r.deviceIdHint:void 0,activeTransportStableId:"activeTransportStableId"in r&&typeof r.activeTransportStableId=="number"?r.activeTransportStableId:"activeTransportStableId"in r?r.activeTransportStableId??null:void 0,transportGeneration:"transportGeneration"in r&&typeof r.transportGeneration=="number"?r.transportGeneration:void 0,routeGeneration:"routeGeneration"in r&&typeof r.routeGeneration=="number"?r.routeGeneration:void 0,activeTransport:"activeTransport"in r?r.activeTransport:void 0,parallelTransport:"parallelTransport"in r?r.parallelTransport:void 0,availableTransports:"availableTransports"in r?oe(r.availableTransports):"transports"in r?oe(r.transports):void 0,latencyMs:"latencyMs"in r&&typeof r.latencyMs=="number"?r.latencyMs:void 0,latencyByTransport:"latencyByTransport"in r?Ht(r.latencyByTransport):void 0}}function se(r,e){return e===void 0?true:e===null?r==null:r==null||r===e}function jt(r,e){let t=se(r.connectionId,e.connectionId)&&se(r.nodeId,e.nodeId)&&se(r.activeTransportStableId,e.activeTransportStableId)&&se(r.transportGeneration,e.transportGeneration)&&se(r.routeGeneration,e.routeGeneration),n=(i,s)=>i!==void 0?i:t?s:void 0;return {inheritsSnapshot:t,fields:{connectionId:n(e.connectionId??void 0,r.connectionId),activeTransportStableId:n(e.activeTransportStableId,r.activeTransportStableId),transportGeneration:n(e.transportGeneration,r.transportGeneration),routeGeneration:n(e.routeGeneration,r.routeGeneration),activeTransport:n(e.activeTransport,r.activeTransport),parallelTransport:n(e.parallelTransport,r.parallelTransport),latencyMs:t?r.latencyMs:void 0,latencyByTransport:t?r.latencyByTransport:void 0}}}var Ai={connectionId:void 0,activeTransportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function _i(r,e,t){let n=jt(r,{connectionId:e.activeConnectionId,nodeId:e.nodeId,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),i=t?t({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):r.promotionEligible??true;if(!i)return {...r,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:i,scopes:e.scopes?.length?[...e.scopes]:r.scopes,nodeId:e.nodeId===void 0?r.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...n.fields,readinessReason:e.readinessReason??r.readinessReason};let s=e.status??r.connectionStatus,o=typeof s=="string"?s.trim().toLowerCase():"",a=o==="failed"||o==="closed"||o==="disconnected",d=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,l=r.settledReady===true||r.readinessState==="routable";if(n.inheritsSnapshot&&l&&!a&&!d)return {...r,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:i,scopes:e.scopes?.length?[...e.scopes]:r.scopes,nodeId:e.nodeId===void 0?r.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...n.fields,readinessReason:e.readinessReason??r.readinessReason};let u=a?false:d,h=d&&!a&&(o==="connecting"||o==="connected")?"connected":s,p=d?"routable":e.readinessState??(n.inheritsSnapshot?r.readinessState:void 0),f=u?e.readinessReason??"peer-session-settled":e.readinessReason??(n.inheritsSnapshot?r.readinessReason:void 0);return {...r,connectionStatus:h,settledReady:u,readinessState:p,readinessReason:f,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:i,scopes:e.scopes?.length?[...e.scopes]:r.scopes,nodeId:e.nodeId===void 0?r.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...n.fields}}function Mi(r,e){let t=jt(r,{connectionId:e.connectionId,nodeId:e.nodeId,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport});if(e.promotionEligible===false)return {...r,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:false,nodeId:e.nodeId??r.nodeId,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:r.scopes};let n=e.status??r.connectionStatus,i=typeof n=="string"?n.trim().toLowerCase():"",s=i==="failed"||i==="closed"||i==="disconnected",o=r.settledReady===true||r.readinessState==="routable",a=e.routable===false;if(t.inheritsSnapshot&&o&&s&&!a)return {...r,peerHealth:r.peerHealth??e.health,peerId:r.peerId??e.peerId,promotionEligible:e.promotionEligible??r.promotionEligible??true,connectionId:r.connectionId??e.connectionId,deviceIdHint:r.deviceIdHint??e.deviceIdHint,scopes:r.scopes?.length?r.scopes:e.scopes??r.scopes};if(o&&s)return {...r,connectionStatus:n,settledReady:false,readinessState:void 0,readinessReason:e.error??r.readinessReason,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:e.promotionEligible??r.promotionEligible??true,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...Ai,scopes:e.scopes?.length?[...e.scopes]:r.scopes};let c=e.routable===true||e.protocolState==="routable";if(t.inheritsSnapshot&&o&&!s&&!c)return {...r,peerHealth:r.peerHealth??e.health,peerId:r.peerId??e.peerId,promotionEligible:e.promotionEligible??r.promotionEligible??true,connectionId:r.connectionId??e.connectionId,deviceIdHint:r.deviceIdHint??e.deviceIdHint,activeTransportStableId:r.activeTransportStableId??e.activeTransportStableId,transportGeneration:r.transportGeneration??e.transportGeneration,routeGeneration:r.routeGeneration??e.routeGeneration,activeTransport:r.activeTransport??e.activeTransport,parallelTransport:r.parallelTransport===void 0?e.parallelTransport:r.parallelTransport,scopes:r.scopes?.length?r.scopes:e.scopes??r.scopes};let d=e.transportState==="connected"&&e.health==="healthy",l=s?false:c,u=!s&&(c||d)&&(i==="connecting"||i==="connected"||e.transportState==="connected")?"connected":n,h=l?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(t.inheritsSnapshot?r.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),p=l?(t.inheritsSnapshot?r.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(t.inheritsSnapshot?r.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...r,connectionStatus:u,settledReady:l,readinessState:h,readinessReason:p,peerHealth:e.health??r.peerHealth,peerId:e.peerId??r.peerId,promotionEligible:e.promotionEligible??r.promotionEligible??true,nodeId:e.nodeId??r.nodeId,deviceIdHint:e.deviceIdHint??r.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:r.scopes}}function xi(r){let{device:e,session:t=null,peer:n=null,isPromotionEligible:i}=r,s=ki(e);return t&&(s=_i(s,t,i)),n&&(s=Mi(s,n)),s}function qt(r){let e=ze(r),t=$e(e),n=qe(m(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),i=Wt({...t,...n?{presenceStatus:n}:{},presenceUpdatedAt:y(e,"presenceUpdatedAt","presence_updated_at")??je(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:y(e,"presenceExpiresAt","presence_expires_at")??x(e.presenceExpiresAt??e.presence_expires_at)??x(e.expiresAt??e.expires_at),connectable:H(e,"connectable")}),s={...t,...i,connectionStatus:m(e,"connectionStatus","connection_status")||"disconnected",settledReady:H(e,"settledReady","settled_ready")??false,readinessState:m(e,"readinessState","readiness_state")??void 0,readinessReason:m(e,"readinessReason","readiness_reason")??void 0,peerHealth:m(e,"peerHealth","peer_health")||"unknown",peerId:m(e,"peerId","peer_id"),scopes:Ve(e.scopes),connectionId:m(e,"connectionId","connection_id"),deviceIdHint:m(e,"deviceIdHint","device_id_hint"),activeTransportStableId:y(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:y(e,"transportGeneration","transport_generation")??void 0,routeGeneration:y(e,"routeGeneration","route_generation")??void 0,activeTransport:J(e,"activeTransport","active_transport"),parallelTransport:J(e,"parallelTransport","parallel_transport")??null,availableTransports:oe(e.availableTransports??e.available_transports),latencyMs:y(e,"latencyMs","latency_ms"),latencyByTransport:Ht(e.latencyByTransport??e.latency_by_transport)};return xi({device:s})}function $t(r){let e=ze(r);return {peerId:m(e,"peerId","peer_id")||"",deviceId:m(e,"deviceId","device_id"),deviceIdHint:m(e,"deviceIdHint","device_id_hint"),nodeId:m(e,"nodeId","node_id"),activeConnectionId:m(e,"activeConnectionId","active_connection_id"),candidateConnectionIds:Array.isArray(e.candidateConnectionIds)?e.candidateConnectionIds.filter(t=>typeof t=="string"):Array.isArray(e.candidate_connection_ids)?e.candidate_connection_ids.filter(t=>typeof t=="string"):[],status:m(e,"status")||"disconnected",health:m(e,"health")||"unknown",settledReady:H(e,"settledReady","settled_ready")??false,readinessState:m(e,"readinessState","readiness_state")??void 0,activeTransportStableId:y(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:y(e,"transportGeneration","transport_generation")??void 0,routeGeneration:y(e,"routeGeneration","route_generation")??void 0,activeTransport:J(e,"activeTransport","active_transport"),parallelTransport:J(e,"parallelTransport","parallel_transport")??null,replacementPending:H(e,"replacementPending","replacement_pending")??void 0,lastLifecycleTransitionAtMs:y(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:m(e,"readinessReason","readiness_reason")??void 0,transitionCount:y(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:y(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:y(e,"replacementCount","replacement_count")??void 0,retireCount:y(e,"retireCount","retire_count")??void 0,lastDisconnectReason:m(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:m(e,"lastReconnectReason","last_reconnect_reason")??void 0,scopes:Array.isArray(e.scopes)?e.scopes.filter(t=>typeof t=="string"):[],lastSeenAtMs:typeof e.lastSeenAtMs=="number"?e.lastSeenAtMs:typeof e.last_seen_at_ms=="number"?e.last_seen_at_ms:0,error:m(e,"error")}}function Hr(r){let e=Y(r);return {connectionId:typeof e.connectionId=="string"?e.connectionId:"",nodeId:typeof e.nodeId=="string"?e.nodeId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,endpointId:typeof e.endpointId=="string"?e.endpointId:null,transportGeneration:typeof e.transportGeneration=="number"?e.transportGeneration:0,routeGeneration:typeof e.routeGeneration=="number"?e.routeGeneration:void 0,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof e.lastRouteChangeAtMs=="number"?e.lastRouteChangeAtMs:void 0,state:typeof e.state=="string"?e.state:"pending",statusReason:typeof e.statusReason=="string"?e.statusReason:null,transitionCount:typeof e.transitionCount=="number"?e.transitionCount:void 0,connectingTransitionCount:typeof e.connectingTransitionCount=="number"?e.connectingTransitionCount:void 0,replacementCount:typeof e.replacementCount=="number"?e.replacementCount:void 0,retireCount:typeof e.retireCount=="number"?e.retireCount:void 0,lastDisconnectReason:typeof e.lastDisconnectReason=="string"?e.lastDisconnectReason:void 0,lastReconnectReason:typeof e.lastReconnectReason=="string"?e.lastReconnectReason:void 0,createdAtMs:typeof e.createdAtMs=="number"?e.createdAtMs:0,updatedAtMs:typeof e.updatedAtMs=="number"?e.updatedAtMs:0}}function Kr(r){let e=Y(r);return {peerId:typeof e.peerId=="string"?e.peerId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,nodeId:typeof e.nodeId=="string"?e.nodeId:null}}function Ni(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=Ni(r.status),n=t==="connected"?"connected":t==="connecting"?"connecting":"closed",i=t==="connected"?r.settledReady?"routable":"transport-only":t==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.nodeId??null,state:t,transportState:n,protocolState:i,routable:!!r.settledReady,readinessState:r.readinessState,readinessReason:r.readinessReason,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,activeTransportStableId:r.activeTransportStableId,activeTransport:r.activeTransport,parallelTransport:r.parallelTransport??null,replacementInProgress:r.replacementPending,lastLifecycleTransitionAtMs:r.lastLifecycleTransitionAtMs,transitionCount:r.transitionCount,connectingTransitionCount:r.connectingTransitionCount,replacementCount:r.replacementCount,retireCount:r.retireCount,lastDisconnectReason:r.lastDisconnectReason??void 0,lastReconnectReason:r.lastReconnectReason??void 0,updatedAt:r.lastSeenAtMs,error:r.error??void 0}}function Yt(r){let e=Y(r),t=m(e,"connectionId","connection_id");if(!t)return null;let n=m(e,"state")||"connecting",i=y(e,"createdAt","created_at")??y(e,"updatedAt","updated_at")??Date.now(),s=y(e,"updatedAt","updated_at")??i;return {connectionId:t,deviceId:m(e,"deviceId","device_id"),deviceIdHint:m(e,"deviceIdHint","device_id_hint"),remoteNodeId:m(e,"remoteNodeId","remote_node_id"),state:n,transportState:m(e,"transportState","transport_state")??(n==="connected"?"connected":n==="connecting"?"connecting":"closed"),protocolState:m(e,"protocolState","protocol_state")??(n==="connected"?"routable":n==="connecting"?"connecting":"closed"),routable:H(e,"routable")??false,readinessState:m(e,"readinessState","readiness_state")??void 0,readinessReason:m(e,"readinessReason","readiness_reason")??void 0,transportGeneration:y(e,"transportGeneration","transport_generation")??void 0,routeGeneration:y(e,"routeGeneration","route_generation")??void 0,activeTransportStableId:y(e,"activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:J(e,"activeTransport","active_transport"),parallelTransport:J(e,"parallelTransport","parallel_transport")??null,replacementInProgress:H(e,"replacementInProgress","replacement_in_progress")??void 0,lastLifecycleTransitionAtMs:y(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:y(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:y(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:y(e,"replacementCount","replacement_count")??void 0,retireCount:y(e,"retireCount","retire_count")??void 0,lastDisconnectReason:m(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:m(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:m(e,"error")??void 0,createdAt:i,updatedAt:s}}function Jt(r,e){return r?r.connectionId===e.connectionId&&(r.deviceId??null)===(e.deviceId??null)&&(r.deviceIdHint??null)===(e.deviceIdHint??null)&&(r.remoteNodeId??null)===(e.remoteNodeId??null)&&r.state===e.state&&(r.transportState??null)===(e.transportState??null)&&(r.protocolState??null)===(e.protocolState??null)&&!!r.routable==!!e.routable&&(r.activeTransport??null)===(e.activeTransport??null)&&(r.parallelTransport??null)===(e.parallelTransport??null)&&(r.activeTransportStableId??null)===(e.activeTransportStableId??null)&&(r.transportGeneration??null)===(e.transportGeneration??null)&&(r.routeGeneration??null)===(e.routeGeneration??null)&&!!r.replacementInProgress==!!e.replacementInProgress&&(r.transitionCount??null)===(e.transitionCount??null)&&(r.connectingTransitionCount??null)===(e.connectingTransitionCount??null)&&(r.replacementCount??null)===(e.replacementCount??null)&&(r.retireCount??null)===(e.retireCount??null)&&(r.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(r.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(r.error??null)===(e.error??null):false}function Li(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 Fi(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?Li(i):null,o=s&&typeof s.t=="string"&&s.t.trim().length>0?s.t.trim():null,a=s&&typeof s.s=="string"&&s.s.trim().length>0?s.s.trim():null,c=s&&typeof s.m=="number"&&Number.isFinite(s.m)?s.m:null;return {present:true,irohFingerprint:M(n),tokenFingerprint:M(o),tokenSuffixFingerprint:M(i),scope:a,maxConnections:c}}function ae(r,e,t={}){let n=typeof r.finishSend=="function"?r.finishSend.bind(r):typeof r.finish_send=="function"?r.finish_send.bind(r):null;if(!n){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let i=e.getWriter();return new WritableStream({write:s=>i.write(s),async close(){await i.close(),await n();},abort:s=>i.abort(s)})}var S=class S{constructor(e){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this._rtdbPresence=null;this.rtdbPresenceScope=null;this.rtdbTicketVersion=0;this.rtdbPresenceDisabledForSession=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationUnsubscribe=null;this.applicationRouteEscalationSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;try{let n=typeof import.meta<"u"?import.meta.env:null;if(!!n&&String(n.VITE_USE_EMULATORS)==="true"&&(n.DEV||String(n.VITE_E2E)==="true")){let s=String(n.VITE_OPENRTC_FIRESTORE_EMULATOR_HOST||"").trim()||"127.0.0.1:8082";globalThis.__OPENRTC_FIRESTORE_EMULATOR_HOST__=s;}}catch{}if(this.appTag=b(e),this.options={...e,appTag:this.appTag,authMode:c(e),projectId:d(e)},this.nativeTrustTokens=this.options.coordinationGateway?new Pe(this.options.coordinationGateway.nativeTrustTokenProvider):null,this.presenceManager=new Te({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(n,i)=>this.waitForWasmClient(n,i),warnMissingWasmOnce:n=>this.warnMissingWasmOnce(n),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(n,i)=>this.withWebPresenceMetadata(n,i),updatePresence:(n,i,s,o,a,c)=>this.updatePresence(n,i,s,o,a,c),buildRtdbScope:n=>this.buildRtdbScope(n),resolveRtdbScope:n=>this.resolveRtdbScope(n),registerRtdbPresence:(n,i,s,o)=>this.registerRtdbPresence(n,i,s,o),isRtdbPresenceDisabledForSession:()=>this.rtdbPresenceDisabledForSession,getRtdbTicketVersion:()=>this.rtdbTicketVersion,getBrowserFirestoreSignaling:()=>this.getBrowserFirestoreSignaling(),rememberRouteRepairTokenFromTicket:n=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(n)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations()}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()){this.app=null,this.auth=null;return}let t=G();this.app=t.getApp(),this.auth=t.getAuth(),t.onAuthStateChanged(n=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(o=>o(this.toRuntimeIdentity(n)));return}let i=n?.uid??null,s=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=i,s&&s!==i&&this.stopAuthScopedActivity({userId:s}),this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(o=>o(this.toRuntimeIdentity(n)));});}get rtdbPresence(){return this._rtdbPresence}get tag(){return this.appTag}getRuntimeCapabilities(){return he()}getDeviceIdentityStorageKey(){let e$1=e(this.options);return `${S.WEB_DEVICE_ID_STORAGE_PREFIX}_${e$1}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let n=this.getDeviceIdentityStorageKey(),i=Date.now(),s=null;try{let l=localStorage.getItem(n);s=l?JSON.parse(l):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 l=o||this.createRandomDeviceId();return localStorage.setItem(n,JSON.stringify({deviceId:l})),l}if(o&&typeof a=="number"&&a>i){let l=i+S.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:o,expiresAt:l})),o}let c=this.createRandomDeviceId(),d=i+S.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:c,expiresAt:d})),c}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}getBrowserFirestoreSignaling(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Browser signaling is disabled when signalingMode="ticket-only".');return this.browserCoordinationSignaling||(this.browserCoordinationSignaling=this.options.coordinationGateway?new Re({app:this.app,gateway:this.options.coordinationGateway,appTag:this.appTag,discoveryMode:this.options.discoveryMode,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(e,t)=>this.normalizeDevice(e,t),nativeTrustTokens:this.nativeTrustTokens}):new we({app:this.app,auth:this.auth,appTag:this.appTag,apiKey:this.options.apiKey,spaceKey:this.options.spaceKey,discoveryMode:this.options.discoveryMode,getCurrentUserId:()=>this.getCurrentUserId(),getDiscoveryScopeId:()=>this.getDiscoveryScopeId(),getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),matchesTag:e=>this.matchesTag(e),normalizeDevice:(e,t)=>this.normalizeDevice(e,t)})),this.browserCoordinationSignaling}usesCoordinationGateway(){return !!this.options.coordinationGateway}async getCoordinationNativeTrustToken(e=false){if(!this.nativeTrustTokens)throw new Error("[OpenRTC] Native trust tokens require a coordination gateway.");return this.nativeTrustTokens.get(e)}invalidateCoordinationNativeTrustToken(){this.nativeTrustTokens?.invalidate();}subscribeCoordinationNativeTrustToken(e,t){return this.nativeTrustTokens?this.nativeTrustTokens.subscribe(e,t):()=>{}}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}async joinCoordinationRoom(e,t,n){let i=this.getBrowserFirestoreSignaling();if(!i.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await i.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){await this.getBrowserFirestoreSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getBrowserFirestoreSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let n=this.getBrowserFirestoreSignaling();if(!n.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return n.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let n;if(!e||!e.trim())n=JSON.stringify({deviceId:t});else {try{let i=JSON.parse(e);if(i&&typeof i=="object"&&!Array.isArray(i))return n=JSON.stringify({...i,deviceId:t}),await Ke(n)??n}catch{}n=JSON.stringify({deviceId:t,metadata:e});}return await Ke(n)??n}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive;if(this.authContext=e,!this.isTicketOnlyMode()&&e?.customToken?.trim())try{await this.ensureBrowserFirestoreAuth(e.userId,e.customToken.trim());}catch(n){console.warn("[WasmBridge] ensureBrowserFirestoreAuth failed (non-fatal):",n);}else if(!this.isTicketOnlyMode()&&!e&&t)try{await this.auth?.signOut();}catch(n){console.warn("[WasmBridge] Failed to clear injected browser auth session:",n);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(n=>n(this.currentUser));}async ensureBrowserFirestoreAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await G().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){if(!this.wasmClient||typeof this.wasmClient.set_auth_token!="function"||!this.authContext&&this.isSpaceMode())return;let e=this.authContext?.userId??null,t=this.authContext?.token??null;this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===e&&this.lastWasmAuthToken===t||(this.lastWasmAuthUserId=e,this.lastWasmAuthToken=t,this.hasSyncedAuthToWasmClient=true,this.wasmClient.set_auth_token(t));}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return Kt(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 zt(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}disableRtdbPresenceForSession(e,t){this.rtdbPresenceDisabledForSession||console.warn(`[WasmBridge] Disabling RTDB presence for this browser session (${e})`,t),this.rtdbPresenceDisabledForSession=true,this.rtdbPresenceScope=null,this.browserCoordinationSignaling?.stopRtdbPresence();}async registerRtdbPresence(e,t,n,i){if(this.isTicketOnlyMode()||this.options.coordinationGateway)return;if(!this._rtdbPresence)try{this._rtdbPresence=new ge(this.app);}catch(c){throw this.disableRtdbPresenceForSession("RTDB service unavailable",c),c}this.rtdbPresenceScope=e;let s=n??this.rtdbTicketVersion,o=this.getBrowserFirestoreSignaling(),a=o.setRtdbPresence;if(a){a.call(o,this._rtdbPresence,e);try{await this._rtdbPresence.registerDevice(e,t,s,i);}catch(c){throw c}}}buildRtdbPresenceFields(e,t,n,i){return {ticket:t,nodeId:e,deviceName:i?.trim()||this.getDefaultBrowserDeviceName(),platformType:"web",metadata:n}}async refreshRtdbPresenceTicket(e,t,n,i){if(this.isTicketOnlyMode()||this.rtdbPresenceDisabledForSession||this.options.coordinationGateway)return;let s=this.resolveWebLogicalDeviceId();if(!s)return;let o=this.rtdbPresenceScope??await this.resolveRtdbScope(this.getCurrentUserId()??void 0);if(!o)return;this.rtdbTicketVersion+=1;let a=this.rtdbTicketVersion,c=this.buildRtdbPresenceFields(e,t,n,i);if(this._rtdbPresence&&this.rtdbPresenceScope){await this._rtdbPresence.bumpTicketVersion(o,s,a,c);return}await this.registerRtdbPresence(o,s,a,c);}async stopAuthScopedActivity(e){lt("WasmBridge.stopAuthScopedActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(n){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",n);}this.presenceManager.stop(),this.rtdbPresenceDisabledForSession=false,this.rtdbPresenceScope=null,this.rtdbTicketVersion=0,this.browserCoordinationSignaling?.stopAuthScopedActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.hasSyncedAuthToWasmClient=false,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.syncWasmAuthToken();}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let n=Date.now();for(;!this.wasmClient&&Date.now()-n<e;)await u(t);return this.wasmClient??null}normalizeDevice(e,t){return $e(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}normalizeDeviceStatusSnapshot(e){return qt(e)}normalizePeerSessionSnapshot(e){return $t(e)}toBackendConnectionStateFromPeerSession(e){return Vt(e)}normalizeConnectionStateSnapshot(e){return Yt(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 Jt(e,t)}deliverConnectionState(e,t,n,i){let s=this.stabilizeConnectionState(e);this.escalateManagedApplicationRoute(s),this.lastDeliveredConnectionStates.set(s.connectionId,s);let a=(i??this.lastDeliveredConnectionStates).get(s.connectionId);this.sameConnectionState(a,s)||(i&&i.set(s.connectionId,s),t(s));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(n=false)=>{if(e&&(!n||!t))return e;if(t)try{let s=await t(n);if(s)return s}catch{}let i=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(i&&i.uid===this.authContext?.userId)try{return await i.getIdToken(n)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||await G().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await G().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await G().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await G().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthScopedActivity({userId:e}),this.authContext=null,this.hasSyncedAuthToWasmClient=false,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,n=true,i=3e5,s,o){if(this.isTicketOnlyMode())return;let a=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?S.EPHEMERAL_DEVICE_ID_TTL_MS:i,d=await this.withWebPresenceMetadata(s,a);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:d,deviceName:o?.trim()||this.getDefaultBrowserDeviceName()}),await this.getBrowserFirestoreSignaling().updatePresence(e,t,n,c,d,o),await this.refreshRtdbPresenceTicket(e,t,d,o);}async refreshLivePresence(e,t,n,i){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),o=await this.withWebPresenceMetadata(n,s);if(this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:o,deviceName:i?.trim()||this.getDefaultBrowserDeviceName()}),this.options.coordinationGateway){await this.getBrowserFirestoreSignaling().updatePresence(e,t,true,3e5,o,i);return}await this.refreshRtdbPresenceTicket(e,t,o,i);}async setOffline(e){if(this.presenceManager.stopPresence(),!this.isTicketOnlyMode()){if(this._rtdbPresence&&this.rtdbPresenceScope){let t=this.resolveWebLogicalDeviceId();t&&await this._rtdbPresence.markOffline(this.rtdbPresenceScope,t,this.rtdbTicketVersion).catch(n=>console.warn("[WasmBridge] RTDB markOffline failed:",n));}await this.getBrowserFirestoreSignaling().setOffline(e);}}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().cleanupStaleDevices();}async sendMessage(e,t,n,i){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getBrowserFirestoreSignaling().sendMessage(e,t,n,i)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getBrowserFirestoreSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getBrowserFirestoreSignaling().searchDevices(e)}async listDevicesWithStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getBrowserFirestoreSignaling().listDevices(),n=this.wasmClient;return Promise.all(t.map(async i=>{let s=this.normalizeDeviceStatusSnapshot({...i,connectionStatus:i.online?"online":"disconnected"}),o=typeof i.nodeId=="string"?i.nodeId.trim():"";if(!o||typeof n?.iroh_path_kind!="function"||typeof n?.iroh_transport_rtt_ms!="function")return s;try{let[a,c]=await Promise.all([n.iroh_path_kind(o),n.iroh_transport_rtt_ms(o)]);if(typeof c!="number"||!Number.isFinite(c))return s;let d=Math.max(0,Math.round(c)),l={};if(a==="direct-lan")l.irohLan=d;else if(a==="direct-quic")l.iroh=d;else if(a==="ble")l.ble=d;else if(a==="relay")l.irohRelay=d;else return s;return {...s,latencyMs:d,latencyByTransport:l}}catch(a){return ue("[WasmBridge] iroh transport latency unavailable",{deviceId:i.deviceId,error:a instanceof Error?a.message:String(a)}),s}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let n=await t.peer_session(e);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(i=>this.normalizePeerSessionSnapshot(i)).filter(i=>!!(i.peerId||i.deviceId||i.deviceIdHint||i.nodeId||i.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.wait_for_settled_peer=="function"){let i=await n.wait_for_settled_peer(e,t);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.open_peer_bi=="function"){let i=await n.open_peer_bi(e,t);if(!i?.recv||!i?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:i.recv,writable:ae(i,i.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerNativeBi(e,t,n){let i=await this.waitForWasmClient(500),s=i&&i.open_peer_native_bi;if(typeof s=="function"){let o=await s.call(i,e,t,n);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_native_bi returned an invalid bidirectional stream");return {readable:o.recv,writable:ae(o,o.send)}}throw this.warnMissingWasmOnce("openPeerNativeBi"),new Error("WASM runtime does not support open_peer_native_bi()")}async openPeerBiTransportOnly(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiTransportOnly is debug-only and cannot be used when application crypto is required");let n=await this.waitForWasmClient(500),i=n&&typeof n.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiTransportOnly",{peerId:e,hasWasmClient:!!n,hasTransportOnly:i,timeoutMs:t}),i){let s=await n.open_peer_bi_transport_only(e,t);if(!s?.recv||!s?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:s.recv,writable:ae(s,s.send)}}return console.debug("[WasmBridge] openPeerBiTransportOnly falling back to openPeerBi",{peerId:e}),this.openPeerBi(e,t)}async openPeerUni(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.open_peer_uni=="function"){let i=await n.open_peer_uni(e,t),s=i?.writable??i;if(!s)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:ae(i,s)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}async resolvePeerConnectionRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let n=await t.resolve_peer_connection_records(e);return (Array.isArray(n)?n:[]).map(i=>({connectionId:typeof i.connectionId=="string"?i.connectionId:"",nodeId:typeof i.nodeId=="string"?i.nodeId:null,deviceId:typeof i.deviceId=="string"?i.deviceId:null,deviceIdHint:typeof i.deviceIdHint=="string"?i.deviceIdHint:null,endpointId:typeof i.endpointId=="string"?i.endpointId:null,transportGeneration:typeof i.transportGeneration=="number"?i.transportGeneration:0,routeGeneration:typeof i.routeGeneration=="number"?i.routeGeneration:void 0,transportStableId:typeof i.transportStableId=="number"?i.transportStableId:null,transportSource:typeof i.transportSource=="string"?i.transportSource:null,lastTransportChangeAtMs:typeof i.lastTransportChangeAtMs=="number"?i.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof i.lastRouteChangeAtMs=="number"?i.lastRouteChangeAtMs:void 0,state:typeof i.state=="string"?i.state:"pending",statusReason:typeof i.statusReason=="string"?i.statusReason:null,createdAtMs:typeof i.createdAtMs=="number"?i.createdAtMs:0,updatedAtMs:typeof i.updatedAtMs=="number"?i.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerConnectionRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let n=i=>{if(!i||typeof i!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let s=i;return {peerId:typeof s.peerId=="string"?s.peerId:null,deviceId:typeof s.deviceId=="string"?s.deviceId:null,deviceIdHint:typeof s.deviceIdHint=="string"?s.deviceIdHint:null,nodeId:typeof s.nodeId=="string"?s.nodeId:null}};if(typeof t.peer_session=="function")try{let i=await t.peer_session(e),s=n(i);if(s.peerId||s.deviceId||s.deviceIdHint||s.nodeId)return s}catch{}if(typeof t.peer_snapshot=="function")try{return n(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getBrowserFirestoreSignaling().onDevicesChange(e,t)}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getBrowserFirestoreSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let n=this.authScopedRuntimeGeneration;try{let i=await this.waitForWasmClient();if(n!==this.authScopedRuntimeGeneration||!i||typeof i.start_auto_connect!="function")return;await i.start_auto_connect(e,t),n===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(i){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:i});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnectSnapshot();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async setAutoConnectExcluded(e,t){await this.presenceManager.setAutoConnectExcluded(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.setAutoConnectExcluded(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(n){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:n?.message??String(n)}),n}}setCoreClient(e){e&&typeof e.connect=="function"?(this.coreClient=e,this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.applicationRouteEscalationSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,n=this.onConnectionStateChange(()=>{});this.applicationRouteEscalationUnsubscribe=()=>{},this.applicationRouteEscalationSubscriptionGeneration=e,Promise.resolve(n).then(i=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){i();return}this.applicationRouteEscalationUnsubscribe=i,this.applicationRouteEscalationSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.applicationRouteEscalationSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state)||this.applicationRouteEscalations.has(e.connectionId)||e.remoteNodeId&&this.coreClient.hasApplicationRouteForPeer?.(e.connectionId,e.remoteNodeId)===true)return;let t=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!t?.ticket)return;let n=this.authScopedRuntimeGeneration,i=this.coreClient,s;s=(async()=>{let o=typeof i.ensureManagedApplicationRoute=="function"?await i.ensureManagedApplicationRoute({ticket:t.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??t.nodeId,expectedDeviceId:t.deviceId,timeoutMs:2e4}):await i.connect(t.ticket,2e4,t.deviceId,void 0,{admissionAlreadyPresented:true});if(n!==this.authScopedRuntimeGeneration)return;let a=o,c=a.id?.trim()||e.connectionId,d=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||t.deviceId;if(i.hasApplicationRouteForPeer?.(c,d)!==true&&i.hasApplicationRouteForPeer?.(c,d)!==true)throw new Error(`application crypto was not ready for ${d}`)})().catch(o=>{n===this.authScopedRuntimeGeneration&&console.warn("[WasmBridge][ROUTE-ESCALATION] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:t.deviceId,remoteNodeId:e.remoteNodeId??t.nodeId,error:o?.message??String(o)});}).finally(()=>{this.applicationRouteEscalations.get(e.connectionId)===s&&this.applicationRouteEscalations.delete(e.connectionId);}),this.applicationRouteEscalations.set(e.connectionId,s);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let n=Date.now();R("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:Fi(e.endpointTicket),hasCoreClient:!!this.coreClient});let i=await t.connect_device(e.deviceId??null,e.endpointTicket);R("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:i?.remoteNodeId??null,connectionId:i?.connectionId??null,elapsedMs:Date.now()-n});let s=e.endpointTicket;if(s&&this.coreClient){let o=this.coreClient;try{R("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:i?.remoteNodeId??null,connectionId:i?.connectionId??null});let a=typeof o.ensureManagedApplicationRoute=="function"?await o.ensureManagedApplicationRoute({ticket:s,connectionId:i?.connectionId??null,remoteNodeId:i?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,timeoutMs:2e4}):await o.connect(s,2e4,e.deviceId??null,void 0,{admissionAlreadyPresented:!0}),c=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():"",d=typeof a?.deviceId=="string"?a.deviceId.trim():"",l=c||i?.remoteNodeId?.trim?.()||d||e.deviceId?.trim?.()||"",u=typeof o.hasApplicationRouteForPeer=="function"?o.hasApplicationRouteForPeer.bind(o):null;if(!(!!l&&u?.(a?.id??void 0,l)===!0)&&l&&typeof o.waitForApplicationCryptoForPeer=="function"&&!(!!await o.waitForApplicationCryptoForPeer(l,2e4)&&(!u||u(a?.id??void 0,l)===!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:l,elapsedMs:Date.now()-n}),Object.assign(new Error(`application crypto was not ready for ${l}`),{applicationCryptoNotReady:!0});R("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:c||(i?.remoteNodeId??null),connectionId:i?.connectionId??null,elapsedMs:Date.now()-n});}catch(a){if(a?.applicationCryptoNotReady)throw a;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:i?.remoteNodeId??null,connectionId:i?.connectionId??null,error:a?.message??String(a)}),i}}return i}forceReconnectSnapshot(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,n,i,s){this.presenceManager.startPresenceLoop(e,t,n,i,s);}usesSpaceScopedRtdb(){return (this.options.discoveryMode??"space")==="space"}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=a(e,t).then(n=>(this.cachedSpaceNamespaceId=n,n)).catch(()=>null);}return this.spaceNamespaceIdPromise}buildRtdbScope(e){if(this.isTicketOnlyMode())return null;let t=this.options.discoveryMode??"space",n=this.appTag;if(t==="space")return this.usesSpaceScopedRtdb()&&this.cachedSpaceNamespaceId?{kind:"space",namespaceId:this.cachedSpaceNamespaceId}:null;let i=e||this.getDiscoveryScopeId()||this.getCurrentUserId();return i?{kind:"user-scoped",appTag:n,userId:i}:null}async resolveRtdbScope(e){let t=this.buildRtdbScope(e);if(t||(this.options.discoveryMode??"space")!=="space")return t;if(!this.usesSpaceScopedRtdb())return null;let n=await this.ensureSpaceNamespaceIdPromise();return n?{kind:"space",namespaceId:n}:null}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let n={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getBrowserFirestoreSignaling().createSession(n);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getBrowserFirestoreSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getBrowserFirestoreSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"&&await t.is_connected(e)?true:this.hasConnectedIndependentPeerRoute(t,e)}async hasConnectedIndependentPeerRoute(e,t){if(!e||typeof t!="string"||t.trim().length===0)return false;let n=t.trim(),i=[];if(typeof e.peer_session=="function")try{let s=await e.peer_session(n);s&&typeof s=="object"&&i.push(this.normalizePeerSessionSnapshot(s));}catch{}if(typeof e.peer_sessions=="function")try{let s=await e.peer_sessions();Array.isArray(s)&&i.push(...s.filter(o=>!!o&&typeof o=="object").map(o=>this.normalizePeerSessionSnapshot(o)));}catch{}return i.some(s=>{let o=typeof s.peerId=="string"?s.peerId.trim():"",a=typeof s.deviceId=="string"?s.deviceId.trim():"",c=typeof s.deviceIdHint=="string"?s.deviceIdHint.trim():"",d=typeof s.nodeId=="string"?s.nodeId.trim():"";return (n===o||n===a||n===c||n===d)&&s.status==="connected"&&s.settledReady===true&&s.replacementPending!==true&&h(s.activeTransport)})}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let i=await e.connection_states(),s=(Array.isArray(i)?i:[]).map(o=>this.normalizeConnectionStateSnapshot(o)).filter(o=>!!o);return s.length>0&&ue("[WasmBridge] replaying current wasm connection states",s.map(o=>({connectionId:o.connectionId,deviceId:o.deviceId??null,deviceIdHint:o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportState:o.transportState??null,protocolState:o.protocolState??null,routable:o.routable??null}))),s}let n=(await this.listPeerSessions().catch(()=>[])).map(i=>this.toBackendConnectionStateFromPeerSession(i)).filter(i=>!!i);return n.length>0&&ue("[WasmBridge] replaying current wasm connection states",n.map(i=>({connectionId:i.connectionId,deviceId:i.deviceId??null,deviceIdHint:i.deviceIdHint??null,remoteNodeId:i.remoteNodeId??null,state:i.state,transportState:i.transportState??null,protocolState:i.protocolState??null,routable:i.routable??null}))),n}onConnectionStateChange(e){let t=new Map,n=new Map,i=this.authScopedRuntimeGeneration,s=false,o=d=>{let l=d.detail,u=typeof l?.connectionId=="string"?l.connectionId.trim():"";if(!u||s)return;let h=(n.get(u)??0)+1;n.set(u,h);let p=this.authScopedRuntimeGeneration;(async()=>{let f=this.normalizeConnectionStateSnapshot(l),g=await this.waitForWasmClient(500);if(!(s||p!==this.authScopedRuntimeGeneration||n.get(u)!==h)){if(g&&typeof g.connection_state=="function"){let b=await g.connection_state(u),v=this.normalizeConnectionStateSnapshot(b);if(!s&&p===this.authScopedRuntimeGeneration&&n.get(u)===h&&v){this.deliverConnectionState(v,e,"rust-event",t);return}}!s&&p===this.authScopedRuntimeGeneration&&n.get(u)===h&&f&&this.deliverConnectionState(f,e,"rust-event-detail",t);}})().catch(f=>{s||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:u,error:f});});},a=typeof window<"u"?window:null,c=typeof a?.addEventListener=="function"&&typeof a?.removeEventListener=="function";return c&&a.addEventListener("connection-state-changed",o),this.getConnectionStates().then(d=>{!s&&i===this.authScopedRuntimeGeneration&&d.forEach(l=>{n.has(l.connectionId)||this.deliverConnectionState(l,e,"replay",t);});}).catch(d=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",d);}),()=>{s=true,n.clear(),c&&a.removeEventListener("connection-state-changed",o);}}async sendExplicitFilePath(e,t,n=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let n=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(o=>o.trim().length>0)?.trim()??"";if(!n||n==="."||n==="..")return S.FALLBACK_EXPLICIT_FILE_NAME;let i="";for(let o of n){if([...i].length>=S.MAX_EXPLICIT_FILE_NAME_CHARS)break;let a=o.charCodeAt(0);o==="/"||o==="\\"||o==="\0"||a<32||a===127?i+="_":i+=o;}let s=i.trim();return !s||s==="."||s===".."?S.FALLBACK_EXPLICIT_FILE_NAME:s}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return S.FALLBACK_EXPLICIT_MIME_TYPE;let n="";for(let i of t){if(n.length>=S.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let s=i.charCodeAt(0);s<33||s>126||i==='"'||i==="\\"?n+="_":n+=i;}return n.length>0?n:S.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>S.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let n=0;n<e.byteLength;n+=1)e[n]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,n,i,s){let o=s?.headerFrame===true?4:0,a=new Uint8Array(25+o+i.byteLength);a[0]=S.EXPLICIT_FILE_PROTOCOL_TYPE,a.set(e,1);let c=new DataView(a.buffer);c.setUint32(17,t,false),c.setUint32(21,n,false);let d=s?.headerFrame===true?29:25;return s?.headerFrame===true&&c.setUint32(25,i.byteLength,false),a.set(i,d),a}async sendExplicitFileData(e){let t=e.connection,n=e.file,i=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!i)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let o=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`,a=typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null,c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(R("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:n.name,fileSize:n.size,transferId:o}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let d=await this.waitForWasmClient();if(!d)throw new Error("WASM explicit transfer requires an initialized WASM client");let l=new TextEncoder,u={transfer_id:o,filename:this.sanitizeExplicitFileName(n.name),size:n.size,mime_type:this.sanitizeExplicitMimeType(n.type)},h=l.encode(JSON.stringify(u));this.assertExplicitTransferHeaderSize(h);let p=new Uint8Array(4);new DataView(p.buffer).setUint32(0,h.byteLength,false);let f=new Uint8Array(p.byteLength+h.byteLength);f.set(p,0),f.set(h,p.byteLength);let g=async()=>{if(a!=="web"||!t||typeof t.sendOnWebRTC!="function"||typeof t.isWebRtcApplicationRouteReady!="function"||t.isWebRtcApplicationRouteReady()!==true)return a&&a!=="web"&&typeof t?.isWebRtcApplicationRouteReady=="function"&&t.isWebRtcApplicationRouteReady()===true&&R("[WasmBridge] sendExplicitFileData kept on Iroh for non-browser receiver",{remoteNodeId:c,transferId:o,receiverPlatformType:a}),false;let v=i?dt(i):null,w=F=>v?v.protectFrame(F):F,I=new Uint8Array(await n.arrayBuffer()),T=this.createWebRTCExplicitTransferId(),N=Math.max(1,Math.ceil(I.byteLength/S.EXPLICIT_FILE_CHUNK_SIZE_BYTES)),C=typeof t.getWebRTCTransport=="function"?t.getWebRTCTransport():null,L=async()=>{C&&typeof C.getBufferedAmount=="function"&&typeof C.waitForDrain=="function"&&C.getBufferedAmount()>S.EXPLICIT_FILE_CHUNK_SIZE_BYTES*4&&await C.waitForDrain(S.EXPLICIT_FILE_CHUNK_SIZE_BYTES*2);};if(await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(T,4294967295,N,w(h),{headerFrame:true})),await L(),I.byteLength===0)return await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(T,0,N,w(new Uint8Array(0)))),true;let ce=0;for(let F=0;F<I.byteLength;F+=S.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let Zt=I.slice(F,Math.min(F+S.EXPLICIT_FILE_CHUNK_SIZE_BYTES,I.byteLength));await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(T,ce,N,w(Zt))),ce+=1,await L();}return R("[WasmBridge] sendExplicitFileData sent over WebRTC explicit route",{connectionId:e.connectionId??null,remoteNodeId:c,transferId:o,chunks:N,encrypted:!!v}),true},b=async()=>{let v=d.open_peer_bi_explicit_file_sender;if(typeof v!="function")return false;let w=await v.call(d,c,5e3),I=w?.writable??w?.send;if(!I||typeof I.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");R("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let T=ae(w,I,{requireFinish:true}).getWriter(),N=false;try{await T.write(f);let C=new Uint8Array(await n.arrayBuffer());for(let L=0;L<C.byteLength;L+=S.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let ce=C.slice(L,Math.min(L+S.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await T.write(ce);}}catch(C){throw N=true,C}finally{try{await T.close();}catch(C){if(!N)throw C}finally{T.releaseLock();}}return true};try{try{if(await g())return}catch(v){R("[WasmBridge] sendExplicitFileData WebRTC explicit route failed; falling back",{remoteNodeId:c,transferId:o,error:v instanceof Error?v.message:String(v)});}if(await b())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{R("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:o,fileName:n.name,fileSize:n.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getBrowserFirestoreSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().updateFriendTicket(e);}};S.EXPLICIT_FILE_PROTOCOL_TYPE=2,S.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,S.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,S.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",S.MAX_EXPLICIT_FILE_NAME_CHARS=180,S.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",S.MAX_EXPLICIT_MIME_TYPE_CHARS=255,S.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",S.EPHEMERAL_DEVICE_ID_TTL_MS=Q.browserIdentity.ephemeralDeviceIdTtlMs;var Xt=S;var Qt=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();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,n){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,n);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,i,s){return this.backend.updatePresence(e,t,n,i,s)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDevicesWithStatus(){if(typeof this.backend.listDevicesWithStatus!="function")throw new Error("Selected runtime adapter does not support listDevicesWithStatus().");return this.backend.listDevicesWithStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerConnectionRecords(e){return typeof this.backend.resolvePeerConnectionRecords!="function"?[]:this.backend.resolvePeerConnectionRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,n,i){return this.backend.sendMessage(e,t,n,i)}async pollMessages(e){return this.backend.pollMessages(e)}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}startPresenceLoop(e,t,n,i,s){this.backend.startPresenceLoop(e,t,n,i,s);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnectSnapshot(){this.backend.forceReconnectSnapshot();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateLocalDeviceName(e){return typeof this.backend.updateLocalDeviceName!="function"?null:this.backend.updateLocalDeviceName(e)}async startManagedSessionNative(e){let t=this.backend;if(typeof t.startManagedSessionNative!="function")throw new Error("Selected runtime adapter does not support startManagedSessionNative().");return t.startManagedSessionNative(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresenceLoopOnce(e,t,n,i,s){let o=this.backend;if(typeof o.startPresenceLoopOnce!="function")throw new Error("Selected runtime adapter does not support startPresenceLoopOnce().");return o.startPresenceLoopOnce(e,t,n,i,s)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getEndpointTicketWithToken(e,t){let n=this.backend;return typeof n.getEndpointTicketWithToken!="function"?null:n.getEndpointTicketWithToken(e,t)}async registerSessionToken(e,t,n){let i=this.backend;typeof i.registerSessionToken=="function"&&await i.registerSessionToken(e,t,n);}async revokeSessionTokensByScope(e){let t=this.backend;return typeof t.revokeSessionTokensByScope!="function"?[]:t.revokeSessionTokensByScope(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async is_current_transport_stable_id(e,t){let n=this.backend;return typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerNativeBi(e,t,n){let i=this.backend;if(typeof i.openPeerNativeBi!="function")throw new Error("Selected runtime adapter does not support openPeerNativeBi().");return i.openPeerNativeBi(e,t,n)}async openPeerBiTransportOnly(e,t){let n=this.backend;return typeof n.openPeerBiTransportOnly=="function"?n.openPeerBiTransportOnly(e,t):this.openPeerBi(e,t)}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onConnectionStateChange(e){return typeof this.backend.onConnectionStateChange!="function"?()=>{}:this.backend.onConnectionStateChange(e)}async sendExplicitFilePath(e,t,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}getRuntimeCapabilities(){let e=this.backend;return typeof e.getRuntimeCapabilities=="function"?e.getRuntimeCapabilities():he()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};
2
+ export{hn as A,ut as B,he as C,qi as D,$i as E,Xt as F,Qt as G,k as a,en as b,ue as c,R as d,Oi as e,ge as f,Fr as g,Or as h,Br as i,Ur as j,Ke as k,Ci as l,cn as m,Gi as n,dt as o,lt as p,ze as q,xi as r,qt as s,$t as t,Hr as u,Kr as v,Yt as w,Q as x,zi as y,pn as z};
@@ -1 +1 @@
1
- import {g,h}from'./chunk-5QT2DMQU.js';function c(){return g()}var i=class extends h{constructor(r){super({...r,bridge:g(),allowWasmFallback:r.allowWasmFallback??false});}};export{c as a,i as b};
1
+ import {g,h}from'./chunk-POUO36QG.js';function c(){return g()}var i=class extends h{constructor(r){super({...r,bridge:g(),allowWasmFallback:r.allowWasmFallback??false});}};export{c as a,i as b};
@@ -0,0 +1,2 @@
1
+ import {x,G,D as D$1,F,B,d,q,c,p,s,t as t$1,u as u$1,v,w}from'./chunk-F3P2RCH5.js';import {x as x$1,u,a,g as g$1,t,E,G as G$1}from'./chunk-HBMXO563.js';function ie(h){let e=String(h?.message??h??"").toLowerCase();return e?e.includes("__tauri_internals__")||e.includes("window is not defined")||e.includes("cannot read properties of undefined")?"runtime-unavailable":e.includes("timeout after")?"timeout":e.includes("not found")||e.includes("not allowed")||e.includes("unknown command")||e.includes("plugin not found")||e.includes("plugin:openrtc-tauri-plugin")||e.includes("plugin:openrtc")?"command-unavailable":"unknown":"unknown"}function D(h){return ie(h)==="command-unavailable"}function N(h,e="native runtime"){if(!h||typeof h!="object")throw new Error(`[openrtc] ${e} requires a valid IPC bridge object.`);if(typeof h.invoke!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing invoke(command, args).`);if(typeof h.listen!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing listen(event, handler).`);return h}var L=null;async function ne(){return L||(L=(async()=>{let h="openrtc-tauri",e="../../../tauri/src/runtime/ipc";try{return await import(h)}catch(t){try{return await import(e)}catch(i){let n=new Error("[openrtc] Native support now lives in the first-party `openrtc-tauri` package. Install `openrtc-tauri` (and `@tauri-apps/api`) or pass an explicit IPC bridge to OpenRTC.native(...).");throw n.cause={packageError:t,workspaceError:i},n}}})()),L}function Q(){let h=null,e=async()=>(h||(h=ne().then(t=>N(t.createTauriIpcBridge(),"openrtc-tauri"))),h);return {async invoke(t,i){return (await e()).invoke(t,i)},async listen(t,i){return (await e()).listen(t,i)},async isAvailable(){try{let t=await e();return typeof t.isAvailable=="function"?!!await t.isAvailable():!0}catch{return false}}}}var ae="relay-only endpoint ticket unavailable",re=12e3,se=250,oe=1500;function ce(h){return String(h?.message??h??"").toLowerCase().includes(ae)}async function O(h,e={}){let t=e.windowMs??re,i=e.minDelayMs??se,n=e.maxDelayMs??oe,a=Date.now(),o=0,r=null;for(;e.isActive?.()??true;){o+=1;try{return await h()}catch(c){if(r=c,!ce(c))throw c;let l=Date.now()-a;if(l>=t)throw c;let s=Math.min(x$1(o,i,n),Math.max(0,t-l));s>0&&await u(s);}}throw r||new Error("endpoint ticket minting stopped before a ticket was available")}function Z(h){let e=h?.split(".")[1];if(!e)return null;try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4,n=atob(t+"=".repeat(i)),a=JSON.parse(n);return a&&typeof a=="object"&&!Array.isArray(a)?a:null}catch{return null}}function X(h,e){let t=h?.[e];return typeof t=="string"&&t.trim()?t.trim():null}function ee(h,e){return X(h,"namespaceId")===e||X(h,"appTag")===`space::${e}`}var g=class g{constructor(e){this.subscriptionNonce=0;this.lastSyncedAuthToken=null;this.cachedLocalDeviceId=null;this.cachedLocalDeviceName=null;this.tauriCoreAvailability=null;this.tauriCoreAvailabilityValue=null;this.tauriCoreAvailabilityCheckedAtMs=0;this.authSyncInFlight=null;this.nativeTrustTokenUnsubscribe=null;this.nativeTrustRelayQueue=Promise.resolve();this.nativeRuntimeCapabilitiesSyncInFlight=null;this.gatewayDesiredPeersCleanup=null;this.gatewayDesiredPeerRevision=0;this.gatewayDesiredPeerSubmission=Promise.resolve();this.lastNativeAuthSyncAtMs=0;this.hasLoggedMissingAuthForDevices=false;this.runtimeCapabilities=D$1(null,false);this.fallback=new F({...e,coordinationPlatformType:"desktop"}),this.app=this.fallback.app,this.auth=this.fallback.auth,this.appTag=this.fallback.tag,this.options=this.fallback.getResolvedOptions(),this.transportOptions=e.transports,this.strictMode=e.strictMode===true,this.turnCredentialsProvider=e.turnCredentialsProvider,this.allowWasmFallback=e.allowWasmFallback??false,this.ipcBridge=N(e.ipcBridge??Q(),"NativeIpcBridge"),this.runtimeCapabilities=D$1(null,this.allowWasmFallback),this.syncNativeRuntimeCapabilities("constructor");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}getRuntimeCapabilities(){let e=B(this.runtimeCapabilities);return e.fallback.wasm=this.allowWasmFallback,e}usesCoordinationGateway(){return this.fallback.usesCoordinationGateway()}async joinCoordinationRoom(e,t,i){await this.syncCoordinationDeviceIdentity(),await this.fallback.joinCoordinationRoom(e,t,i);}leaveCoordinationRoom(e){return this.fallback.leaveCoordinationRoom(e)}getCoordinationRoomMembers(e){return this.fallback.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){return this.fallback.watchCoordinationRoomMembers(e,t)}async syncCoordinationDeviceIdentity(){if(!this.usesCoordinationGateway())return;let e=await this.resolveLocalDeviceId();this.fallback.setCoordinationLocalDeviceId(e);}setWasmClient(e){if(!this.allowWasmFallback){let t="[NativeIpcBridge][NATIVE-GUARD] Refusing WasmClient attachment because native IPC is authoritative and WASM fallback is disabled.";throw console.error(t,{capabilities:this.getRuntimeCapabilities()}),new Error(t)}this.fallback.setWasmClient(e);}onAuthChange(e){return this.fallback.onAuthChange(e)}checkForSSOToken(){return this.fallback.checkForSSOToken()}waitForAuth(){return this.fallback.waitForAuth()}signInAnonymously(){return this.fallback.signInAnonymously()}getTurnCredentials(){return this.fallback.getTurnCredentials()}cleanupStaleDevices(){return this.fallback.cleanupStaleDevices()}sendMessage(e,t,i,n){return this.fallback.sendMessage(e,t,i,n)}pollMessages(e){return this.fallback.pollMessages(e)}createSession(e){return this.fallback.createSession(e)}updateSession(e,t){return this.fallback.updateSession(e,t)}async openPeerBi(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_stream",{peerId:e,timeoutMs:t??null}):this.fallback.openPeerBi(e,t)}async openPeerBiTransportOnly(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_transport_only_stream",{peerId:e,timeoutMs:t??null},{fallbackCommand:"open_peer_bi_stream"}):this.fallback.openPeerBiTransportOnly(e,t)}async openPeerNativeBi(e,t,i){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_native_bi_stream",{peerId:e,label:t,timeoutMs:i??null},{fallbackCommand:"open_peer_bi_stream",fallbackArgs:{peerId:e,timeoutMs:i??null}}):this.fallback.openPeerNativeBi(e,t,i)}async incoming_streams(){if(!await this.canUseTauriIpc()){let a=this.fallback;if(typeof a.incoming_streams=="function")return a.incoming_streams();throw new Error("Native incoming stream bridge is unavailable")}let e=`native-incoming-${Date.now()}-${++this.subscriptionNonce}`,t=null,i=false,n=async()=>{i=true;let a=t;t=null,await Promise.allSettled([a?Promise.resolve(a()):Promise.resolve(),this.invokeIpc("stop_rtc_subscription",{requestId:e},{timeoutMs:null}).catch(()=>{})]);};return new ReadableStream({start:async a=>{try{t=await this.listenIpc("openrtc://peer-bi-stream/incoming",o=>{if(i)return;let r=o.payload,c=typeof r?.requestId=="string"?r.requestId:typeof r?.request_id=="string"?r.request_id:"";if(c!==e){d("[NativeIpcBridge][incoming-application-stream] ignored request id",{expectedRequestId:e,eventRequestId:c});return}let l=typeof r?.streamId=="string"?r.streamId.trim():typeof r?.stream_id=="string"?r.stream_id.trim():"";if(!l)return;let s=typeof r?.remoteNodeId=="string"?r.remoteNodeId.trim():typeof r?.remote_node_id=="string"?r.remote_node_id.trim():"",u=Number.isSafeInteger(r?.transportStableId)?Number(r.transportStableId):Number.isSafeInteger(r?.transport_stable_id)?Number(r.transport_stable_id):0;if(!s||u<=0){d("[NativeIpcBridge][incoming-application-stream] ignored invalid generation",{requestId:e,remoteNodeId:s,transportStableId:u});return}d("[NativeIpcBridge][incoming-application-stream] accepted event",{requestId:e,remoteNodeId:s,transportStableId:u});let d$1=this.peerBiStreamFromId(l,{startReadAfterListeners:!0});a.enqueue({type:"bi",stream:{send:d$1.writable,recv:d$1.readable,endpoint_id:s},endpointId:s,transportStableId:u,protocolHint:"unknown",channel:null});}),await this.invokeIpc("start_incoming_peer_bi_streams",{requestId:e},{timeoutMs:null});}catch(o){i=true,a.error(o),await n();}},cancel:async()=>{await n();}})}async is_current_transport_stable_id(e,t){if(!await this.canUseTauriIpc()){let i=this.fallback;return typeof i.is_current_transport_stable_id=="function"?i.is_current_transport_stable_id(e,t):false}return !e.trim()||t<=0n||t>BigInt(Number.MAX_SAFE_INTEGER)?false:this.invokeIpc("is_current_transport_stable_id",{endpointId:e.trim(),transportStableId:Number(t)})}openPeerUni(e,t){return this.fallback.openPeerUni(e,t)}isConnected(e){return this.fallback.isConnected(e)}getAuthContext(){return this.fallback.getAuthContext()}resolveNativeAuthScopedUserId(e){return this.currentUser?.id??this.getAuthContext()?.userId??e??null}resolveConfiguredSpaceKey(){let e=this.options.spaceKey??this.options.space;return typeof e=="string"?e.trim():""}usesAnonymousSpaceMode(){return this.options.authMode==="anonymous"&&this.resolveConfiguredSpaceKey().length>0}requiresNativeAuthToken(){return !this.usesAnonymousSpaceMode()||typeof this.options.spaceTokenProvider=="function"}async nativeAuthTokenMatchesExpectedScope(e){if(!this.usesAnonymousSpaceMode())return true;let t=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",i=this.resolveConfiguredSpaceKey();if(!t||!i)return true;let n=await a(t,i).catch(()=>null);return n?ee(Z(e),n):true}resolveNativeSignalingUserId(e){return this.usesAnonymousSpaceMode()?(typeof e=="string"?e.trim():"")||this.resolveConfiguredSpaceKey()||null:this.resolveNativeAuthScopedUserId(e)}getCurrentUserId(){return this.resolveNativeSignalingUserId(this.fallback.getCurrentUserIdForScope())}nativeAuthWaitMs(){return this.requiresNativeAuthToken()?g.AUTH_REQUIRED_WAIT_MS:0}resolveWebLogicalDeviceId(){return this.fallback.getResolvedWebLogicalDeviceId()}normalizeDevice(e,t){return this.fallback.normalizeDeviceRecord(e,t)}matchesTag(e){return this.fallback.matchesLegacyOrCurrentTag(e)}nativeRosterTagDisposition(e){let t=q(e);if(this.matchesTag(t))return {keep:true,classification:"match"};let i=typeof t.appTag=="string"&&t.appTag.trim().length>0?t.appTag.trim():typeof t.tag=="string"&&t.tag.trim().length>0?t.tag.trim():void 0;return i===void 0?{keep:true,classification:"untagged"}:{keep:false,classification:"foreign",foreignTag:i}}filterNativeRosterByTag(e,t){let i=new Set,n=e.filter(a=>{let o=this.nativeRosterTagDisposition(a);return !o.keep&&o.foreignTag&&i.add(o.foreignTag),o.keep});return e.length>0&&n.length===0&&i.size>0?console.warn(`[NativeIpcBridge] ${t}: dropped ALL ${e.length} native device(s) as foreign-app \u2014 this is the app-tag drift signature (empty native device list). The native Rust OpenRTC app tag does not match the SDK app tag; check that the desktop binary and the web bundle use the same VITE_PLUTO_OPENRTC_API_KEY / VITE_PLUTO_OPENRTC_APP_TAG for this environment lane.`,{sdkAppTag:this.appTag,foreignTags:Array.from(i),droppedCount:e.length}):i.size>0&&d(`[NativeIpcBridge] ${t}: filtered ${e.length-n.length} foreign-app device(s) from the native roster`,{sdkAppTag:this.appTag,foreignTags:Array.from(i)}),n}normalizeNativeIceServer(e){let t=e.urls,i=Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.trim().length>0):typeof t=="string"&&t.trim().length>0?[t]:[];return i.length===0?null:{urls:i,username:typeof e.username=="string"&&e.username.trim().length>0?e.username:void 0,credential:typeof e.credential=="string"&&e.credential.trim().length>0?e.credential:void 0}}filterNativeStunServers(e){return e.map(t=>({...t,urls:t.urls.filter(i=>!i.startsWith("stun:"))})).filter(t=>t.urls.length>0)}nativeIceServerHasTurnUrl(e){return e.urls.some(t=>t.startsWith("turn:")||t.startsWith("turns:"))}async loadNativeTurnIceServers(){if(typeof this.turnCredentialsProvider!="function")return [];let e=await this.turnCredentialsProvider().catch(t=>(console.warn("[NativeIpcBridge] TURN credential provider failed:",t),null));return !e||!Array.isArray(e.iceServers)?[]:e.iceServers.map(t=>this.normalizeNativeIceServer(t)).filter(t=>!!t)}async buildNativeTransportConfigPayload(){let e=this.transportOptions;if(!e&&!this.strictMode)return null;let t=null;if(!this.strictMode&&e?.iroh&&typeof e.iroh=="object"){let l=e.iroh;l.localDiscovery===true&&(t={enabled:true,advertise:l.localDiscoveryMode!=="passive"});}let i=null;if(e?.webrtc===true||e?.webrtc&&typeof e.webrtc=="object"){let l=e.webrtc===true?null:e.webrtc,s=l?.useDefaultIceServers!==false,u=Array.isArray(l?.iceServers)&&l.iceServers.length>0?l.iceServers.map(m=>this.normalizeNativeIceServer(m)).filter(m=>!!m):s?g$1.map(m=>this.normalizeNativeIceServer(m)).filter(m=>!!m):[],d=this.strictMode||l?.privacyMode===true;(this.strictMode||l?.privacyMode===true||l?.useTurn===true)&&(u=[...u,...await this.loadNativeTurnIceServers()]),d&&(u=this.filterNativeStunServers(u));let v=u.some(m=>this.nativeIceServerHasTurnUrl(m)),f=d&&v;d&&!v&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let _=l?.lanMode===true;(u.length>0||f||_||!s)&&(i={iceServers:u.length>0||!s?u:void 0,privacyMode:f,lanMode:_||void 0});}let n=null;if(e?.moq&&typeof e.moq=="object"){let l=typeof e.moq.relayUrl=="string"&&e.moq.relayUrl.trim().length>0?e.moq.relayUrl:void 0;if(l){let s=typeof e.moq.accessToken=="string"&&e.moq.accessToken.trim().length>0?e.moq.accessToken.trim():void 0;n={relayUrl:l,accessToken:s};}}let a=null;if(!this.strictMode&&(e?.ble===true||e?.ble&&typeof e.ble=="object")){let l=e.ble===true?null:e.ble,s=Number(l?.connectTimeoutMs);a={enabled:l?.enabled!==false,connectTimeoutMs:Number.isFinite(s)&&s>0?Math.round(s):void 0};}let o=this.strictMode||e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true,r=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,c=this.strictMode?r??"auto":r;return !o&&!c&&!i&&!n&&!t&&!a?null:{irohRelayOnly:o||void 0,irohRelayTransportPolicy:c,irohLan:t,webrtc:i,moq:n,ble:a}}isTauriEnv(){return t()}nextConnectionEventRetryDelayMs(e){return x$1(e,g.CONNECTION_EVENT_RETRY_MIN_DELAY_MS,g.CONNECTION_EVENT_RETRY_MAX_DELAY_MS)}async clearNativeAuthRelay(e){if(await this.canUseTauriIpc())try{await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:null,refreshToken:null}),this.lastSyncedAuthToken=null,this.lastNativeAuthSyncAtMs=0,d(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}async clearNativeTrustRelay(e){if(this.nativeTrustTokenUnsubscribe?.(),this.nativeTrustTokenUnsubscribe=null,this.fallback.invalidateCoordinationNativeTrustToken(),!!await this.canUseTauriIpc())try{await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:null,expiresAtMs:null}),d(`[NativeIpcBridge] cleared native trust relay (${e})`);}catch(t){D(t)||console.warn(`[NativeIpcBridge] failed clearing native trust relay (${e}):`,t);}}relayNativeTrustToken(e,t){let i=async()=>{await this.canUseTauriIpc()&&(await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:e?.token??null,expiresAtMs:e?.expiresAtMs??null}),d(`[NativeIpcBridge] native trust token ${e?"relayed":"cleared"} (${t})`));},n=this.nativeTrustRelayQueue.then(i,i);return this.nativeTrustRelayQueue=n.catch(()=>{}),n}async ensureNativeTrustRelay(e=false){if(!this.usesCoordinationGateway()||typeof this.options.coordinationGateway?.nativeTrustTokenProvider!="function"||!await this.canUseTauriIpc())return true;try{let t=await this.fallback.getCoordinationNativeTrustToken(e);return await this.relayNativeTrustToken(t,"auth-ready"),this.nativeTrustTokenUnsubscribe||(this.nativeTrustTokenUnsubscribe=this.fallback.subscribeCoordinationNativeTrustToken(i=>{this.relayNativeTrustToken(i,"provider-refresh").catch(n=>{console.warn("[NativeIpcBridge] native trust token refresh relay failed:",n);});},{emitCurrent:!1})),!0}catch(t){return console.warn("[NativeIpcBridge] native trust token unavailable:",t),false}}async relayNativeAuthToken(e,t,i,n){if(!await this.canUseTauriIpc())return true;if(!await this.nativeAuthTokenMatchesExpectedScope(e))return d(`[NativeIpcBridge] auth sync deferred (${i}): token claims do not match configured space`),false;if(e===this.lastSyncedAuthToken)return true;try{await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:e,refreshToken:t??null});}catch(a){return D(a)?console.warn(`[NativeIpcBridge] desktop auth relay unavailable (${i}); install/register openrtc-tauri-plugin and include its default permission set.`,a):console.warn(`[NativeIpcBridge] desktop auth relay failed (${i}):`,a),false}return this.lastSyncedAuthToken=e,this.lastNativeAuthSyncAtMs=Date.now(),d(`[NativeIpcBridge] auth token relayed to native runtime (${i}) user_id=${n??this.currentUser?.id??"unknown"}`),true}async relayExplicitNativeAuthContext(e){let t=this.authSyncInFlight,i=(async()=>(await t?.catch(()=>{}),this.relayNativeAuthToken(e.token,e.refreshToken,"setAuthContext",e.userId)))();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}applyNativeRuntimeStatus(e){this.runtimeCapabilities=D$1(e,this.allowWasmFallback);}syncNativeRuntimeCapabilities(e){return this.ipcBridge?this.nativeRuntimeCapabilitiesSyncInFlight?this.nativeRuntimeCapabilitiesSyncInFlight:(this.nativeRuntimeCapabilitiesSyncInFlight=(async()=>{try{let t=await this.invokeIpc("rtc_native_status",void 0,{timeoutMs:g.NATIVE_STATUS_IPC_TIMEOUT_MS});this.applyNativeRuntimeStatus(t),d(`[NativeIpcBridge] refreshed native runtime capabilities (${e})`);}catch(t){c("[NativeIpcBridge] native runtime capability refresh skipped",t);}})().finally(()=>{this.nativeRuntimeCapabilitiesSyncInFlight=null;}),this.nativeRuntimeCapabilitiesSyncInFlight):Promise.resolve()}async canUseTauriIpc(){if(this.ipcBridge){let e=typeof this.ipcBridge.isAvailable=="function"?!!await this.ipcBridge.isAvailable():true;return e&&this.syncNativeRuntimeCapabilities("ipc-available"),e}return typeof window>"u"?false:this.tauriCoreAvailabilityValue===true?true:this.tauriCoreAvailabilityValue===false&&Date.now()-this.tauriCoreAvailabilityCheckedAtMs<g.TAURI_IPC_NEGATIVE_CACHE_MS?false:(this.tauriCoreAvailability||(this.tauriCoreAvailability=(async()=>{try{if(this.isTauriEnv())return this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),this.syncNativeRuntimeCapabilities("tauri-env"),!0;try{let e=await this.invokeIpc("rtc_native_status");return this.applyNativeRuntimeStatus(e),d("[NativeIpcBridge] Resolved Tauri IPC via rtc_native_status probe"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0}catch(e){let t=String(e?.message??e??"");return t.includes("__TAURI_INTERNALS__")||t.includes("Cannot read properties of undefined")||t.includes("window is not defined")?(this.tauriCoreAvailabilityValue=!1,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!1):(d("[NativeIpcBridge] Tauri IPC probe reached native layer (command-level error acceptable)"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0)}}catch{return this.tauriCoreAvailabilityValue=false,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),false}})().finally(()=>{this.tauriCoreAvailability=null;})),this.tauriCoreAvailability)}async invokeIpc(e,t,i){let n=this.ipcBridge.invoke(e,t),a=i&&Object.prototype.hasOwnProperty.call(i,"timeoutMs")?i.timeoutMs:g.DEFAULT_BOUNDED_IPC_TIMEOUT_MS;return a==null||a<=0?n:E(n,a,()=>new Error(`${e} timeout after ${a}ms`))}async listenIpc(e,t){return this.ipcBridge.listen(e,i=>{t({payload:i});})}async openPeerBiViaIpc(e,t,i){let n=await this.invokePeerBiOpen(e,t,i),a=typeof n?.streamId=="string"?n.streamId.trim():typeof n?.stream_id=="string"?n.stream_id.trim():"";if(!a)throw new Error(`${e} returned no streamId`);return this.peerBiStreamFromId(a)}peerBiStreamFromId(e,t={}){let i=this,n=null,a=null,o=false,r=null,c=null,l=async()=>{let v=[n,a];n=null,a=null,await Promise.allSettled(v.filter(f=>typeof f=="function").map(f=>Promise.resolve(f())));},s=(async()=>{n=await this.listenIpc("openrtc://peer-bi-stream/chunk",v=>{let f=v.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||o||!r)return;let w=f?.bytes;w instanceof Uint8Array?r.enqueue(w):Array.isArray(w)&&r.enqueue(new Uint8Array(w));}),a=await this.listenIpc("openrtc://peer-bi-stream/closed",v=>{let f=v.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||o||!r)return;o=true;let w=typeof f?.error=="string"?f.error.trim():"";w?r.error(new Error(w)):r.close(),l();}),t.startReadAfterListeners&&await this.invokeIpc("start_peer_bi_stream_read",{streamId:e},{timeoutMs:null});})().catch(v=>{c=v,r&&!o&&(o=true,r.error(v));}),u=async()=>{await this.invokeIpc("close_peer_bi_stream",{streamId:e},{timeoutMs:null}).catch(()=>{}),await l();},d=new ReadableStream({async start(v){r=v,await s,c&&!o&&(o=true,v.error(c));},async cancel(){o=true,await u();}}),y=new WritableStream({write:async v=>{await i.invokeIpc("write_peer_bi_stream",{streamId:e,bytes:Array.from(v)},{timeoutMs:null});},close:u,abort:u});return {readable:d,writable:y}}async invokePeerBiOpen(e,t,i){try{return await this.invokeIpc(e,t)}catch(n){if(!i?.fallbackCommand||!this.isMissingNativeCommandError(n))throw n;return this.invokeIpc(i.fallbackCommand,i.fallbackArgs??t)}}isMissingNativeCommandError(e){let t=e instanceof Error?e.message:String(e??"");return t.includes("Command")&&t.includes("not found")}async shouldUseTauriSignaling(){if(await this.canUseTauriIpc())return true;if(this.allowWasmFallback)return false;throw new Error("[pluto-rtc] Tauri runtime adapter requires native IPC, but it is unavailable.")}async signInWithPluto(){if(!await this.canUseTauriIpc()){await this.fallback.signInWithPluto();return}let e=await this.invokeIpc("rtc_sign_in_with_pluto"),t=typeof e?.customToken=="string"?e.customToken.trim():"";if(!t)throw new Error("[pluto-rtc] Native Pluto SSO did not return a custom token.");await G$1().signInWithCustomTokenValue(t),await this.ensureNativeAuth("pluto-sso",{requireToken:true,maxWaitMs:1e4});}async setAuthContext(e){let t=this.getAuthContext()?.userId??null,i=typeof e?.userId=="string"&&e.userId.trim()||null,n=this.fallback.setAuthContext(e);if(t&&i&&t!==i&&await this.stopNativeAuthScopedActivity(t),await n,!e?.token)await this.clearNativeAuthRelay("setAuthContext"),await this.clearNativeTrustRelay("setAuthContext");else {if(!await this.relayExplicitNativeAuthContext(e))throw new Error("Native auth token unavailable for setAuthContext");if(!await this.ensureNativeTrustRelay())throw new Error("Native trust token unavailable for setAuthContext")}}async signOut(){await this.fallback.signOut(),await Promise.all([this.clearNativeAuthRelay("signOut"),this.clearNativeTrustRelay("signOut")]);}async stopAuthScopedActivity(e){let t=this.resolveNativeSignalingUserId(e?.userId??null);await this.stopNativeAuthScopedActivity(t);}async stopNativeAuthScopedActivity(e){this.stopGatewayDesiredPeerRelay();let t=await this.shouldUseTauriSignaling();if(p("NativeIpcBridge.stopAuthScopedActivity",{userId:e,useTauri:t}),t)try{await Promise.allSettled([this.revokeSessionTokensByScope("user-device"),this.invokeIpc("stop_rtc_presence_loop"),this.invokeIpc("stop_rtc_auto_connect"),e&&!this.usesCoordinationGateway()?this.invokeIpc("set_rtc_offline",{userId:e}):Promise.resolve()]);}catch(i){console.warn("[NativeIpcBridge] Failed to stop native auth-scoped RTC activity:",i);}await this.fallback.stopAuthScopedActivity({userId:e});}async ensureNativeAuthOnce(e,t){if(!await this.canUseTauriIpc())return true;if(this.authSyncInFlight)return this.authSyncInFlight;let i=(async()=>{try{if(!this.currentUser)return d(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let n=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,a=this.currentUser?.getToken?await this.currentUser.getToken(n):null,r=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;return a?this.relayNativeAuthToken(a,r,e,this.currentUser?.id):(d(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t)}catch(n){return console.error("[NativeIpcBridge] auth sync failed:",n),false}})();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}async ensureNativeAuth(e="runtime",t){if(!await this.canUseTauriIpc())return true;let i=t?.requireToken??false,n=t?.maxWaitMs??(i?g.AUTH_REQUIRED_WAIT_MS:0),a=t?.pollMs??250,o=Date.now()+Math.max(0,n);for(;;){if(await this.ensureNativeAuthOnce(e,i))return true;if(!i||Date.now()>=o)return false;await u(a);}}decodeNativeDeviceIdentity(e){let t=e?.systemInfo??e?.system_info??null,i=typeof e?.deviceId=="string"?e.deviceId.trim():typeof e?.device_id=="string"?e.device_id.trim():"",n=typeof e?.deviceName=="string"?e.deviceName.trim():typeof e?.device_name=="string"?e.device_name.trim():"",a=typeof e?.platformType=="string"?e.platformType.trim():typeof e?.platform_type=="string"?e.platform_type.trim():typeof t?.platformType=="string"?t.platformType.trim():typeof t?.platform_type=="string"?t.platform_type.trim():"";return {deviceId:i,deviceName:n,platformType:a}}async resolveLocalDeviceId(){if(this.cachedLocalDeviceId)return this.cachedLocalDeviceId;if(await this.canUseTauriIpc())try{let t=await this.invokeIpc("get_rtc_local_device_info"),{deviceId:i,deviceName:n}=this.decodeNativeDeviceIdentity(t);if(i)return this.cachedLocalDeviceId=i,n&&(this.cachedLocalDeviceName=n),i}catch(t){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",t);}let e=this.resolveWebLogicalDeviceId();return this.cachedLocalDeviceId=e,e}async resolveLocalDeviceName(){if(this.cachedLocalDeviceName)return this.cachedLocalDeviceName;if(await this.canUseTauriIpc())try{let e=await this.invokeIpc("get_rtc_local_device_info"),{deviceName:t}=this.decodeNativeDeviceIdentity(e);if(t){let i=this.normalizeNativeDeviceName(t);return this.cachedLocalDeviceName=i,i}}catch(e){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",e);}return this.defaultDeviceNameFallback()}normalizeNativeDeviceName(e){let t=e.trim();if(!t)return this.defaultDeviceNameFallback();if(t==="Desktop Device"){let i=this.defaultDeviceNameFallback();if(i!=="Desktop Device")return i}return t}defaultDeviceNameFallback(){if(typeof window>"u"||typeof navigator>"u")return "Desktop Device";let e=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(e)?"iPhone":/Android/i.test(e)?"Android":"Desktop Device"}inferNativePlatformTypeFallback(){if(typeof window>"u"||typeof navigator>"u")return "desktop";if(!this.isTauriEnv())return "web";let e=navigator.userAgent||"";return /iPhone|iPad|iPod|Android|Mobile/i.test(e)?"mobile":"desktop"}withPresenceMetadata(e,t){try{let i=e?JSON.parse(e):{};return JSON.stringify({...i,deviceId:t,plutoVersion:"0.1.0-desktop"})}catch{return JSON.stringify({deviceId:t,plutoVersion:"0.1.0-desktop",rawMetadata:e})}}async searchDevices(e){if(this.usesCoordinationGateway())return this.fallback.searchDevices(e);if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("searchDevices",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for searchDevices");let i=await this.invokeIpc("search_rtc_devices",{userId:this.getCurrentUserId()});if(Array.isArray(i?.devices)){let n=i.devices.map(a=>this.normalizeDevice(a));return e&&(n=n.filter(a=>a.ticket!==e&&a.deviceId!==e&&a.nodeId!==e)),n}throw typeof i?.message=="string"?new Error(String(i.message)):new Error("Unexpected response for search_rtc_devices")}return this.fallback.searchDevices(e)}async listDevicesWithStatus(){if(this.usesCoordinationGateway())return (await this.fallback.searchDevices()).map(e=>s(e));if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("listDevicesWithStatus",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for listDevicesWithStatus");let t=await this.invokeIpc("search_rtc_devices_with_status",{userId:this.getCurrentUserId()});if(Array.isArray(t?.devices)){let i=t.devices,n=this.filterNativeRosterByTag(i,"listDevicesWithStatus").map(r=>s(r)),a=await this.resolveLocalDeviceId().catch(()=>null),o=!!a&&n.some(r=>r.deviceId===a);return c("[NativeIpcBridge] listDevicesWithStatus result",{rawCount:i.length,count:n.length,localDeviceId:a,selfIncluded:o,devices:n.map(r=>({deviceId:r.deviceId,deviceName:r.deviceName,online:!!r.online,presenceStatus:r.presenceStatus,connectable:r.connectable,connectionStatus:r.connectionStatus,settledReady:!!r.settledReady,peerHealth:r.peerHealth,scopes:r.scopes,connectionId:r.connectionId??null,deviceIdHint:r.deviceIdHint??null,nodeId:r.nodeId??null,activeTransport:r.activeTransport??null,parallelTransport:r.parallelTransport??null}))}),a&&!o&&c("[NativeIpcBridge] native status snapshot excludes local device by design",{localDeviceId:a,count:n.length}),n}throw typeof t?.message=="string"?new Error(String(t.message)):new Error("Unexpected response for search_rtc_devices_with_status")}return this.fallback.listDevicesWithStatus()}async getPeerSession(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("get_rtc_peer_session",{id:e});return !t||typeof t!="object"?null:t$1(t)}return this.fallback.getPeerSession(e)}async listPeerSessions(){if(await this.shouldUseTauriSignaling()){let e=await this.invokeIpc("list_rtc_peer_sessions");return (Array.isArray(e)?e:[]).map(t=>t$1(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let i=typeof t=="number"?Math.max(g.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,t+1e3):g.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,n=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:i});return !n||typeof n!="object"?null:t$1(n)}return this.fallback.waitForSettledPeer(e,t)}async resolvePeerConnectionRecords(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_connection_records",{id:e});return (Array.isArray(t)?t:[]).map(i=>u$1(i))}return this.fallback.resolvePeerConnectionRecords(e)}async resolvePeerIdentity(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_identity",{id:e});return v(t)}return this.fallback.resolvePeerIdentity(e)}async setOffline(e){if(this.usesCoordinationGateway())return this.fallback.setOffline(e);if(await this.shouldUseTauriSignaling())try{if(!await this.ensureNativeAuth("setOffline",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for setOffline");let i=this.getCurrentUserId();await this.invokeIpc("set_rtc_offline",{userId:i});return}catch(t){console.warn("[NativeIpcBridge] set_rtc_offline failed:",t);}return this.fallback.setOffline(e)}async updateDevice(e,t){if(this.usesCoordinationGateway())return await this.syncCoordinationDeviceIdentity(),this.fallback.updateDevice(e,t);if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("updateDevice",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for updateDevice");let a=this.getCurrentUserId();if(!a)throw new Error("updateDevice requires authenticated user scope");try{await this.invokeIpc("update_rtc_device",{userId:a,deviceId:e,deviceName:t.deviceName??null,capabilities:t.capabilities??null,metadata:t.metadata??null});return}catch(o){throw console.warn("[NativeIpcBridge] update_rtc_device failed:",o),o instanceof Error?o:new Error(String(o))}}return this.fallback.updateDevice(e,t)}async deleteDevice(e){if(this.usesCoordinationGateway())return await this.syncCoordinationDeviceIdentity(),this.fallback.deleteDevice(e);if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("deleteDevice",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for deleteDevice");let n=this.getCurrentUserId();if(!n)throw new Error("deleteDevice requires authenticated user scope");try{await this.invokeIpc("delete_rtc_device",{userId:n,deviceId:e});return}catch(a){throw console.warn("[NativeIpcBridge] delete_rtc_device failed:",a),a instanceof Error?a:new Error(String(a))}}return this.fallback.deleteDevice(e)}async getLocalDeviceInfo(){if(!await this.canUseTauriIpc()){let e=await this.getLocalDeviceId?.();return e?{deviceId:e,deviceName:this.defaultDeviceNameFallback(),platformType:this.inferNativePlatformTypeFallback()}:null}try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=this.decodeNativeDeviceIdentity(e),{deviceId:i}=t;return i?{deviceId:i,deviceName:this.normalizeNativeDeviceName(t.deviceName),platformType:t.platformType||this.inferNativePlatformTypeFallback(),capabilities:e?.capabilities??void 0,lastSeenAt:typeof e?.last_seen_at=="string"?e.last_seen_at:void 0}:null}catch(e){return console.warn("[NativeIpcBridge] getLocalDeviceInfo failed:",e),null}}async updateLocalDeviceName(e){if(!await this.canUseTauriIpc())return null;try{let t=await this.invokeIpc("update_rtc_local_device_name",{deviceName:e}),i=this.decodeNativeDeviceIdentity(t),{deviceId:n}=i;return n?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:n,deviceName:this.cachedLocalDeviceName,platformType:i.platformType||this.inferNativePlatformTypeFallback(),capabilities:t?.capabilities??void 0,lastSeenAt:typeof t?.last_seen_at=="string"?t.last_seen_at:void 0}):null}catch(t){return console.warn("[NativeIpcBridge] updateLocalDeviceName failed:",t),null}}async startManagedSessionNative(e){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startManagedSessionNative().");if(!await this.ensureNativeAuth("startManagedSessionNative",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startManagedSessionNative");let i=this.resolveNativeSignalingUserId(e.userId);if(!i)throw new Error("Native managed session startup requires a runtime auth-scoped user id.");i!==e.userId&&console.info("[NativeIpcBridge][managed-session][user-id-remap]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i});let n=this.resolveConfiguredSpaceKey();console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,spaceKey:n?"[configured]":null,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,presence:e.presence!==false,autoConnect:e.autoConnect!==false,hasMetadata:typeof e.metadata=="string"&&e.metadata.trim().length>0});let a=await this.buildNativeTransportConfigPayload(),o=this.usesCoordinationGateway(),r={userId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...a?{transports:a}:{},autoConnect:o?false:e.autoConnect!==false,presence:o?false:e.presence!==false,apiKey:this.options.apiKey??null,spaceKey:n||null},c=await this.invokeIpc("start_rtc_managed_session",r,{timeoutMs:null});this.syncNativeRuntimeCapabilities("managed-session-started");let l=typeof c?.ticket=="string"&&c.ticket.trim().length>0?c.ticket.trim():null,s=c?.localDevice&&typeof c.localDevice=="object"?c.localDevice:c?.local_device&&typeof c.local_device=="object"?c.local_device:null,u=s?{deviceId:typeof s.deviceId=="string"?s.deviceId:typeof s.device_id=="string"?s.device_id:"",deviceName:this.normalizeNativeDeviceName(typeof s.deviceName=="string"?s.deviceName:typeof s.device_name=="string"?s.device_name:""),platformType:typeof s.platformType=="string"?s.platformType:typeof s.platform_type=="string"?s.platform_type:"desktop",capabilities:s.capabilities??void 0,lastSeenAt:typeof s.lastSeenAt=="string"?s.lastSeenAt:typeof s.last_seen_at=="string"?s.last_seen_at:void 0}:null,d={localNodeId:typeof c?.localNodeId=="string"?c.localNodeId:typeof c?.local_node_id=="string"?c.local_node_id:null,ticket:l,ticketScope:typeof c?.ticketScope=="string"?c.ticketScope:typeof c?.ticket_scope=="string"?c.ticket_scope:null,presenceStarted:typeof c?.presenceStarted=="boolean"?c.presenceStarted:!!c?.presence_started,autoConnectStarted:typeof c?.autoConnectStarted=="boolean"?c.autoConnectStarted:!!c?.auto_connect_started,localDevice:u?.deviceId?u:null};if(o){e.presence!==false&&!d.ticket&&(d.ticket=await this.getEndpointTicketWithToken("user-device",0),d.ticketScope=d.ticket?"user-device":null);let y=d.localDevice?.deviceId||e.localDeviceId?.trim()||await this.resolveLocalDeviceId();if(y&&this.fallback.setCoordinationLocalDeviceId(y),e.presence!==false){if(!d.localNodeId||!d.ticket)throw new Error("Native managed session did not return the node identity required for gateway presence.");await this.fallback.updatePresence(d.localNodeId,d.ticket,true,3e5,e.metadata,d.localDevice?.deviceName||e.deviceName),d.presenceStarted=true;}else d.presenceStarted=false;e.autoConnect!==false&&y?(await this.startGatewayAutoConnect(i,y),d.autoConnectStarted=true):d.autoConnectStarted=false;}return console.info("[NativeIpcBridge][managed-session][ipc-started]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,localNodeId:d.localNodeId,ticketScope:d.ticketScope,presenceStarted:d.presenceStarted,autoConnectStarted:d.autoConnectStarted,localDeviceId:d.localDevice?.deviceId??null}),d}async reconcileNativeManagedSession(e){if(this.usesCoordinationGateway())return console.info("[NativeIpcBridge] native Firebase managed-session reconciliation is disabled in the staging gateway lane.",{reason:e?.reason??"frontend"}),null;if(!await this.shouldUseTauriSignaling())return null;if(!await this.ensureNativeAuth("reconcileNativeManagedSession",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for reconcileNativeManagedSession");return this.invokeIpc("reconcile_mobile_rtc_after_resume",{reason:e?.reason??"frontend"})}async notifyNetworkChange(e){return await this.canUseTauriIpc()?(d("[NativeIpcBridge] forwarding host network-change hint",{reason:e?.reason??"host"}),this.invokeIpc("notify_rtc_network_change")):null}async getManagedNodeId(e){let t=e?.initializeIfMissing??true;console.info("[NativeIpcBridge][getManagedNodeId] enter",{initializeIfMissing:t});let i=await this.canUseTauriIpc();if(console.info("[NativeIpcBridge][getManagedNodeId] canUseTauriIpc",{canUse:i}),!i)return null;try{console.info("[NativeIpcBridge][getManagedNodeId] invoking get_iroh_node_id");let n=await this.invokeIpc("get_iroh_node_id");if(console.info("[NativeIpcBridge][getManagedNodeId] get_iroh_node_id returned",{existing:n}),n||!t)return n;console.info("[NativeIpcBridge][getManagedNodeId] invoking start_iroh_node");let a=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:a}),a}catch(n){if(console.warn("[NativeIpcBridge] getManagedNodeId failed:",n),!t)return null;throw n}}async getEndpointTicket(){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] getEndpointTicket requires native IPC in Tauri runtime.");return O(()=>this.invokeIpc("get_iroh_endpoint_ticket"))}async connectToDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] connectToDevice requires native IPC in Tauri runtime.");this.options.authMode!=="anonymous"?await this.ensureNativeAuth("connectToDevice",{requireToken:true,maxWaitMs:g.AUTH_REQUIRED_WAIT_MS}):d("[NativeIpcBridge] connectToDevice using anonymous native ticket path");let t=Math.max(1,Math.floor(e.timeoutMs??g.DEFAULT_BOUNDED_IPC_TIMEOUT_MS));return this.invokeIpc("connect_to_device",{deviceId:e.deviceId??null,endpointTicket:e.endpointTicket,timeoutMs:t},{timeoutMs:t+1e3})}async registerSessionToken(e,t,i){await this.canUseTauriIpc()&&await this.invokeIpc("register_session_token",{token:e,scope:t,maxConnections:i});}async getEndpointTicketWithToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await O(()=>this.invokeIpc("get_endpoint_ticket_with_token",{scope:e,maxConnections:t}))}catch{return null}}async validateSessionToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await this.invokeIpc("validate_session_token",{token:e,connectionId:t??null})}catch{return null}}async revokeSessionTokensByScope(e){if(p("NativeIpcBridge.revokeSessionTokensByScope",{grantScope:e}),!await this.canUseTauriIpc())return [];try{return await this.invokeIpc("revoke_session_tokens_by_scope",{scope:e})}catch{return []}}async disconnectDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] disconnectDevice requires native IPC in Tauri runtime.");await this.invokeIpc("disconnect_device",{deviceId:e});}async setAutoConnectExcluded(e,t){await this.canUseTauriIpc()&&await this.invokeIpc(this.usesCoordinationGateway()?"set_rtc_external_auto_connect_excluded":"set_auto_connect_excluded",{deviceId:e,excluded:t});}onDevicesChange(e,t){if(this.usesCoordinationGateway())return this.fallback.onDevicesChange(e,t);let i=false,n=new Map,a=null,o=false,r=false,c=()=>{if(r=false,i)return;let d=Array.from(n.values());t&&(d=d.filter(y=>y.ticket!==t&&y.deviceId!==t&&y.nodeId!==t)),e(d);},l=()=>{if(!r){if(r=true,typeof queueMicrotask=="function"){queueMicrotask(c);return}Promise.resolve().then(c);}},s=async()=>{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] onDevicesChange falling back to wasm signaling (Tauri IPC unavailable)"),u$1=this.fallback.onDevicesChange(e,t);return}for(;!i;)try{let d$1=this.requiresNativeAuthToken()?15e3:0,y=Date.now()+d$1,v=this.getCurrentUserId();for(;!i&&!v&&Date.now()<y&&(this.hasLoggedMissingAuthForDevices||(this.hasLoggedMissingAuthForDevices=!0,d("[NativeIpcBridge] onDevicesChange waiting for authenticated user before subscription")),v=this.getCurrentUserId(),!v);)await u(250);if(!v){!i&&!o&&(console.warn("[NativeIpcBridge] onDevicesChange could not resolve authenticated user; keeping subscription in retry mode"),e([]),o=!0),await u(1e3);continue}if(!await this.ensureNativeAuth("onDevicesChange",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:Math.max(0,y-Date.now())})){!i&&!o&&(console.warn("[NativeIpcBridge] onDevicesChange timed out waiting for auth token; keeping subscription in retry mode"),e([]),o=!0),await u(1e3);continue}this.hasLoggedMissingAuthForDevices=!1,o=!1,d(`[NativeIpcBridge] onDevicesChange starting subscription user_id=${v}`);let _=await this.listDevicesWithStatus().catch(async m=>(d(`[NativeIpcBridge] onDevicesChange full-roster seed failed; falling back to online-only search: ${m}`),this.searchDevices(t)));n.clear();for(let m of _)m?.deviceId&&n.set(m.deviceId,m);for(l(),a=(await this.subscribeDevices(v)).getReader();!i;){let{done:m,value:x}=await a.read();if(m||!x)break;for(let T of x){if(T.type==="removed"){n.delete(T.deviceId);continue}let R=T.device?.deviceId,E=this.nativeRosterTagDisposition(T.device??{});if(!E.keep){E.foreignTag&&d("[NativeIpcBridge] onDevicesChange dropped foreign-app device event",{sdkAppTag:this.appTag,foreignTag:E.foreignTag,deviceId:R??null}),R&&n.delete(R);continue}let U=this.normalizeDevice(T.device);U.deviceId&&n.set(U.deviceId,U);}l();}}catch(d){i||(console.error("[NativeIpcBridge] onDevicesChange stream failed; retrying subscription:",d),await u(1e3));}finally{if(a){try{await a.cancel();}catch{}a=null;}}},u$1=()=>{i=true,a&&(a.cancel(),a=null);};return s(),()=>u$1()}async subscribeDevices(e){if(this.usesCoordinationGateway())return this.fallback.subscribeDevices(e);if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("subscribeDevices",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for subscribeDevices");let i=`sub-${Math.random().toString(36).substring(2,11)}`,n=null,a=null,o=false,r=async()=>{if(!o&&(o=true,n&&(await Promise.resolve(n()),n=null),a)){try{await a();}catch{}a=null;}};return new ReadableStream({start:async c$1=>{d(`[NativeIpcBridge] subscribeDevices request start user_id=${e} request_id=${i}`),n=await this.listenIpc("rtc-device-events",l=>{if(o)return;let s=l.payload;if(s.requestId===i){if(s.type==="deviceEvents"){let u=Array.isArray(s.events)?s.events.length:0;c(`[NativeIpcBridge] subscribeDevices event batch request_id=${i} count=${u}`);try{c$1.enqueue(s.events);}catch{r();}}else if(s.type==="error"&&(console.warn(`[NativeIpcBridge] subscribeDevices stream error request_id=${i}: ${s.message}`),!o)){try{c$1.error(s.message);}catch{}r();}}}),a=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_device_subscription",{requestId:i,userId:e});}catch(l){try{c$1.error(l);}catch{}await r();}},cancel:async()=>{d(`[NativeIpcBridge] subscribeDevices request stop request_id=${i}`),await r();}})}return this.fallback.subscribeDevices(e)}async subscribeSessions(e){if(this.usesCoordinationGateway())return this.fallback.subscribeSessions(e);if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("subscribeSessions",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for subscribeSessions");let i=`sub-${Math.random().toString(36).substring(2,11)}`,n=await this.resolveLocalDeviceId()||e,a=null,o=null,r=false,c=async()=>{if(!r&&(r=true,a&&(await Promise.resolve(a()),a=null),o)){try{await o();}catch{}o=null;}};return new ReadableStream({start:async l=>{a=await this.listenIpc("rtc-session-events",s=>{if(r)return;let u=s.payload;if(u.requestId===i){if(u.type==="sessionEvents")try{l.enqueue(u.events);}catch{c();}else if(u.type==="error"&&!r){try{l.error(u.message);}catch{}c();}}}),o=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_session_subscription",{requestId:i,localDeviceId:n});}catch(s){try{l.error(s);}catch{}await c();}},cancel:async()=>{await c();}})}return this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,i=true,n=3e5,a){if(this.usesCoordinationGateway())return await this.syncCoordinationDeviceIdentity(),this.fallback.updatePresence(e,t,i,n,a);if(await this.shouldUseTauriSignaling())try{if(!await this.ensureNativeAuth("updatePresence",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for updatePresence");let r=this.resolveNativeSignalingUserId(),c=await this.resolveLocalDeviceId(),l=await this.resolveLocalDeviceName();await this.invokeIpc("update_rtc_presence",{userId:r,deviceName:l,ticket:t,metadata:this.withPresenceMetadata(a,c)});return}catch(o){console.warn("[NativeIpcBridge] update_rtc_presence failed:",o);}return this.fallback.updatePresence(e,t,i,n,a)}startAutoConnect(e,t){if(this.usesCoordinationGateway()){this.startGatewayAutoConnect(e,t).catch(i=>{console.warn("[NativeIpcBridge] staging gateway auto-connect failed:",i);});return}(async()=>{try{if(!await this.shouldUseTauriSignaling()){console.error("[NativeIpcBridge] startAutoConnect requires native Rust signaling; IPC unavailable");return}let i=await this.resolveLocalDeviceId()||t;await this.startAutoConnectOnce(e,i);}catch(i){console.warn("[NativeIpcBridge] startAutoConnect failed:",i);}})();}forceReconnectSnapshot(){if(this.usesCoordinationGateway()){console.info("[NativeIpcBridge] native Firebase reconnect snapshots are disabled in the staging gateway lane.");return}(async()=>{if(!await this.shouldUseTauriSignaling()){console.error("[NativeIpcBridge] forceReconnectSnapshot requires native Rust signaling; IPC unavailable");return}try{await this.invokeIpc("force_rtc_reconnect_snapshot");}catch(e){console.warn("[NativeIpcBridge] force_rtc_reconnect_snapshot failed:",e);}})();}startPresenceLoop(e,t,i,n,a){if(this.usesCoordinationGateway()){this.syncCoordinationDeviceIdentity().then(()=>this.fallback.startPresenceLoop(e,t,i,n,a));return}(async()=>{try{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] startPresenceLoop falling back to wasm signaling (Tauri IPC unavailable)"),this.fallback.startPresenceLoop(e,t,i,n,a);return}let o=await this.resolveLocalDeviceId(),r=this.shouldUseResolvedDeviceName(i)?await this.resolveLocalDeviceName():i.trim(),c=this.withPresenceMetadata(a,o);await this.startPresenceLoopOnce(e,t,r,n,c);}catch(o){console.warn("[NativeIpcBridge] startPresenceLoop failed:",o);}})();}async startAutoConnectOnce(e,t){if(this.usesCoordinationGateway()){await this.startGatewayAutoConnect(e,t);return}if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startAutoConnectOnce().");if(!await this.ensureNativeAuth("startAutoConnect",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startAutoConnect");let n=this.resolveNativeSignalingUserId(e);if(!n)throw new Error("Native auto-connect requires a runtime auth-scoped user id.");await this.invokeIpc("start_rtc_auto_connect",{userId:n,localDeviceId:t});}stopGatewayDesiredPeerRelay(){this.gatewayDesiredPeersCleanup?.(),this.gatewayDesiredPeersCleanup=null,this.gatewayDesiredPeerRevision=0,this.gatewayDesiredPeerSubmission=Promise.resolve();}async startGatewayAutoConnect(e,t){if(!await this.shouldUseTauriSignaling())throw new Error("[openrtc] Native IPC unavailable for staging gateway auto-connect.");if(!await this.ensureNativeAuth("startGatewayAutoConnect",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for staging gateway auto-connect");let n=this.resolveNativeSignalingUserId(e);if(!n)throw new Error("Staging gateway auto-connect requires an authenticated user id.");let a=await this.resolveLocalDeviceId()||t.trim();if(!a)throw new Error("Staging gateway auto-connect requires a local device id.");this.fallback.setCoordinationLocalDeviceId(a),this.stopGatewayDesiredPeerRelay(),await this.invokeIpc("start_rtc_external_auto_connect",{userId:n,localDeviceId:a}),this.gatewayDesiredPeersCleanup=this.fallback.onDevicesChange(o=>{let r=o.map(l=>({deviceId:String(l.deviceId??"").trim(),nodeId:typeof l.nodeId=="string"&&l.nodeId.trim()||null,ticket:typeof l.ticket=="string"&&l.ticket.trim()||null,online:l.online===true,sessionId:typeof l.sessionId=="string"&&l.sessionId.trim()||null,excludedPeers:Array.isArray(l.excludedPeers)?[...new Set(l.excludedPeers.map(s=>String(s??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(l=>l.deviceId.length>0).sort((l,s)=>l.deviceId.localeCompare(s.deviceId)),c=++this.gatewayDesiredPeerRevision;this.gatewayDesiredPeerSubmission=this.gatewayDesiredPeerSubmission.then(async()=>{await this.invokeIpc("submit_rtc_desired_peers",{revision:c,peersJson:JSON.stringify(r)});}).catch(l=>{console.warn("[NativeIpcBridge] failed to relay gateway desired peers to Rust:",{revision:c,error:l});});},a);}async startPresenceLoopOnce(e,t,i,n,a){if(this.usesCoordinationGateway()){await this.syncCoordinationDeviceIdentity(),await this.fallback.startPresenceLoop(e,t,i,n,a);return}if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startPresenceLoopOnce().");if(console.info("[NativeIpcBridge][presence][start-request]",{userId:e,localNodeId:t,deviceName:i,hasMetadata:typeof a=="string"&&a.trim().length>0,hasCompoundTicket:typeof n=="string"&&n.includes(".")}),!await this.ensureNativeAuth("startPresenceLoop",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startPresenceLoop");let r=this.resolveNativeSignalingUserId(e);if(!r)throw new Error("Native presence loop requires a runtime auth-scoped user id.");console.info("[NativeIpcBridge][presence][auth-ready]",{requestedUserId:e,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:r,localNodeId:t}),await this.invokeIpc("start_rtc_presence_loop",{userId:r,localNodeId:t,deviceName:i,ticket:n,metadata:a,apiKey:this.options.apiKey??null,spaceKey:this.resolveConfiguredSpaceKey()||null}),console.info("[NativeIpcBridge][presence][ipc-started]",{requestedUserId:e,effectiveUserId:r,localNodeId:t,deviceName:i});}shouldUseResolvedDeviceName(e){let t=e.trim();return t.length===0||t==="Unknown Device"||t==="Desktop Device"}async sendExplicitFilePath(e,t,i=""){if(d("[NativeIpcBridge] sendExplicitFilePath start",{connectionId:e,filePath:t,transferId:i||null,authMode:this.options.authMode}),await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFilePath"):d("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let n=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:i});return d("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:i||null,result:n}),n}return this.fallback.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){d("[NativeIpcBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:e.connection?.remoteNodeId??null,remoteNodeId:e.remoteNodeId??null,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size,authMode:this.options.authMode});let t=e.applicationCrypto??this.options.applicationCrypto;if(await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFileData"):d("[NativeIpcBridge] sendExplicitFileData using anonymous native path");let i=e.connectionId||e.connection?.deviceId||e.connection?.remoteNodeId||e.remoteNodeId||"";if(!i)throw new Error("sendExplicitFileData requires a settled peer identifier in native runtime");let n=new Uint8Array(await e.file.arrayBuffer());await this.invokeIpc("send_file_data",{connectionId:i,filename:e.file.name,data:Array.from(n),transferId:e.transferId}),d("[NativeIpcBridge] sendExplicitFileData completed",{connectionId:i,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size});return}return this.fallback.sendExplicitFileData({...e,applicationCrypto:t})}async getConnectionStates(){if(await this.canUseTauriIpc())try{this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionStates");let e=await this.invokeIpc("list_rtc_connection_states");return (Array.isArray(e)?e:[]).map(t=>w(t)).filter(t=>!!t)}catch(e){return D(e)?d("[NativeIpcBridge] native connection-state replay unavailable; continuing without replay. Install/register openrtc-tauri-plugin default permissions to enable it."):console.warn("[NativeIpcBridge] Failed to fetch native connection states:",e),[]}return []}async getConnectionState(e){let t=e.trim();if(!t||!await this.canUseTauriIpc())return null;try{return this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionState"),w(await this.invokeIpc("get_rtc_connection_state",{connectionId:t}))}catch(i){return console.warn("[NativeIpcBridge] Failed to fetch native connection state:",{connectionId:t,error:i}),null}}async onConnectionStateChange(e){let t=false,i=null,n=new Map,a=Date.now(),o=0,r=()=>{let s=i;s&&Promise.resolve(s());},c$1=async()=>{try{let s=await this.getConnectionStates();s.length>0&&(c("[NativeIpcBridge] replaying current native connection states",s.map(u=>({connectionId:u.connectionId,deviceId:u.deviceId??null,deviceIdHint:u.deviceIdHint??null,remoteNodeId:u.remoteNodeId??null,state:u.state,transportState:u.transportState??null,protocolState:u.protocolState??null,routable:u.routable??null}))),s.forEach(u=>e(u)));}catch(s){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",s);}},l=async s=>{let u$1=(n.get(s)??0)+1;n.set(s,u$1);let d=await this.getConnectionState(s);if(!d||t||n.get(s)!==u$1)return;if(["closed","failed","disconnected"].includes(String(d.state??"").trim().toLowerCase())){if(await u(g.CONNECTION_TERMINAL_CONFIRMATION_MS),t||n.get(s)!==u$1)return;d=await this.getConnectionState(s)??d;}!t&&n.get(s)===u$1&&e(d);};for(;!t&&Date.now()-a<=g.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(o+=1,!await this.canUseTauriIpc()){await u(this.nextConnectionEventRetryDelayMs(o));continue}return i=await this.listenIpc("connection-state-changed",s=>{let u=w(s?.payload);u&&(c("[NativeIpcBridge] connection-state-changed trigger",{connectionId:u.connectionId}),l(u.connectionId));}),await c$1(),()=>{t=true,r();}}return ()=>{t=true,r();}}async onIncomingNativeMessage(e){if(!await this.canUseTauriIpc())return ()=>{};let t=await this.listenIpc("iroh://message",i=>{if(i?.payload?.data&&i.payload.streamId==="main")try{let n=new Uint8Array(i.payload.data);if(n.length<2||n[0]!==0)return;let o=n.slice(1),r=new TextDecoder().decode(o),c=JSON.parse(r);e(i.payload.connectionId,i.payload.remoteNodeId??null,c);}catch{}});return typeof t=="function"?t:()=>{}}async getTransferHistory(e=50){return await this.canUseTauriIpc()?this.invokeIpc("get_transfer_history",{limit:e}):[]}async deleteTransferJob(e){await this.canUseTauriIpc()&&await this.invokeIpc("delete_transfer_job",{jobId:e});}};g.AUTH_REQUIRED_WAIT_MS=x.nativeIpc.authRequiredWaitMs,g.DEFAULT_BOUNDED_IPC_TIMEOUT_MS=x.nativeIpc.defaultBoundedCommandTimeoutMs,g.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=x.nativeIpc.connectionEventSubscribeWindowMs,g.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=x.nativeIpc.connectionEventRetryMinDelayMs,g.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=x.nativeIpc.connectionEventRetryMaxDelayMs,g.CONNECTION_TERMINAL_CONFIRMATION_MS=1500,g.TAURI_IPC_NEGATIVE_CACHE_MS=x.nativeIpc.tauriIpcNegativeCacheMs,g.NATIVE_STATUS_IPC_TIMEOUT_MS=2500;var M=g;var te=class extends G{constructor(e){let t=N(e.bridge,"IpcRuntimeAdapter");super(new M({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
2
+ export{Z as a,X as b,ee as c,O as d,ie as e,D as f,Q as g,te as h};
@@ -0,0 +1 @@
1
+ import {G,F}from'./chunk-F3P2RCH5.js';var n=class extends G{constructor(e){super(new F(e));}setWasmClient(e){this.unwrap().setWasmClient(e);}};export{n as a};