openrtc 1.0.14 → 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.
- package/dist/{DelegatingRuntimeAdapter-D_kGKQtW.d.ts → DelegatingRuntimeAdapter-K-B_ElEc.d.ts} +1 -1
- package/dist/{assembly-DisGbrdH.d.ts → assembly-DiR_2Qp7.d.ts} +2 -2
- package/dist/auth/index.js +1 -1
- package/dist/auth/internal.js +1 -1
- package/dist/{chunk-TOO3FUPK.js → chunk-B6ZCYM46.js} +1 -1
- package/dist/chunk-F3P2RCH5.js +2 -0
- package/dist/chunk-HBMXO563.js +2 -0
- package/dist/{chunk-R5P73PEG.js → chunk-IU57RAB3.js} +1 -1
- package/dist/{chunk-HFWOWDEH.js → chunk-JJWS2LYK.js} +1 -1
- package/dist/chunk-POUO36QG.js +2 -0
- package/dist/chunk-V64AKZHT.js +1 -0
- package/dist/{chunk-6J3QKQRS.js → chunk-VOLTY4MH.js} +1 -1
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/native.d.ts +5 -5
- package/dist/native.js +1 -1
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/runtime/WasmRuntimeAdapter.d.ts +2 -2
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +2 -2
- package/dist/runtime/index.d.ts +8 -8
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/tauri.d.ts +3 -3
- package/dist/runtime/tauri.js +1 -1
- package/dist/{spaceTokens-Dc1CsMQt.d.ts → spaceTokens-BjtMfh14.d.ts} +3 -3
- package/dist/{tauri-DSkrSuO-.d.ts → tauri-VwfPg-zt.d.ts} +2 -2
- package/dist/transport/index.d.ts +2 -2
- package/dist/{types-Cb_GFANp.d.ts → types-CC6PiV2m.d.ts} +12 -0
- package/dist/{types-BSJ8IyBq.d.ts → types-vbfYvAZu.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-JGBEYISL.js +0 -2
- package/dist/chunk-SVBFZRGV.js +0 -2
- package/dist/chunk-TW4HQLK6.js +0 -1
- package/dist/chunk-W5YFLH2U.js +0 -2
|
@@ -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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {c as c$1}from'./chunk-C7YN5MSV.js';import {getApps,initializeApp}from'firebase/app';import {getToken,initializeAppCheck,ReCaptchaEnterpriseProvider}from'firebase/app-check';import {getFunctions,connectFunctionsEmulator,httpsCallable}from'firebase/functions';import {browserLocalPersistence,inMemoryPersistence,browserPopupRedirectResolver,initializeAuth,getAuth,connectAuthEmulator,setPersistence,onIdTokenChanged,getIdToken,signInWithCustomToken,onAuthStateChanged,signInAnonymously,signInWithEmailAndPassword,createUserWithEmailAndPassword,signOut,deleteUser,updateProfile,GoogleAuthProvider,OAuthProvider,signInWithCredential,signInWithPopup,signInWithRedirect,getRedirectResult}from'firebase/auth';function D(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var L=new Set;function R(t,e){L.has(t)||(L.add(t),console.warn(e));}function oe(t){return /^pk_(live|test)_[0-9a-f]{40}$/.test(t)}async function je(t,e){let n=`${t}:${e}`,o=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i)).map(d=>d.toString(16).padStart(2,"0")).join("")}function S(t){let e=typeof t.apiKey=="string"?t.apiKey.trim():"";if(e)return oe(e)||R(`invalid-api-key:${e.slice(0,10)}`,"[pluto-rtc] The provided `apiKey` does not match the expected format (pk_live_... or pk_test_...). Create an app at https://api.openrtc.app/developer."),`app_${e.slice(-16)}`;throw new Error("[openrtc] `apiKey` is required. Create an app at https://api.openrtc.app/developer.")}function P(t){return t.authMode?t.authMode:("apiKey"in t&&typeof t.apiKey=="string"&&t.apiKey.trim().length>0&&typeof(t.spaceKey??t.space)=="string"&&(t.spaceKey??t.space).trim().length>0||R("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function ze(t){let e=typeof t.projectId=="string"?t.projectId.trim():"";return e||(R("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),y)}function H(t){return t.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Qe(t){let e="storagePrefix"in t&&typeof t.storagePrefix=="string"?H(t.storagePrefix):"";return e||H(S(t))||"default"}var ie={devicesPerUser:100,maxRooms:1e4,maxMembersPerRoom:250,maxPersonalDevices:25e3},Ve=ie;var ae=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],B={iceServers:ae},Ye={};var F=["iroh-relay","iroh","moq"];function se(t){return (Array.isArray(t.urls)?t.urls:[t.urls]).some(n=>typeof n=="string"&&(n.startsWith("turn:")||n.startsWith("turns:")))}function ce(t){let n=(Array.isArray(t.urls)?t.urls:[t.urls]).filter(r=>typeof r=="string"&&!r.startsWith("stun:"));return n.length===0?null:{...t,urls:Array.isArray(t.urls)?n:n[0]}}function I(t){if(t)return t.map(e=>ce(e)).filter(e=>e!==null)}function K(t,e){let n=new Set(["iroh-relay","iroh","moq"]);e&&n.add("webrtc");let r=(t??F).filter(o=>n.has(o));return r.length>0?r:[...F]}function Xe(t){return !!t?.transports?.webrtc}function Ze(t,e){let n=t?.transports?.webrtc||void 0;if(n)return t?.strictMode||n.privacyMode?{...n,iceServers:I(n.iceServers),iceTransportPolicy:"relay"}:n.iceTransportPolicy==="relay"&&!(Array.isArray(n.iceServers)&&n.iceServers.some(o=>se(o)))?(e?.("[Client] Overriding relay-only ICE policy to all because no TURN servers are configured"),{...n,iceTransportPolicy:"all"}):n}var le=/^[A-Za-z0-9._-]+$/,de="[redacted]";function q(t){let e;try{e=new URL(t);}catch{throw new Error("[OpenRTC] transports.moq.relayUrl must be a valid HTTPS URL.")}if(e.protocol!=="https:")throw new Error("[OpenRTC] transports.moq.relayUrl must use HTTPS/WebTransport.");if(e.hash)throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a fragment.");if(e.searchParams.has("jwt"))throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a jwt query parameter; use transports.moq.accessToken.");return e}function C(t){return q(t.trim()).toString()}function tt(t,e){let n=q(t.trim());if(e!==void 0){let r=e.trim();if(!r)throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");if(new TextEncoder().encode(r).byteLength>16384)throw new Error("[OpenRTC] transports.moq.accessToken exceeds the maximum supported size.");if(!le.test(r))throw new Error("[OpenRTC] transports.moq.accessToken must be a URL-safe JWT.");n.searchParams.append("jwt",r);}return n.toString()}function nt(t){try{let e=new URL(t);return e.search="",e.hash="",e.toString()}catch{return "invalid-moq-relay-url"}}function rt(t,e){let n=t instanceof Error?`${t.name}: ${t.message}`:String(t),r=e?.trim();return r?n.split(r).join(de):n}var ue=[...c$1];function A(t){let e=t.spaceKey??t.space;return {...t,...e!==void 0?{spaceKey:e}:{}}}function W(t){return {...t,iceServers:t.iceServers?t.iceServers.map(e=>({...e})):t.iceServers}}function pe(t){return {...t}}function me(t){return {...t}}function ge(t){if(t)return {iroh:typeof t.iroh=="object"?me(t.iroh):t.iroh,webrtc:typeof t.webrtc=="object"?W(t.webrtc):t.webrtc,ble:typeof t.ble=="object"?{...t.ble}:t.ble,moq:typeof t.moq=="object"?pe(t.moq):t.moq}}function fe(t){if(t.strictMode&&!t.transports&&(t.transports={iroh:{relayOnly:true}}),!!t.transports){if(t.transports.webrtc===true?t.transports.webrtc=W(B):t.transports.webrtc===false&&(t.transports.webrtc=void 0),t.transports.moq===true)throw new Error("[OpenRTC] transports.moq=true is ambiguous because no anonymous MoQ relay is available; provide transports.moq.relayUrl explicitly.");if(t.transports.moq===false)t.transports.moq=void 0;else if(t.transports.moq&&typeof t.transports.moq=="object"){let e=t.transports.moq,n=e.relayUrl?.trim(),r=e.accessToken;if(r!==void 0&&!r.trim())throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");t.transports.moq={...e,...n?{relayUrl:C(n)}:{},...r!==void 0?{accessToken:r.trim()}:{}};}t.transports.iroh===true?t.transports.iroh={}:t.transports.iroh===false&&(t.transports.iroh=void 0);}}function ye(t){if(!t.strictMode||!t.transports)return;let e=t.transports.iroh&&typeof t.transports.iroh=="object"?t.transports.iroh:{};t.transports.iroh={...e,relayOnly:true,relayTransportPolicy:e.relayTransportPolicy??"websocketRequired",localDiscovery:false,localDiscoveryMode:void 0},t.transports.ble=void 0;let n=t.transports.webrtc;n&&typeof n=="object"&&(t.transports.webrtc={...n,privacyMode:true,lanMode:false,iceServers:I(n.iceServers)??[],iceTransportPolicy:"relay"});let r=t.transports.moq;if(r&&typeof r=="object"){let o=r.relayUrl?.trim();if(!o)throw new Error("[OpenRTC] strictMode requires an explicit transports.moq.relayUrl.");t.transports.moq={...r,relayUrl:C(o)};}}function dt(t){let e=A(t),n=S(e),r=P(e),o={strictMode:false,disableIrohFallback:false,transportPriority:[...ue],...e,authMode:r,transports:ge(e.transports)};fe(o),ye(o),o.strictMode&&(o.transportPriority=K(e.transportPriority,!!o.transports?.webrtc));let i=G(o),a=(o.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:n,authMode:r,configuredPersistenceMode:i,options:o,roomCreationMode:a}}function G(t){let e=t.transports?.iroh;return t.endpointIdPersistence??t.nodeIdPersistence??(typeof e=="object"?e.persistenceMode:void 0)??"ephemeral"}function ut(t){return "options"in t&&"configuredPersistenceMode"in t?{apiKey:t.options.apiKey,authMode:P(t.options),projectId:t.options.projectId,storagePrefix:t.options.storagePrefix,nodeIdPersistence:t.configuredPersistenceMode}:{apiKey:t.apiKey,authMode:P(t),projectId:t.projectId,storagePrefix:t.storagePrefix,nodeIdPersistence:G(t)}}function pt(t,e){e&&(t.transports={...t.transports||{},...e});}var y="pluto-rtc-prod",he="https://openrtc-coordination-gateway.hargreaves-bryant.workers.dev",k={apiKey:"AIzaSyA62Krj-7ZYFT5xjrTUq7mXana41Ahj_mM",authDomain:"api.openrtc.app",projectId:y,storageBucket:"pluto-rtc-prod.firebasestorage.app",messagingSenderId:"607066575224",appId:"1:607066575224:web:ed3f51825ba228db92b88d",recaptchaSiteKey:"6LfGv2gtAAAAALFAuE_kpLYpNBpk2IsKiLIGdOGl"};function be(){let t=globalThis;if([t.__OPENRTC_FIRESTORE_EMULATOR_HOST__,t.__OPENRTC_RTDB_EMULATOR_HOST__].some(n=>typeof n=="string"&&n.trim().length>0))return true;try{let n=import.meta.env,r=String(n?.VITE_USE_EMULATORS??"").toLowerCase()==="true",o=n?.DEV===!0||String(n?.VITE_E2E??"").toLowerCase()==="true";return r&&o}catch{return false}}function ft(t){let e=A(t),r=(typeof e.projectId=="string"&&e.projectId.trim()?e.projectId.trim():void 0)??y,o=r===y&&!be();return {...e,projectId:r,coordinationGateway:e.coordinationGateway??(o?{endpoint:he,environment:"production"}:void 0)}}function j(t){return new Promise(e=>setTimeout(e,t))}function ht(t){let e=new Uint8Array(t.byteLength);return e.set(t),e}function bt(t){let e=t.reduce((o,i)=>o+i.byteLength,0),n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n}function Tt(t,e,n){let r=e*Math.pow(2,Math.max(0,t-1));return Math.min(n,r)}function Pt(t){try{let e=t;return !!e&&!!e.send&&typeof e.send.getWriter=="function"&&!!e.recv&&typeof e.recv.getReader=="function"}catch{return false}}function vt(t,e,n){let r=t;if(!r)return null;try{let o=r.send,i=r.recv;if(!o||typeof o.getWriter!="function"||!i||typeof i.getReader!="function")return null;let a=typeof r.endpoint_id=="string"&&r.endpoint_id.trim().length>0?r.endpoint_id:e,l=Number.isSafeInteger(r.transport_stable_id)&&Number(r.transport_stable_id)>0?Number(r.transport_stable_id):void 0,d=Number.isSafeInteger(n)&&Number(n)>0?Number(n):void 0;if(l!==void 0&&d!==void 0&&l!==d)return null;let s=l??d;return {send:o,recv:i,endpoint_id:a,...s?{transport_stable_id:s}:{}}}catch{return null}}function Rt(t,e){let n={send:t.send,recv:e,endpoint_id:typeof t.endpoint_id=="string"?t.endpoint_id:"",...Number.isSafeInteger(t.transport_stable_id)&&Number(t.transport_stable_id)>0?{transport_stable_id:Number(t.transport_stable_id)}:{}};return t?.applicationCryptoWrapped===true&&(n.applicationCryptoWrapped=true),n}async function St(t,e){if(!t)return false;try{let n=t.send?.getWriter?.();if(n)try{await n.close();}catch{}finally{try{n.releaseLock();}catch{}}}catch{}try{let n=t.recv?.getReader?.();if(n)try{await n.cancel(e);}catch{}finally{try{n.releaseLock();}catch{}}}catch{}return true}function It(t,e,n={}){let r=n.context??"prependBytesToReader",o=n.traceId,i=e.byteLength===0,a=n.pendingRead??null,l=s=>n.release?.(s),d=(s,p)=>n.log?.(s,p);return new ReadableStream({async pull(s){if(!i){i=true,s.enqueue(e);return}if(a){let u=a;a=null;let m;try{m=await u;}catch(f){s.error(f),l("pending-read-error"),d("prepend-bytes:pending-read-error",{context:r,traceId:o||null,error:f?.message||String(f)});return}if(m.done){s.close(),l("pending-done");return}m.value&&s.enqueue(m.value);return}let p;try{p=await t.read();}catch(u){s.error(u),l("read-error"),d("prepend-bytes:read-error",{context:r,traceId:o||null,error:u?.message||String(u)});return}let{done:v,value:T}=p;if(v){s.close(),l("done");return}T&&s.enqueue(T);},async cancel(s){l("cancel");}})}async function Ct(t,e){let n=t.read(),r=e-Date.now();if(r<=0)return {status:"timeout",pendingRead:n};let o=Symbol("probe-timeout"),i,a=new Promise(l=>{i=setTimeout(()=>l(o),r);});try{let l=await Promise.race([n,a]);if(l===o)return {status:"timeout",pendingRead:n};let{done:d,value:s}=l;return d?{status:"done"}:{status:"data",value:s&&s.byteLength>0?new Uint8Array(s):new Uint8Array(0)}}finally{i&&clearTimeout(i);}}function z(t,e,n){let r;return new Promise((o,i)=>{r=setTimeout(()=>{if(r=void 0,typeof n=="function"){i(n());return}let a=n?`${n} timed out`:"timeout";i(new Error(`${a} after ${e}ms`));},e),t.then(a=>{r!==void 0&&clearTimeout(r),o(a);},a=>{r!==void 0&&clearTimeout(r),i(a);});})}var X="pluto-rtc-auth";function Be(t){let e=typeof import.meta<"u"?import.meta.env:null,n=String(e?.VITE_OPENRTC_APP_CHECK_SITE_KEY??globalThis.__OPENRTC_APP_CHECK_SITE_KEY__??k.recaptchaSiteKey??"").trim(),r=String(e?.VITE_OPENRTC_APP_CHECK_MODE??globalThis.__OPENRTC_APP_CHECK_MODE__??"monitor").trim().toLowerCase();if(!n)return r==="enforce"&&console.error("[PLUTO-RTC][APP-CHECK] Enforcement requested without VITE_OPENRTC_APP_CHECK_SITE_KEY"),null;let o=String(e?.VITE_OPENRTC_APP_CHECK_DEBUG_TOKEN??"").trim();o&&e?.DEV!==true?console.error("[PLUTO-RTC][APP-CHECK] Debug tokens are allowed only in development builds"):o&&typeof self<"u"&&(self.FIREBASE_APPCHECK_DEBUG_TOKEN=o==="true"?true:o);try{return initializeAppCheck(t,{provider:new ReCaptchaEnterpriseProvider(n),isTokenAutoRefreshEnabled:!0})}catch(i){let a=i instanceof Error?i.message:String(i);return a.toLowerCase().includes("already exists")||console.warn("[PLUTO-RTC][APP-CHECK] Initialization failed",{message:a}),null}}var M=null;function Fe(){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 c(t,e){if(Fe()){if(typeof e>"u"){console.log(t);return}console.log(t,e);}}function qt(t){M=t;}function Ke(){return D()}function ne(){return typeof navigator>"u"?false:/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||"")}function Z(){return Ke()&&ne()}function g(t,e,n){return z(t,e,()=>new Error(`${n} timeout after ${e}ms`))}function ee(t){let e="0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._",n=new Uint8Array(t);window.crypto.getRandomValues(n);let r="";for(let o=0;o<t;o+=1)r+=e[n[o]%e.length];return r}async function te(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var E=class{constructor(){this.redirectResultPromise=null;this.redirectResultConsumed=false;this.lastRelayedToken=null;this.lastRelayedRefreshToken=null;this.desktopTokenRefreshIntervalId=null;let e=getApps().find(o=>o.name===X);this.app=e||initializeApp(k,X),this.appCheck=Be(this.app);let n=ne(),r=Z();if(n)try{let o=r?{persistence:[browserLocalPersistence,inMemoryPersistence]}:{persistence:[browserLocalPersistence,inMemoryPersistence],popupRedirectResolver:browserPopupRedirectResolver};this.auth=initializeAuth(this.app,o),c("[PLUTO-RTC][AUTH-HOST] Using mobile-safe Firebase auth initialization",{appName:this.app.name,persistence:"browserLocalPersistence->inMemoryPersistence",redirectResolver:r?"disabled-for-tauri-mobile":"browserPopupRedirectResolver",tauriMobile:r});}catch{this.auth=getAuth(this.app),console.warn("[PLUTO-RTC][AUTH-HOST] Mobile-safe auth initialization unavailable; falling back to default getAuth");}else this.auth=getAuth(this.app);this.functions=getFunctions(this.app);try{let o=typeof globalThis<"u"?String(globalThis.__OPENRTC_AUTH_EMULATOR_HOST__??"").trim():"",i=typeof globalThis<"u"?String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim():"",a=typeof import.meta<"u"?import.meta.env:null;if(!!o||!!i||!!a&&String(a.VITE_USE_EMULATORS)==="true"&&(a.DEV||String(a.VITE_E2E)==="true")){let d=String(a?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",[s,p]=o.split(":"),[v,T]=i.split(":"),u=(s??"").trim()||d,m=(v??"").trim()||d,f=Number(p??a?.VITE_OPENRTC_AUTH_EMULATOR_PORT??9100),re=Number(T??a?.VITE_OPENRTC_FUNCTIONS_EMULATOR_PORT??5002);try{connectAuthEmulator(this.auth,`http://${u}:${f}`,{disableWarnings:!0});}catch{}try{connectFunctionsEmulator(this.functions,m,re);}catch{}}}catch{}n?this.persistenceReady=Promise.resolve():this.persistenceReady=setPersistence(this.auth,browserLocalPersistence).catch(o=>{console.warn("[PLUTO-RTC][AUTH-HOST] Failed to set auth persistence",{message:o?.message});}),c("[PLUTO-RTC][AUTH-HOST] Initialized auth host",{appName:this.app.name,mobileSafeAuth:n}),onIdTokenChanged(this.auth,o=>{c("[PLUTO-RTC][AUTH-HOST] Firebase ID token changed",{hasUser:!!o,uid:o?.uid,providerDataCount:o?.providerData?.length||0}),this.syncDesktopAuthToken(o);}),this.desktopTokenRefreshIntervalId||(this.desktopTokenRefreshIntervalId=setInterval(()=>{this.syncDesktopAuthToken(this.auth.currentUser,true);},600*1e3));}async syncDesktopAuthToken(e,n=false){if(!M)return;let r=e?await getIdToken(e,n).catch(()=>null):null,o=e?e.refreshToken??null:null;if(r===this.lastRelayedToken&&o===this.lastRelayedRefreshToken)return;this.lastRelayedToken=r,this.lastRelayedRefreshToken=o;let i=await Promise.allSettled([Promise.resolve(M({authToken:r,refreshToken:o}))]);i[0]?.status==="rejected"&&console.warn("[PLUTO-RTC][AUTH-HOST] Failed to relay auth token to desktop backend",{message:i[0].reason?.message});}getApp(){return this.app}async getAppCheckToken(e=false){if(!this.appCheck)return null;try{return (await getToken(this.appCheck,e)).token?.trim()||null}catch(n){let r=n instanceof Error?n.message:String(n);return console.warn("[PLUTO-RTC][APP-CHECK] Token acquisition failed",{message:r}),null}}getCurrentUser(){return this.auth.currentUser}getAuth(){return this.auth}onAuthStateChanged(e){return c("[PLUTO-RTC][AUTH-HOST] onAuthStateChanged listener registered (via onIdTokenChanged)"),onIdTokenChanged(this.auth,e)}onIdTokenChanged(e){return c("[PLUTO-RTC][AUTH-HOST] onIdTokenChanged listener registered"),onIdTokenChanged(this.auth,e)}async getIdToken(e){return this.auth.currentUser?getIdToken(this.auth.currentUser,e?.forceRefresh??true):null}async checkForSSOToken(){if(typeof window>"u")return;let e=new URLSearchParams(window.location.search),n=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash),r=e.get("token")||n.get("token")||(e.get("custom_token")==="true"||n.get("custom_token")==="true"?e.get("id_token")||n.get("id_token"):null);if(r)try{await this.persistenceReady,await signInWithCustomToken(this.auth,r),window.history.replaceState({},document.title,window.location.pathname);}catch(o){console.error("[PLUTO-RTC][AUTH-HOST] SSO sign-in failed:",o);}}async signInWithCustomTokenValue(e){return await this.persistenceReady,(await signInWithCustomToken(this.auth,e)).user}async signInWithPluto(e){if(typeof window>"u")throw new Error("Pluto SSO requires a browser environment.");let n=e?.redirectUri||window.location.href,r=e?.authorizeBaseUrl||"https://pluto.openrtc.app/sso/authorize",o=new URL(r);o.searchParams.set("redirect_uri",n),window.location.assign(o.toString());}async waitForAuth(){if(await this.persistenceReady,!this.auth.currentUser)return new Promise(e=>{let n=onAuthStateChanged(this.auth,r=>{r&&(n(),e());});})}async signInAnonymously(){await signInAnonymously(this.auth);}async signIn(e,n){return (await signInWithEmailAndPassword(this.auth,e,n)).user}async signUp(e,n){return (await createUserWithEmailAndPassword(this.auth,e,n)).user}async signOut(){await signOut(this.auth);}async deleteAccount(){if(!this.auth.currentUser)throw new Error("No user signed in");await deleteUser(this.auth.currentUser);}async signInWithCredential(e){let n=Date.now();if(c("[PLUTO-RTC][AUTH-HOST] signInWithCredential start",{callbackId:e.callbackId,provider:e.provider,hasIdToken:!!e.idToken,hasAccessToken:!!e.accessToken,hasNonce:!!e.nonce}),e.isCustomToken){c("[PLUTO-RTC][AUTH-HOST] signInWithCredential: custom token detected, using signInWithCustomToken");try{if(Z())c("[PLUTO-RTC][AUTH-HOST] Skipping authStateReady before custom token sign-in on Tauri mobile",{callbackId:e.callbackId});else {c("[PLUTO-RTC][AUTH-HOST] Awaiting authStateReady...");try{await g(this.auth.authStateReady(),5e3,"authStateReady"),c("[PLUTO-RTC][AUTH-HOST] Auth state ready, signing in with custom token...");}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] authStateReady did not resolve in time; continuing custom token sign-in",{callbackId:e.callbackId,message:a?.message});}}let i;try{i=await g(signInWithCustomToken(this.auth,e.idToken),25e3,"signInWithCustomToken (custom token path)");}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] First custom token sign-in attempt failed; retrying once",{callbackId:e.callbackId,message:a?.message,code:a?.code}),await j(250),i=await g(signInWithCustomToken(this.auth,e.idToken),25e3,"signInWithCustomToken (custom token path retry)");}if(c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken success",{callbackId:e.callbackId,provider:e.provider,uid:i.user?.uid,elapsedMs:Date.now()-n}),i.user&&(e.displayName||e.photoURL))try{await updateProfile(i.user,{displayName:e.displayName||i.user.displayName||void 0,photoURL:e.photoURL||i.user.photoURL||void 0});}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] Failed to update custom-token user profile",{callbackId:e.callbackId,message:a?.message});}return i.user}catch(o){throw console.error("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken failed",{callbackId:e.callbackId,error:o?.message,code:o?.code,stack:o?.stack,elapsedMs:Date.now()-n}),o}}let r;e.provider==="google"?r=GoogleAuthProvider.credential(e.idToken,e.accessToken):r=new OAuthProvider("apple.com").credential({idToken:e.idToken,rawNonce:e.nonce,accessToken:e.accessToken});try{let o=await g(signInWithCredential(this.auth,r),1e4,"firebase signInWithCredential");return c("[PLUTO-RTC][AUTH-HOST] signInWithCredential success",{callbackId:e.callbackId,provider:e.provider,uid:o.user?.uid,elapsedMs:Date.now()-n}),o.user}catch(o){console.warn("[PLUTO-RTC][AUTH-HOST] signInWithCredential primary path failed; trying custom token fallback",{callbackId:e.callbackId,provider:e.provider,elapsedMs:Date.now()-n,code:o?.code,message:o?.message});let i=await g(this.mintSessionTokenFromProviderToken(e),15e3,"mintSessionTokenFromProviderToken"),a=await g(signInWithCustomToken(this.auth,i),15e3,"signInWithCustomToken");return c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken fallback success",{callbackId:e.callbackId,provider:e.provider,uid:a.user?.uid,elapsedMs:Date.now()-n}),a.user}}async mintSessionTokenFromProviderToken(e){let n=httpsCallable(this.functions,"mintSessionToken");c("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request start",{provider:e.provider,hasIdToken:!!e.idToken,hasNonce:!!e.nonce});let o=(await n({provider:e.provider,idToken:e.idToken,nonce:e.nonce})).data?.token;if(!o)throw new Error("mintSessionToken did not return a token for provider exchange");return c("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request success",{provider:e.provider}),o}async signInWithPopup(e){if(e==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"});let a=await signInWithPopup(this.auth,i);return {idToken:await getIdToken(a.user,true),refreshToken:a.user.refreshToken}}let n=new OAuthProvider("apple.com");n.addScope("email"),n.addScope("name");let r=ee(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",r),n.setCustomParameters({nonce:await te(r)});let o=await signInWithPopup(this.auth,n);return {idToken:await getIdToken(o.user,true),refreshToken:o.user.refreshToken}}async signInWithRedirect(e,n){if(e==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"}),await signInWithRedirect(this.auth,i);return}let r=new OAuthProvider("apple.com");r.addScope("email"),r.addScope("name");let o=n?.nonce||ee(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",o),r.setCustomParameters({nonce:await te(o)}),await signInWithRedirect(this.auth,r);}async consumeRedirectResult(){return this.redirectResultConsumed?(c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult skipped (already consumed)"),null):this.redirectResultPromise?this.redirectResultPromise:(this.redirectResultPromise=(async()=>{try{c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult start");let e=await getRedirectResult(this.auth);if(!e)return c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult: no redirect result"),{fromRedirect:!1,user:null};this.redirectResultConsumed=!0;let n=await getIdToken(e.user,!0).catch(()=>null),r=e.providerId||e.user.providerData?.[0]?.providerId||null;return c("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult success",{uid:e.user.uid,providerId:r,hasIdToken:!!n}),{fromRedirect:!0,user:e.user,providerId:r,idToken:n}}finally{this.redirectResultPromise=null;}})(),this.redirectResultPromise)}async startGoogleSignIn(){await this.signInWithRedirect("google");}async startAppleSignIn(){await this.signInWithRedirect("apple");}async mintSessionToken(){let r=(await httpsCallable(this.functions,"mintSessionToken")()).data;if(!r?.token)throw new Error("mintSessionToken did not return a token");return r.token}},x=null;function qe(){return x||(x=new E),x}var Wt=new Proxy({},{get(t,e,n){let r=qe(),o=r[e];return typeof o=="function"?o.bind(r):o}});
|
|
2
|
+
export{Rt as A,St as B,It as C,Ct as D,z as E,qt as F,qe as G,Wt as H,je as a,S as b,P as c,ze as d,Qe as e,Ve as f,ae as g,B as h,Ye as i,Xe as j,Ze as k,tt as l,nt as m,rt as n,A as o,dt as p,ut as q,pt as r,ft as s,D as t,j as u,ht as v,bt as w,Tt as x,Pt as y,vt as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {g,h}from'./chunk-
|
|
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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {o,G}from'./chunk-
|
|
1
|
+
import {o,G}from'./chunk-HBMXO563.js';function x(t){let i=o({...t});if("auth"in t&&!t.authMode){let n=t.auth;i.authMode=n==="none"?"anonymous":n;}if("identity"in t){let n=t.identity,s=n==="temporary"?"ephemeral":n;!t.deviceIdPersistence&&!t.nodeIdPersistence&&(i.deviceIdPersistence=s),!t.endpointIdPersistence&&!t.nodeIdPersistence&&(i.endpointIdPersistence=s);}return "namespace"in t&&!t.storagePrefix&&(i.storagePrefix=t.namespace),"privacy"in t&&t.strictMode===void 0&&(i.strictMode=!!t.privacy),i}function A(t,i){let n=t.runtime,s=Object.create(n),r=async e=>{if(typeof e!="string")return e;let a=(await n.listDevices()).find(l=>l.deviceId===e);if(!a)throw new Error(`OpenRTC device '${e}' is not currently discoverable.`);return a},c=async e=>({...e,localDeviceId:e?.localDeviceId??await n.getLocalDeviceId()??""}),m=async e=>{let{device:o,scope:a,...l}=e,P=l.deviceId??(typeof o=="string"?o:o?.deviceId)??null,v=l.ticket??(typeof o=="string"?void 0:o?.ticket);P&&!v&&(v=(await r(P).catch(()=>null))?.ticket);let C={...l,scope:a??"session"};return P&&(C.deviceId=P),v&&(C.ticket=v),C},u={list:()=>n.listDevices(),startSession:(e={})=>n.startManagedSession({...e,platform:e.platform??i}),stopSession:e=>n.stopManagedSession(e),listWithStatus:()=>n.listDevicesWithStatus(),watch:e=>n.watchDevices(e),watchWithStatus:e=>n.watchDevicesWithStatus(e),connect:async(e,o)=>n.connectDevice(await r(e),await c(o)),connectWithRetry:async(e,o,a)=>n.connectDeviceWithRetry(await r(e),o,a),disconnect:e=>n.disconnectDevice(e),update:(e,o)=>n.updateDevice(e,o),delete:e=>n.deleteDevice(e),localId:()=>n.getLocalDeviceId(),localInfo:()=>n.getLocalDeviceInfo(),localProfile:e=>n.getLocalDeviceProfile(e),updateLocalName:e=>n.updateLocalDeviceName(e)},d={watch:e=>n.watchPeerStates(e),watchLifecycle:e=>n.watchPeerLifecycle(e),get:e=>n.getPeerState(e),listConnected:()=>n.listConnectedPeers(),connect:e=>n.connectPeer(e),disconnect:(e,o)=>n.disconnectPeer(e,o),forceDisconnect:e=>n.forceDisconnectPeer(e),session:e=>n.getPeerSession(e),sessions:()=>n.listPeerSessions(),waitConnected:(e,o)=>n.waitForConnectedPeer(e,o),readiness:(e,o)=>n.getPeerReadiness(e,o),health:e=>n.getPeerHealth(e),identity:e=>n.resolvePeerIdentity(e),addScope:(e,o)=>n.addPeerScope(e,o),releaseScope:(e,o)=>n.releasePeerScope(e,o),scopes:e=>n.getPeerScopes(e),refresh:()=>n.refreshPeerSnapshot()},g={register:e=>n.registerChannel(e),unregister:e=>n.unregisterChannel(e),list:()=>n.listChannels(),openBi:(e,o,a)=>n.openPeerBi(e,{...a,channelId:o}),openUni:(e,o,a)=>n.openPeerUni(e,{...a,channelId:o}),onIncoming:e=>n.onIncomingStream(e),onIncomingChannel:(e,o)=>n.onIncomingChannelStream(e,a=>{if(a.channel)return o(a)}),connect:async e=>n.connectScopedChannel(await m(e)),connectScoped:e=>n.connectScopedChannel(e)},p={create:e=>n.createRoom(e),join:(e,o)=>n.joinRoom(e,o),leave:e=>n.leaveRoom(e),watch:(e,o)=>n.watchRoom(e,o),members:e=>n.getRoomMembers(e)},R={raw:()=>n.getInvite(),share:e=>n.getTicketWithToken("share",e?.maxConnections??1),grant:(e,o)=>n.getTicketWithToken(e,o?.maxConnections??0),revoke:e=>n.revokeTokensByScope(e)},h={status:()=>n.getRuntimeStatus(),policy:()=>n.getRuntimePolicy(),capabilities:()=>n.getRuntimeCapabilities(),capabilityProfile:()=>n.getCapabilityProfile(),connectionStates:()=>n.getConnectionStates(),onConnectionStateChange:e=>n.onConnectionStateChange(e),connections:()=>n.getConnections(),applicationReadyConnections:e=>n.getApplicationReadyConnections(e),onConnection:e=>n.onConnection(e),onDisconnection:e=>n.onDisconnection(e),onConnectionEvent:e=>n.onConnectionEvent(e),forceReconnectSnapshot:()=>n.forceReconnectSnapshot(),peerReconciliation:()=>n.getPeerReconciliationStats()},I={runtime:n,assembly:t,nodeId:()=>n.getNodeId(),nodeIdFromTicket:e=>n.getNodeIdFromTicket(e),endpointTicket:()=>n.getEndpointTicket(),connectRaw:e=>n.connectRaw(e),openBi:e=>n.openBi(e),openUni:e=>n.openUni(e),isConnected:e=>n.isConnected(e),disconnectNode:e=>n.disconnectNode(e),setAutoConnectExcluded:(e,o)=>n.setAutoConnectExcluded(e,o),notifyNetworkChange:e=>n.notifyNetworkChange(e)};return Object.defineProperties(s,{devices:{get:()=>u,enumerable:true},peers:{get:()=>d,enumerable:true},channels:{get:()=>g,enumerable:true},rooms:{get:()=>p,enumerable:true},tickets:{get:()=>R,enumerable:true},diagnostics:{get:()=>h,enumerable:true},advanced:{get:()=>I,enumerable:true},setAuth:{value:e=>t.setAuthContext(e),enumerable:true,writable:true,configurable:true},setAuthContext:{value:e=>t.setAuthContext(e),enumerable:true,writable:true,configurable:true},syncPlutoAuth:{value:e=>t.syncPlutoAuth(e),enumerable:true,writable:true,configurable:true},bindPlutoAuthHost:{value:()=>t.bindPlutoAuthHost(),enumerable:true,writable:true,configurable:true},signIn:{value:()=>t.signInWithPluto(),enumerable:true,writable:true,configurable:true},signOut:{value:()=>t.signOut(),enumerable:true,writable:true,configurable:true},runtime:{get:()=>n,enumerable:false},_assembly:{get:()=>t,enumerable:false}}),s}var k="https://api.openrtc.app";async function E(t,i,n){let s=t.replace(/\/$/,""),r=await fetch(`${s}/v1/spaces/${encodeURIComponent(n)}/scoped-auth`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:"{}"}),c=await r.json().catch(()=>({}));if(!r.ok){let m=typeof c?.error=="string"?c.error:`enableSpaceAuth failed (${r.status})`;throw new Error(m)}return c}async function L(t,i,n){let s=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify(n)}),r=await s.json().catch(()=>({}));if(!s.ok){let c=typeof r?.error=="string"?r.error:`mintSpaceToken failed (${s.status})`;throw new Error(c)}if(typeof r?.token!="string"||!r.token.trim())throw new Error("mintSpaceToken response missing token");return r}function b(t){let i=t.apiKey.trim(),n=(t.spaceKey??t.space??"").trim(),s=f(t.sandboxAppId),r=(t.endpointUrl??k).replace(/\/$/,""),c=t.memberIdStorageKey??`openrtc:space-member:${n}${s?`:sandbox:${s}`:""}`;return async()=>{if(!i||!n)throw new Error("spaceToken requires apiKey and space");let m=null;typeof sessionStorage<"u"?(m=sessionStorage.getItem(c),m||(m=globalThis.crypto?.randomUUID?.()??`member-${Date.now()}`,sessionStorage.setItem(c,m))):m=`member-${Date.now()}`;let u=await G().getAppCheckToken(),d=await fetch(`${r}/v1SpacePublicTokens`,{method:"POST",headers:{"Content-Type":"application/json",...u?{"X-Firebase-AppCheck":u}:{}},body:JSON.stringify({apiKey:i,spaceKey:n,memberId:m,...s?{sandboxAppId:s}:{}})}),{text:g,payload:p}=await w(d);if(!d.ok){let h=typeof p?.error=="string"?p.error:g.trim()?g.trim().slice(0,240):`public space token mint failed (${d.status})`;throw new Error(h)}let R=typeof p?.token=="string"?p.token.trim():"";if(!R)throw new Error("public space token response missing token");return {customToken:R}}}function O(t){if(!t.trim())return {};try{let i=JSON.parse(t);return i&&typeof i=="object"?i:{}}catch{return {}}}async function w(t){let i=t.text;if(typeof i=="function"){let s=await i.call(t).catch(()=>"");return {text:s,payload:O(s)}}let n=await t.json().catch(()=>({}));return {text:JSON.stringify(n),payload:n&&typeof n=="object"?n:{}}}function f(t){let i=t?.trim().toLowerCase()??"";if(!i)return "";if(!/^[a-z0-9][a-z0-9-]{0,47}$/.test(i))throw new Error("sandboxAppId must be 1-48 lowercase letters, numbers, or dashes.");return i}function U(t,i){let n=t.trim(),s=f(i);return s?`${n}::sandbox::${s}`:n}var W=b,$=b;
|
|
2
2
|
export{x as a,A as b,E as c,L as d,b as e,U as f,W as g,$ as h};
|