openrtc 0.2.1 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -0
- package/dist/{DelegatingRuntimeAdapter-BxOcVIx_.d.ts → DelegatingRuntimeAdapter-By7pziBs.d.ts} +15 -15
- package/dist/IEngineBridge-C7OT2CRv.d.ts +10 -0
- package/dist/{IpcRuntimeAdapter-U5AEH0jn.d.ts → IpcRuntimeAdapter-DymXAsNU.d.ts} +2 -2
- package/dist/auth/index.js +1 -1
- package/dist/auth/internal.js +1 -1
- package/dist/chunk-A2ENDDFR.js +2 -0
- package/dist/chunk-CK6WQV7J.js +1 -0
- package/dist/{chunk-7DN33VUQ.js → chunk-EGEA3GU2.js} +1 -1
- package/dist/chunk-KZ3KWQTO.js +1 -0
- package/dist/chunk-MA2JFAV7.js +2 -0
- package/dist/chunk-OCNLQID3.js +1 -0
- package/dist/chunk-VIPNH2BE.js +3 -0
- package/dist/device-status-nkXepu97.d.ts +560 -0
- package/dist/{framing-lxzHEuSr.d.ts → framing-BUtu0oZK.d.ts} +19 -559
- package/dist/index.d.ts +11 -7
- package/dist/index.js +2 -2
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -2
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/device-status.d.ts +3 -0
- package/dist/runtime/device-status.js +1 -0
- package/dist/runtime/index.d.ts +86 -83
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/tauri.d.ts +4 -3
- package/dist/runtime/tauri.js +1 -1
- package/dist/transport/index.d.ts +1 -1
- package/dist/{types-D0fRvUbN.d.ts → types-CzIpGV9x.d.ts} +87 -5
- package/package.json +11 -8
- package/dist/chunk-FQETZQPW.js +0 -2
- package/dist/chunk-IUHUYHNZ.js +0 -1
- package/dist/chunk-UBEE42VU.js +0 -2
- package/dist/chunk-UPO23UMZ.js +0 -3
- package/dist/chunk-WNJE3MJF.js +0 -1
- package/env/index.d.ts +0 -64
- package/env/index.mjs +0 -230
package/README.md
CHANGED
|
@@ -115,10 +115,30 @@ The recommended TypeScript extension path is:
|
|
|
115
115
|
This keeps the runtime responsible for peer/session establishment while leaving
|
|
116
116
|
full control of channel/message specifics to the developer.
|
|
117
117
|
|
|
118
|
+
Register a `RuntimeChannelDescriptor` with `client.channels.register(...)` and
|
|
119
|
+
install one process-level `client.channels.onIncomingChannel(...)` handler when
|
|
120
|
+
the protocol needs explicit readiness, routing, or framing metadata. This is an
|
|
121
|
+
application protocol extension. It does not replace the incoming router or
|
|
122
|
+
grant authority over admission, peer scopes, dialing, retry, transport
|
|
123
|
+
promotion, recovery, or settlement.
|
|
124
|
+
|
|
125
|
+
`OpenRTCClient` still inherits `RuntimeClient` compatibility methods, and
|
|
126
|
+
`openrtc/runtime`, `client.peers.addScope()` / `releaseScope()`, and
|
|
127
|
+
`client.advanced` expose authority-capable manual surfaces. They are not the
|
|
128
|
+
recommended extension model and must not be used to build a parallel lifecycle.
|
|
129
|
+
Their narrowing is future-version work.
|
|
130
|
+
|
|
118
131
|
Advanced custom ALPN protocol plugins are a Rust-first/native-first feature.
|
|
119
132
|
Browser parity is guaranteed at the connected-peer stream layer, not at the
|
|
120
133
|
full ALPN plugin layer.
|
|
121
134
|
|
|
135
|
+
For applications that want a reusable file protocol without making it part of
|
|
136
|
+
the core runtime, install `openrtc-file-transfer`. It implements versioned,
|
|
137
|
+
bounded file framing, acknowledgement, progress, cancellation, optional
|
|
138
|
+
integrity verification, and streaming receive sinks over `client.channels`.
|
|
139
|
+
Filesystem destinations, persistent queues, history, acceptance prompts, and
|
|
140
|
+
product policy remain consumer-owned.
|
|
141
|
+
|
|
122
142
|
## Main Surfaces
|
|
123
143
|
|
|
124
144
|
### Root Package
|
|
@@ -149,11 +169,40 @@ auto-connect, and connection state to one `openrtc::client::Client`. Do not use
|
|
|
149
169
|
browser/WASM runtime for a prototype; that path bypasses the native Rust runtime
|
|
150
170
|
and can hide native lifecycle/presence issues from tests.
|
|
151
171
|
|
|
172
|
+
Mobile hosts should forward connectivity-restored callbacks through
|
|
173
|
+
`client.advanced.notifyNetworkChange(reason)`. The Tauri plugin passes this hint
|
|
174
|
+
to the existing Iroh endpoint so it can reconsider relay and direct paths; it
|
|
175
|
+
does not create a second OpenRTC dial or retry loop.
|
|
176
|
+
|
|
152
177
|
## Auth Model
|
|
153
178
|
- `anonymous`: no Pluto auth required
|
|
154
179
|
- `required`: Pluto auth required; the SDK may initiate Pluto SSO
|
|
155
180
|
- `external`: Pluto auth still required, but the host app acquires it and injects it into the runtime
|
|
156
181
|
|
|
182
|
+
## Security Boundary
|
|
183
|
+
|
|
184
|
+
Iroh authenticates endpoint keys and encrypts transport traffic. OpenRTC's
|
|
185
|
+
managed avenues add scoped session-token admission and application payload
|
|
186
|
+
encryption. These protections are cumulative: transport connectivity alone is
|
|
187
|
+
not permission to invoke a product action.
|
|
188
|
+
|
|
189
|
+
- Prefer `client.devices`, `client.rooms`, `client.tickets`, and
|
|
190
|
+
`client.channels` managed flows; they retain admission and protected-route
|
|
191
|
+
checks across transport replacement.
|
|
192
|
+
- Treat raw endpoint tickets and low-level manual peer APIs as transport
|
|
193
|
+
primitives. A consumer using them must define its own authorization boundary.
|
|
194
|
+
- Authorize every privileged message against the accepted OpenRTC scope and the
|
|
195
|
+
consumer application's current ACL. Never trust a payload's self-declared
|
|
196
|
+
sender, role, or scope.
|
|
197
|
+
- Keep compound tickets and session tokens out of logs, telemetry, query
|
|
198
|
+
strings, crash reports, and UI diagnostics. Use URL fragments for intentional
|
|
199
|
+
browser handoff and scrub them immediately after capture.
|
|
200
|
+
- Revocation must invalidate the matching scope and product ACL; reconnecting a
|
|
201
|
+
transport must not restore revoked access.
|
|
202
|
+
|
|
203
|
+
The full owner and release contract is in
|
|
204
|
+
[`docs/architecture/application-security-and-delivery-contract.md`](../../docs/architecture/application-security-and-delivery-contract.md).
|
|
205
|
+
|
|
157
206
|
## Design Rule
|
|
158
207
|
If a feature requires discovery, signaling, presence, or lifecycle state, the TypeScript package should delegate to Rust rather than reimplement it locally, except for the scoped browser Firebase host layer where the official browser SDK is the source of truth. In both cases, keep the avenue semantics intact: persistent user-device rosters are not space/room live rosters.
|
|
159
208
|
|
package/dist/{DelegatingRuntimeAdapter-BxOcVIx_.d.ts → DelegatingRuntimeAdapter-By7pziBs.d.ts}
RENAMED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { D as DiscoveryMode, A as AuthMode, S as SignalingMode, E as ExplicitFileDataSendParams, I as ISignalingBackend, R as RuntimeIdentity, a as Device, b as DeviceStatusSnapshot, P as PeerSessionSnapshot, c as ResolvedPeerIdentity, M as ManagedConnectionRecord, d as SignalingEnvelope, e as DeviceEvent, f as SignalingSession, g as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, h as BackendPeerUniStream, i as
|
|
1
|
+
import { D as DiscoveryMode, A as AuthMode, S as SignalingMode, E as ExplicitFileDataSendParams, I as ISignalingBackend, R as RuntimeIdentity, a as Device, b as DeviceStatusSnapshot, P as PeerSessionSnapshot, c as ResolvedPeerIdentity, M as ManagedConnectionRecord, d as SignalingEnvelope, e as DeviceEvent, f as SignalingSession, g as SessionEvent, L as LocalDeviceInfo, N as NativeManagedSessionStartResult, G as GrantScope, B as BackendPeerBiStream, h as BackendPeerUniStream, i as NativeConnectParams, j as NativeConnectResult, k as BackendConnectionState } from './types-CzIpGV9x.js';
|
|
2
|
+
import { A as AuthContext } from './IEngineBridge-C7OT2CRv.js';
|
|
2
3
|
|
|
3
4
|
type RuntimeAdapterKind = 'browser-wasm' | 'native-ipc' | 'tauri-ipc' | 'unknown';
|
|
4
5
|
interface RuntimeCapabilities {
|
|
@@ -83,23 +84,17 @@ declare function cloneRuntimeCapabilities(capabilities: RuntimeCapabilities): Ru
|
|
|
83
84
|
declare function runtimeCapabilitiesFromNativeStatus(status: NativeRuntimeStatusSnapshot | null | undefined, allowWasmFallback?: boolean): RuntimeCapabilities;
|
|
84
85
|
declare function runtimeCapabilityProfile(capabilities: RuntimeCapabilities): RuntimeCapabilityProfile;
|
|
85
86
|
|
|
86
|
-
type AuthContext = {
|
|
87
|
-
userId: string;
|
|
88
|
-
token?: string | null;
|
|
89
|
-
refreshToken?: string | null;
|
|
90
|
-
customToken?: string | null;
|
|
91
|
-
tokenProvider?: (forceRefresh?: boolean) => Promise<string | null>;
|
|
92
|
-
expiresAtMs?: number | null;
|
|
93
|
-
};
|
|
94
|
-
|
|
95
87
|
interface WasmBridgeOptions {
|
|
96
88
|
apiKey?: string;
|
|
97
89
|
discoveryMode?: DiscoveryMode;
|
|
90
|
+
space?: string;
|
|
98
91
|
spaceKey?: string;
|
|
99
92
|
authMode?: AuthMode;
|
|
100
93
|
signalingMode?: SignalingMode;
|
|
101
94
|
projectId?: string;
|
|
102
95
|
storagePrefix?: string;
|
|
96
|
+
deviceIdPersistence?: 'persistent' | 'ephemeral';
|
|
97
|
+
endpointIdPersistence?: 'persistent' | 'ephemeral';
|
|
103
98
|
nodeIdPersistence?: 'persistent' | 'ephemeral';
|
|
104
99
|
localDeviceId?: string;
|
|
105
100
|
deviceName?: string;
|
|
@@ -121,6 +116,7 @@ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
|
|
|
121
116
|
stopAuthScopedActivity(): Promise<void>;
|
|
122
117
|
getTurnCredentials(): Promise<any>;
|
|
123
118
|
updatePresence(localNodeId: string, ticketStr: string, isOnline: boolean, ttlMs: number, metadata?: string): Promise<void>;
|
|
119
|
+
refreshLivePresence(localNodeId: string, ticketStr: string, metadata?: string): Promise<void>;
|
|
124
120
|
setOffline(localNodeId: string): Promise<void>;
|
|
125
121
|
cleanupStaleDevices(): Promise<void>;
|
|
126
122
|
searchDevices(excludeNodeId?: string): Promise<Device[]>;
|
|
@@ -160,6 +156,9 @@ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
|
|
|
160
156
|
autoConnect?: boolean;
|
|
161
157
|
presence?: boolean;
|
|
162
158
|
}): Promise<NativeManagedSessionStartResult>;
|
|
159
|
+
notifyNetworkChange(options?: {
|
|
160
|
+
reason?: string;
|
|
161
|
+
}): Promise<unknown>;
|
|
163
162
|
getManagedNodeId(options?: {
|
|
164
163
|
initializeIfMissing?: boolean;
|
|
165
164
|
}): Promise<string | null>;
|
|
@@ -174,17 +173,18 @@ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
|
|
|
174
173
|
openPeerNativeBi(id: string, label: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
|
|
175
174
|
openPeerBiTransportOnly(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
|
|
176
175
|
openPeerUni(id: string, timeoutMs?: number): Promise<BackendPeerUniStream>;
|
|
177
|
-
connectToDevice(params:
|
|
178
|
-
deviceId?: string | null;
|
|
179
|
-
endpointTicket: string;
|
|
180
|
-
}): Promise<NativeConnectResult>;
|
|
176
|
+
connectToDevice(params: NativeConnectParams): Promise<NativeConnectResult>;
|
|
181
177
|
disconnectDevice(deviceId: string): Promise<void>;
|
|
182
178
|
isConnected(nodeId: string): Promise<boolean>;
|
|
183
179
|
getConnectionStates(): Promise<BackendConnectionState[]>;
|
|
184
180
|
onConnectionStateChange(callback: (state: BackendConnectionState) => void): Promise<() => void> | (() => void);
|
|
181
|
+
/** @deprecated Use named channels or `openrtc-file-transfer`. */
|
|
185
182
|
sendExplicitFilePath(connectionId: string, filePath: string, transferId?: string): Promise<string>;
|
|
183
|
+
/** @deprecated Use named channels or `openrtc-file-transfer`. */
|
|
186
184
|
sendExplicitFileData(params: ExplicitFileDataSendParams): Promise<void>;
|
|
185
|
+
/** @deprecated Transfer history belongs to the consumer application. */
|
|
187
186
|
getTransferHistory(limit?: number): Promise<Array<[string, unknown]>>;
|
|
187
|
+
/** @deprecated Transfer history belongs to the consumer application. */
|
|
188
188
|
deleteTransferJob(jobId: string): Promise<void>;
|
|
189
189
|
getRuntimeCapabilities(): RuntimeCapabilities;
|
|
190
190
|
onIncomingNativeMessage(callback: (connectionId: string, remoteNodeId: string | null, message: any) => void): Promise<() => void>;
|
|
@@ -198,4 +198,4 @@ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
|
|
|
198
198
|
setCoreClient(client: unknown): void;
|
|
199
199
|
}
|
|
200
200
|
|
|
201
|
-
export {
|
|
201
|
+
export { BROWSER_WASM_RUNTIME_CAPABILITIES as B, DelegatingRuntimeAdapter as D, NATIVE_IPC_RUNTIME_CAPABILITIES as N, type RuntimeCapabilities as R, type WasmBridgeOptions as W, type RuntimeCapabilityProfile as a, type RuntimeAdapterKind as b, type NativeRuntimeStatusSnapshot as c, type NativeRuntimeTransportFeatureStatus as d, cloneRuntimeCapabilities as e, runtimeCapabilityProfile as f, runtimeCapabilitiesFromNativeStatus as r };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
type AuthContext = {
|
|
2
|
+
userId: string;
|
|
3
|
+
token?: string | null;
|
|
4
|
+
refreshToken?: string | null;
|
|
5
|
+
customToken?: string | null;
|
|
6
|
+
tokenProvider?: (forceRefresh?: boolean) => Promise<string | null>;
|
|
7
|
+
expiresAtMs?: number | null;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export type { AuthContext as A };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as ClientOptions } from './types-
|
|
2
|
-
import { W as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-
|
|
1
|
+
import { C as ClientOptions } from './types-CzIpGV9x.js';
|
|
2
|
+
import { W as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-By7pziBs.js';
|
|
3
3
|
|
|
4
4
|
type PlutoIpcUnlisten = () => void | Promise<void>;
|
|
5
5
|
interface PlutoIpcBridge {
|
package/dist/auth/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{H as authHost,G as getAuthHost,F as registerDesktopAuthRelay}from'../chunk-A2ENDDFR.js';
|
package/dist/auth/internal.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{F as registerDesktopAuthRelay}from'../chunk-A2ENDDFR.js';
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {getApps,initializeApp}from'firebase/app';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 E(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var _=new Set;function S(t,e){_.has(t)||(_.add(t),console.warn(e));}function re(t){return /^pk_(live|test)_[0-9a-f]{40}$/.test(t)}async function Le(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 I(t){let e=typeof t.apiKey=="string"?t.apiKey.trim():"";if(e)return re(e)||S(`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 T(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||S("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function He(t){let e=typeof t.projectId=="string"?t.projectId.trim():"";return e||(S("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),v)}function N(t){return t.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Be(t){let e="storagePrefix"in t&&typeof t.storagePrefix=="string"?N(t.storagePrefix):"";return e||N(I(t))||"default"}var qe={devicesPerUser:2,maxRooms:10,maxMembersPerRoom:5,maxPersonalDevices:25};var oe=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],L={iceServers:oe},We={};var H=["iroh-relay","iroh","moq"];function ie(t){return (Array.isArray(t.urls)?t.urls:[t.urls]).some(n=>typeof n=="string"&&(n.startsWith("turn:")||n.startsWith("turns:")))}function se(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 R(t){if(t)return t.map(e=>se(e)).filter(e=>e!==null)}function B(t,e){let n=new Set(["iroh-relay","iroh","moq"]);e&&n.add("webrtc");let r=(t??H).filter(o=>n.has(o));return r.length>0?r:[...H]}function je(t){return !!t?.transports?.webrtc}function Ge(t,e){let n=t?.transports?.webrtc||void 0;if(n)return t?.strictMode||n.privacyMode?{...n,iceServers:R(n.iceServers),iceTransportPolicy:"relay"}:n.iceTransportPolicy==="relay"&&!(Array.isArray(n.iceServers)&&n.iceServers.some(o=>ie(o)))?(e?.("[Client] Overriding relay-only ICE policy to all because no TURN servers are configured"),{...n,iceTransportPolicy:"all"}):n}var ae=/^[A-Za-z0-9._-]+$/,ce="[redacted]";function F(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 F(t.trim()).toString()}function $e(t,e){let n=F(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(!ae.test(r))throw new Error("[OpenRTC] transports.moq.accessToken must be a URL-safe JWT.");n.searchParams.append("jwt",r);}return n.toString()}function Qe(t){try{let e=new URL(t);return e.search="",e.hash="",e.toString()}catch{return "invalid-moq-relay-url"}}function Ye(t,e){let n=t instanceof Error?`${t.name}: ${t.message}`:String(t),r=e?.trim();return r?n.split(r).join(ce):n}var le=["iroh-lan","webrtc-lan","ble","webrtc","moq","iroh"];function A(t){let e=t.spaceKey??t.space;return {...t,...e!==void 0?{spaceKey:e}:{}}}function q(t){return {...t,iceServers:t.iceServers?t.iceServers.map(e=>({...e})):t.iceServers}}function de(t){return {...t}}function ue(t){return {...t}}function pe(t){if(t)return {iroh:typeof t.iroh=="object"?ue(t.iroh):t.iroh,webrtc:typeof t.webrtc=="object"?q(t.webrtc):t.webrtc,ble:typeof t.ble=="object"?{...t.ble}:t.ble,moq:typeof t.moq=="object"?de(t.moq):t.moq}}function me(t){if(t.strictMode&&!t.transports&&(t.transports={iroh:{relayOnly:true}}),!!t.transports){if(t.transports.webrtc===true?t.transports.webrtc=q(L):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 ge(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:R(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 tt(t){let e=A(t),n=I(e),r=T(e),o={strictMode:false,disableIrohFallback:false,transportPriority:[...le],...e,authMode:r,transports:pe(e.transports)};me(o),ge(o),o.strictMode&&(o.transportPriority=B(e.transportPriority,!!o.transports?.webrtc));let i=W(o),s=(o.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:n,authMode:r,configuredPersistenceMode:i,options:o,roomCreationMode:s}}function W(t){let e=t.transports?.iroh;return t.endpointIdPersistence??t.nodeIdPersistence??(typeof e=="object"?e.persistenceMode:void 0)??"ephemeral"}function nt(t){return "options"in t&&"configuredPersistenceMode"in t?{apiKey:t.options.apiKey,authMode:T(t.options),projectId:t.options.projectId,storagePrefix:t.options.storagePrefix,nodeIdPersistence:t.configuredPersistenceMode}:{apiKey:t.apiKey,authMode:T(t),projectId:t.projectId,storagePrefix:t.storagePrefix,nodeIdPersistence:W(t)}}function rt(t,e){e&&(t.transports={...t.transports||{},...e});}var v="pluto-rtc-prod",K={apiKey:"AIzaSyA62Krj-7ZYFT5xjrTUq7mXana41Ahj_mM",authDomain:"api.openrtc.app",projectId:v,storageBucket:"pluto-rtc-prod.firebasestorage.app",messagingSenderId:"607066575224",appId:"1:607066575224:web:ed3f51825ba228db92b88d"};function st(t){let e=A(t),n=typeof e.projectId=="string"&&e.projectId.trim()?e.projectId.trim():v;return {...e,projectId:n}}function j(t){return new Promise(e=>setTimeout(e,t))}function ct(t){let e=new Uint8Array(t.byteLength);return e.set(t),e}function lt(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 dt(t,e,n){let r=e*Math.pow(2,Math.max(0,t-1));return Math.min(n,r)}function ut(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 pt(t,e){let n=t;if(!n)return null;try{let r=n.send,o=n.recv;if(!r||typeof r.getWriter!="function"||!o||typeof o.getReader!="function")return null;let i=typeof n.endpoint_id=="string"&&n.endpoint_id.trim().length>0?n.endpoint_id:e;return {send:r,recv:o,endpoint_id:i}}catch{return null}}function mt(t,e){let n={send:t.send,recv:e,endpoint_id:typeof t.endpoint_id=="string"?t.endpoint_id:""};return t?.applicationCryptoWrapped===true&&(n.applicationCryptoWrapped=true),n}async function gt(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 yt(t,e,n={}){let r=n.context??"prependBytesToReader",o=n.traceId,i=e.byteLength===0,s=n.pendingRead??null,l=a=>n.release?.(a),d=(a,p)=>n.log?.(a,p);return new ReadableStream({async pull(a){if(!i){i=true,a.enqueue(e);return}if(s){let u=s;s=null;let m;try{m=await u;}catch(y){a.error(y),l("pending-read-error"),d("prepend-bytes:pending-read-error",{context:r,traceId:o||null,error:y?.message||String(y)});return}if(m.done){a.close(),l("pending-done");return}m.value&&a.enqueue(m.value);return}let p;try{p=await t.read();}catch(u){a.error(u),l("read-error"),d("prepend-bytes:read-error",{context:r,traceId:o||null,error:u?.message||String(u)});return}let{done:P,value:b}=p;if(P){a.close(),l("done");return}b&&a.enqueue(b);},async cancel(a){l("cancel");}})}async function ft(t,e){let n=t.read(),r=e-Date.now();if(r<=0)return {status:"timeout",pendingRead:n};let o=Symbol("probe-timeout"),i,s=new Promise(l=>{i=setTimeout(()=>l(o),r);});try{let l=await Promise.race([n,s]);if(l===o)return {status:"timeout",pendingRead:n};let{done:d,value:a}=l;return d?{status:"done"}:{status:"data",value:a&&a.byteLength>0?new Uint8Array(a):new Uint8Array(0)}}finally{i&&clearTimeout(i);}}function G(t,e,n){let r;return new Promise((o,i)=>{r=setTimeout(()=>{if(r=void 0,typeof n=="function"){i(n());return}let s=n?`${n} timed out`:"timeout";i(new Error(`${s} after ${e}ms`));},e),t.then(s=>{r!==void 0&&clearTimeout(r),o(s);},s=>{r!==void 0&&clearTimeout(r),i(s);});})}var J="pluto-rtc-auth",M=null;function Me(){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(Me()){if(typeof e>"u"){console.log(t);return}console.log(t,e);}}function Mt(t){M=t;}function De(){return E()}function te(){return typeof navigator>"u"?false:/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||"")}function X(){return De()&&te()}function g(t,e,n){return G(t,e,()=>new Error(`${n} timeout after ${e}ms`))}function Z(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 ee(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 D=class{constructor(){this.redirectResultPromise=null;this.redirectResultConsumed=false;this.lastRelayedToken=null;this.lastRelayedRefreshToken=null;this.desktopTokenRefreshIntervalId=null;let e=getApps().find(o=>o.name===J);this.app=e||initializeApp(K,J);let n=te(),r=X();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():"",s=typeof import.meta<"u"?import.meta.env:null;if(!!o||!!i||!!s&&String(s.VITE_USE_EMULATORS)==="true"&&(s.DEV||String(s.VITE_E2E)==="true")){let d=String(s?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",[a,p]=o.split(":"),[P,b]=i.split(":"),u=(a??"").trim()||d,m=(P??"").trim()||d,y=Number(p??s?.VITE_OPENRTC_AUTH_EMULATOR_PORT??9100),ne=Number(b??s?.VITE_OPENRTC_FUNCTIONS_EMULATOR_PORT??5002);try{connectAuthEmulator(this.auth,`http://${u}:${y}`,{disableWarnings:!0});}catch{}try{connectFunctionsEmulator(this.functions,m,ne);}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}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(X())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(s){console.warn("[PLUTO-RTC][AUTH-HOST] authStateReady did not resolve in time; continuing custom token sign-in",{callbackId:e.callbackId,message:s?.message});}}let i;try{i=await g(signInWithCustomToken(this.auth,e.idToken),25e3,"signInWithCustomToken (custom token path)");}catch(s){console.warn("[PLUTO-RTC][AUTH-HOST] First custom token sign-in attempt failed; retrying once",{callbackId:e.callbackId,message:s?.message,code:s?.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(s){console.warn("[PLUTO-RTC][AUTH-HOST] Failed to update custom-token user profile",{callbackId:e.callbackId,message:s?.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"),s=await g(signInWithCustomToken(this.auth,i),15e3,"signInWithCustomToken");return c("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken fallback success",{callbackId:e.callbackId,provider:e.provider,uid:s.user?.uid,elapsedMs:Date.now()-n}),s.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 s=await signInWithPopup(this.auth,i);return {idToken:await getIdToken(s.user,true),refreshToken:s.user.refreshToken}}let n=new OAuthProvider("apple.com");n.addScope("email"),n.addScope("name");let r=Z(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",r),n.setCustomParameters({nonce:await ee(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||Z(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",o),r.setCustomParameters({nonce:await ee(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}},O=null;function Ee(){return O||(O=new D),O}var Dt=new Proxy({},{get(t,e,n){let r=Ee(),o=r[e];return typeof o=="function"?o.bind(r):o}});
|
|
2
|
+
export{mt as A,gt as B,yt as C,ft as D,G as E,Mt as F,Ee as G,Dt as H,E as a,Le as b,I as c,T as d,He as e,Be as f,qe as g,oe as h,L as i,We as j,je as k,Ge as l,$e as m,Qe as n,Ye as o,A as p,tt as q,nt as r,rt as s,st as t,j as u,ct as v,lt as w,dt as x,ut as y,pt as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function o(e,t={}){if(e.online!==true)return false;let i=t.now??Date.now(),r=n(e.expiresAt);if(typeof r=="number")return r>i;if(typeof t.staleAfterMs!="number"||!Number.isFinite(t.staleAfterMs))return true;let s=n(e.updatedAt)??n(e.lastSeenAt)??n(e.createdAt);return typeof s!="number"||s+t.staleAfterMs>i}function u(e){let t=String(e.connectionStatus??"").trim().toLowerCase();return t==="closed"||t==="disconnected"||t==="failed"?false:e.settledReady===true||String(e.readinessState??"").trim().toLowerCase()==="routable"}function c(e){if(e.connectable!==void 0)return e.connectable===true;let t=typeof e.ticket=="string"?e.ticket.trim():"";return e.online===true&&t.length>0&&String(e.presenceStatus??"online").trim().toLowerCase()!=="offline"}function n(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"){let t=e.toMillis();return Number.isFinite(t)?t:void 0}}export{o as a,u as b,c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {g,h}from'./chunk-
|
|
1
|
+
import {g,h}from'./chunk-MA2JFAV7.js';function c(){return g()}var i=class extends h{constructor(r){super({...r,bridge:g(),allowWasmFallback:r.allowWasmFallback??false});}};export{c as a,i as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {v,c,e,d,G as G$1,f,u,b,w,a,E as E$1,x as x$1}from'./chunk-A2ENDDFR.js';import {g,b as b$1}from'./chunk-BLOEZIFJ.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';import {getFirestore,connectFirestoreEmulator,getDoc,serverTimestamp as serverTimestamp$1,setDoc,updateDoc,deleteDoc,collection,doc,getDocs,query,where,limit,onSnapshot,getDocFromServer}from'firebase/firestore';import {getDatabase,connectDatabaseEmulator,onValue,ref,onDisconnect,set,onChildAdded,onChildChanged,onChildRemoved,serverTimestamp,get}from'firebase/database';import {httpsCallable,getFunctions}from'firebase/functions';import*as we from'tweetnacl';function zt(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function Pe(i,e,t){if(zt()){if(typeof t>"u"){console[i](e);return}console[i](e,t);}}function De(i,e){Pe("debug",i,e);}function R(i,e){Pe("info",i,e);}function ai(i,e){Pe("log",i,e);}var O=new Uint8Array([79,82,84,67,69,49]),de=2,G=8,$=24,st=32,Vt=3,jt=16*1024*1024,qt=4096;function Yt(i,e){if(i.byteLength<e.byteLength)return false;let t=0;for(let n=0;n<e.byteLength;n+=1)t|=i[n]^e[n];return t===0}function $t(i){let e=new Uint8Array(i),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 Xt(i,e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return `${i}:${t}`}function ot(i){if(!Yt(i,O))return null;let e=i[O.byteLength];return e===de?e:null}function Jt(i){return ot(i)===de&&i.byteLength>O.byteLength+1+G+$}function ui(i,e={}){if(!(i instanceof Uint8Array)||i.byteLength!==st)throw new Error(`[OpenRTC] application payload crypto key must be ${st} bytes`);let t=new Uint8Array(i),n=e.requireEncrypted??true,r=e.randomBytes??$t,s=e.replayProtection??true,o=0,a=new Set,c=[];return {requireEncrypted:n,protectPayload(l,d){let u=r($);if(!(u instanceof Uint8Array)||u.byteLength!==$)throw new Error(`[OpenRTC] application payload crypto nonce must be ${$} bytes`);let p=new Uint8Array(1+d.byteLength);p[0]=l,p.set(d,1);let f=xchacha20poly1305(t,u).encrypt(p);if(!s)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let h=new Uint8Array(O.byteLength+1+G+u.byteLength+f.byteLength),g=0;h.set(O,g),g+=O.byteLength,h[g]=de,g+=1;let v=o;return o+=1,new DataView(h.buffer,h.byteOffset+g,G).setBigUint64(0,BigInt(v),false),g+=G,h.set(u,g),g+=u.byteLength,h.set(f,g),h},openPayload(l,d){if(!Jt(d))return n?null:d;if(ot(d)!==de)return null;let p=O.byteLength+1,f=Number(new DataView(d.buffer,d.byteOffset+p,G).getBigUint64(0,false));if(!Number.isFinite(f))return null;let h=p+G,g=h+$,v=d.slice(h,g),w=s?Xt(f,v):null;if(w&&a.has(w))return null;let F=d.slice(g),b;try{b=xchacha20poly1305(t,v).decrypt(F);}catch{return null}if(b.byteLength<1||b[0]!==l)return null;if(w)for(a.add(w),c.push(w);c.length>qt;){let I=c.shift();I&&a.delete(I);}return b.slice(1)}}}function Qt(i){let e=new Uint8Array(4+i.byteLength);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(0,i.byteLength,false),e.set(i,4),e}function Te(i,e={}){let t=e.typeId??Vt,n=e.maxFrameBytes??jt;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 r=d=>i.protectPayload(t,d),s=d=>i.openPayload(t,d),o=()=>new TransformStream({transform(d,u){u.enqueue(Qt(r(new Uint8Array(d))));}}),a=()=>{let d=new Uint8Array(0);return new TransformStream({transform(u,p){for(d=w([d,new Uint8Array(u)]);d.byteLength>=4;){let f=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,false);if(f===0||f>n)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(d.byteLength<4+f)return;let h=d.slice(4,4+f);d=d.slice(4+f);let g=s(h);if(!g)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");p.enqueue(g);}},flush(){if(d.byteLength!==0)throw new Error("[OpenRTC] encrypted raw stream ended mid-frame")}})},c=d=>d.pipeThrough(a()),l=d=>{let u=o();return u.readable.pipeTo(d).catch(()=>{}),u.writable};return {typeId:t,protectFrame:r,openFrame:s,createOutboundTransform:o,createInboundTransform:a,wrapReadable:c,wrapWritable:l,wrapBiStream(d){return {...d,send:l(d.send),recv:c(d.recv)}}}}var Zt="[OpenRTC][teardown-trace]";function en(){try{let i=globalThis;if(i.OPENRTC_TEARDOWN_TRACE===!0||i.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function at(i,e={}){console.info(Zt,{kind:i,ts:new Date().toISOString(),...e}),en()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:i,stack:new Error(`teardown: ${i}`).stack});}var X={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 hi(){return X}var le={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}},tn={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 J(i){return {adapter:i.adapter,signaling:{...i.signaling},transport:{...i.transport},nativeProtocols:{...i.nativeProtocols},lifecycle:{...i.lifecycle},transfers:{...i.transfers},fallback:{...i.fallback}}}function U(i){return i?.compiled===true&&i.enabled===true}function yi(i,e=false){let t=J(tn),n=i?.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 mi(i){return {environment:i.adapter==="native-ipc"||i.adapter==="tauri-ipc"?"native":i.adapter==="browser-wasm"?"web":"unknown",transports:{quic:i.transport.irohQuic,irohRelay:i.transport.irohQuic,irohLan:i.transport.irohLan,webRtc:i.transport.webRtcUpgrade||i.transport.nativeWebRtc,webRtcLan:i.transport.webRtcLan,moq:i.transport.moq,ble:i.transport.ble},lifecycle:{...i.lifecycle},storage:{localFileSystem:i.transfers.explicitFilePath,transferHistory:i.transfers.history},nativeProtocols:{...i.nativeProtocols}}}function x(i){if(!i)return null;let e=2166136261;for(let t=0;t<i.length;t+=1)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var dn=9e4,ln=3e4;function xe(i=Date.now()){return i+dn}function E(i,e=Date.now()){return !i||i.online!==true?false:typeof i.leaseExpiresAt!="number"?true:i.leaseExpiresAt>e}function un(i,e){switch(i.kind){case "user-scoped":return `presence/${i.appTag}/users/${i.userId}/devices/${e}`;case "space":return `presence/spaces/${i.namespaceId}/devices/${e}`}}function Ae(i,e,t){return `${un(i,e)}/instances/${t}`}function dt(i){switch(i.kind){case "user-scoped":return `presence/${i.appTag}/users/${i.userId}/devices`;case "space":return `presence/spaces/${i.namespaceId}/devices`}}function lt(i,e,t){return `presence/${i}/rooms/${e}/members/${t}`}function pn(i,e){return `presence/${i}/rooms/${e}/members`}function Q(i){let e={},t=(n,r)=>{if(typeof r!="string")return;let s=r.trim();s&&(e[n]=s);};if(t("ticket",i?.ticket),t("nodeId",i?.nodeId),t("deviceName",i?.deviceName),t("platformType",i?.platformType),t("metadata",i?.metadata),Array.isArray(i?.excludedPeers)){let n=i.excludedPeers.map(r=>typeof r=="string"?r.trim().toLowerCase():"").filter(Boolean).filter((r,s,o)=>o.indexOf(r)===s).sort();n.length>0&&(e.excludedPeers=n);}return e}function fn(i,e){if(!i||typeof i!="object")return null;let t=i,n=Q({ticket:t.ticket,nodeId:t.nodeId,deviceName:t.deviceName,platformType:t.platformType,metadata:t.metadata,excludedPeers:t.excludedPeers});return {online:E({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 ut(i,e=Date.now()){if(!i||typeof i!="object")return null;let t=i.instances;if(!t||typeof t!="object")return null;let n=Object.entries(t).map(([r,s])=>({instanceId:r,state:fn(s,e)})).filter(r=>!!r.state).sort((r,s)=>s.instanceId.localeCompare(r.instanceId));return n.length===0?null:n.find(r=>r.state.online)?.state??n[0].state}function hn(){let i=Date.now().toString().padStart(13,"0"),e=globalThis.crypto?.randomUUID?.().replace(/-/g,"")??Math.random().toString(36).slice(2);return `${i}-${e}`}function _e(i,e){return {online:true,lastSeenAt:serverTimestamp(),ticketVersion:i,leaseExpiresAt:xe(),...Q(e)}}function ke(i,e){return {online:false,lastSeenAt:serverTimestamp(),ticketVersion:i,leaseExpiresAt:Date.now(),...Q(e)}}function ue(i){return {...i}}function Me(i,e){return {...i,lastSeenAt:serverTimestamp(),leaseExpiresAt:e?xe():Date.now()}}var pe=class{constructor(e,t=hn()){this.desiredOnlineNodes=new Map;this.connected=null;this.connectedUnsubscribe=null;this.leaseRefreshTimer=null;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;try{let r=globalThis?.__OPENRTC_RTDB_EMULATOR_HOST__,s=typeof r=="string"?r.trim():"";if(s){let[o,a]=s.split(":"),c=(o??"").trim()||"127.0.0.1",l=Number(a??9001);try{connectDatabaseEmulator(this.db,c,l);}catch{}}else {let o=import.meta?.env;if(!!o?.DEV&&String(o?.VITE_USE_EMULATORS)==="true"){let c=String(o?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",l=Number(o?.VITE_OPENRTC_RTDB_EMULATOR_PORT??9001);try{connectDatabaseEmulator(this.db,c,l);}catch{}}}}catch{}}ensureReconnectWatch(){this.connectedUnsubscribe||(this.connectedUnsubscribe=onValue(ref(this.db,".info/connected"),e=>{let t=e.val()===true,n=t&&this.connected===false;if(this.connected=t,!!n)for(let r of this.desiredOnlineNodes.keys())this.publishDesiredOnline(r).catch(s=>{console.warn("[RtdbPresence] failed to republish presence after reconnect:",{path:r,error:s});});}));}async publishDesiredOnline(e){let t=this.desiredOnlineNodes.get(e);if(!t)return;t.online=Me(t.online,true),t.offline=Me(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});});},ln));}stopLeaseRefreshIfIdle(){this.desiredOnlineNodes.size>0||!this.leaseRefreshTimer||(clearInterval(this.leaseRefreshTimer),this.leaseRefreshTimer=null);}async registerOnlineNode(e,t,n){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,Me(t,false));}subscribeIncremental(e,t,n,r){let s=ref(this.db,e),o={},a=()=>n({...o}),c=u=>{let p=typeof u.key=="string"?u.key:"";if(!p)return;let f=t(p,u.val());f?o[p]=f:delete o[p],a();},l=u=>{console.warn(`[RtdbPresence] ${r} presence subscription error:`,u);},d=[onChildAdded(s,c,l),onChildChanged(s,c,l),onChildRemoved(s,u=>{let p=typeof u.key=="string"?u.key:"";p&&(delete o[p],a());},l)];return ()=>{for(let u of d)u();}}async registerDevice(e,t,n=0,r){let s=Ae(e,t,this.runtimeInstanceId);try{await this.registerOnlineNode(s,ue(_e(n,r)),ue(ke(n,r))),R("[RtdbPresence] registered device presence",{path:s,scopeKind:e.kind,deviceId:t,ticketVersion:n,hasTicket:typeof r?.ticket=="string"&&r.ticket.length>0,hasNodeId:typeof r?.nodeId=="string"&&r.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,r){let s=Ae(e,t,this.runtimeInstanceId),o=ref(this.db,s),a=this.desiredOnlineNodes.get(s),c=Q(r);if(a){let l=a.online;c=Q({ticket:r?.ticket??l.ticket,nodeId:r?.nodeId??l.nodeId,deviceName:r?.deviceName??l.deviceName,platformType:r?.platformType??l.platformType,metadata:r?.metadata??l.metadata,excludedPeers:r?.excludedPeers??l.excludedPeers}),a.online=ue(_e(n,c)),a.offline=ue(ke(n,c));}await onDisconnect(o).set(ke(n,c)),await set(o,_e(n,c));}async markOffline(e,t,n=0){await this.markNodeOffline(Ae(e,t,this.runtimeInstanceId),{online:false,lastSeenAt:serverTimestamp(),ticketVersion:n,leaseExpiresAt:Date.now()});}async registerRoomMember(e,t,n){await this.registerOnlineNode(lt(e,t,n),{online:true,lastSeenAt:serverTimestamp(),leaseExpiresAt:xe()},{online:false,lastSeenAt:serverTimestamp(),leaseExpiresAt:Date.now()});}async markRoomMemberOffline(e,t,n){await this.markNodeOffline(lt(e,t,n),{online:false,lastSeenAt:serverTimestamp(),leaseExpiresAt:Date.now()});}onRoomPresenceChange(e,t,n){return this.subscribeIncremental(pn(e,t),(r,s)=>{if(!s||typeof s!="object")return null;let o=s;return {online:E({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(dt(e),(n,r)=>ut(r),t,"device")}async readPresenceMap(e){let n=(await get(ref(this.db,dt(e)))).val();if(!n||typeof n!="object")return {};let r={};for(let[s,o]of Object.entries(n)){if(!o||typeof o!="object")continue;let a=ut(o);a&&(r[s]=a);}return r}};var Le=100;function yt(i,e){return !i||i.kind!==e.kind?false:i.kind==="user-scoped"&&e.kind==="user-scoped"?i.appTag===e.appTag&&i.userId===e.userId:i.kind==="space"&&e.kind==="space"&&i.namespaceId===e.namespaceId}function bn(i){try{let e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,n=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(n));let r=globalThis.Buffer;if(r)return JSON.parse(r.from(n,"base64").toString("utf8"))}catch{return null}return null}function z(i){let e=typeof i=="string"?i.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null,s=r?bn(r):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:x(n),tokenFingerprint:x(o),tokenSuffixFingerprint:x(r),scope:a,maxConnections:c}}var V=class V{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;}get options(){return this.hooks.options}setRtdbPresence(e,t){let n=this.rtdbPresence===e,r=yt(this.rtdbScope,t);if(n&&r)return;let s=this.deviceListeners.size>0;R("[BrowserDeviceDiscovery][rtdb] adapter or scope changed",{sameAdapter:n,sameScope:r,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(r=>r.online);return e?this.filterDevices(n,e):n}async listDevices(e){let t=await this.readCurrentDeviceSnapshot();return e?this.filterDevices(t,e):t}async subscribeDevices(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return new ReadableStream({start(n){n.close();}});let t=null;return new ReadableStream({start:n=>{t=onSnapshot(query(e,limit(Le)),r=>{let s=Date.now(),o=[];for(let a of r.docChanges()){let c=this.toDevice(a.doc,s);if(a.type==="removed"){o.push({type:"removed",deviceId:a.doc.id});continue}if(!c){o.push({type:"removed",deviceId:a.doc.id});continue}o.push({type:a.type==="added"?"added":"modified",device:c});}o.length>0&&n.enqueue(o);},r=>{console.warn("[BrowserDeviceDiscovery] subscribeDevices snapshot error:",{message:r?.message,code:r?.code});try{n.close();}catch{}});},cancel:()=>{t?.(),t=null;}})}onDevicesChange(e,t){let n=this.nextListenerIdSeed.value++;return this.deviceListeners.set(n,{callback:e,excludeNodeId:t}),this.emitDevicesToListener(n),this.ensureDeviceWatch(),()=>{this.deviceListeners.delete(n),this.deviceListeners.size===0&&this.stopDeviceWatch({clearDevices:true});}}async handleScopeChange(){let e=this.deviceListeners.size>0;this.stopDeviceWatch({clearDevices:true}),e&&await this.ensureDeviceWatch();}async cleanupStaleDevices(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return;let t=Date.now(),n=!!(this.rtdbPresence&&this.rtdbScope),r=await getDocs(query(e,where("online","==",false),where("expiresAt","<",t),limit(100)));if(await Promise.allSettled(r.docs.map(async c=>{let l=c.data();l.online===false&&this.isDeviceExpired(l,t)&&await deleteDoc(c.ref);})),n)return;let s=this.rtdbPresence&&this.rtdbScope?await this.rtdbPresence.readPresenceMap(this.rtdbScope).catch(()=>this.rtdbPresenceMap):this.rtdbPresenceMap,o=await getDocs(query(e,where("online","==",true),limit(100))),a=new Map;for(let c of o.docs)a.set(c.ref.path,c);await Promise.allSettled([...a.values()].map(async c=>{let l=c.data();this.isDeviceExpired(l,t);let u=l.online===true,p=this.toMillis(l.updatedAt)??this.toMillis(l.lastSeenAt)??0,f=this.rtdbPresence&&this.rtdbScope?3e4:3e5;if(!(!u||!p||p+f>t)){if(this.rtdbPresence&&this.rtdbScope){let h=typeof l.deviceId=="string"&&l.deviceId.trim()?l.deviceId.trim():c.id;if(E(s[h]))return}await updateDoc(c.ref,{online:false,updatedAt:serverTimestamp$1(),expiresAt:t+2592e6});}}));}async refreshDeviceForAutoConnect(e){let t=e.trim();if(!t)return null;let n=this.autoConnectRefreshes.get(t);if(n)return n;let r=this.refreshDeviceForAutoConnectOnce(t);this.autoConnectRefreshes.set(t,r);try{return await r}finally{this.autoConnectRefreshes.get(t)===r&&this.autoConnectRefreshes.delete(t);}}async refreshDeviceForAutoConnectOnce(e){if(this.rtdbPresence&&this.rtdbScope){let f=false,h=await this.readRtdbPresenceSnapshot().then(g=>g[e]).catch(g=>(f=true,console.warn("[BrowserDeviceDiscovery][auto-connect][refresh] RTDB read failed; refusing Firestore liveness fallback",{deviceId:e,error:g}),this.rtdbPresenceMap[e]));if(E(h)&&(h.ticket||h.nodeId)){let g=this.devicesById.get(e)??null,v=this.mergeRtdbPresenceIntoDevice(e,g,h)??this.deviceFromRtdbPresence(e,h);if(v){let w=this.upsertDeviceProjection(e,v);return R("[BrowserDeviceDiscovery][auto-connect][refresh]",{deviceId:e,source:"rtdb",ticketChanged:(g?.ticket??null)!==(v.ticket??null),previousTicket:z(g?.ticket),refreshedTicket:z(v.ticket),previousNodeId:g?.nodeId??null,refreshedNodeId:v.nodeId??null}),w&&this.emitDevicesToAll(),this.devicesById.get(e)??v}}if(f||!E(h))return null}let t=await this.hooks.getDevicesCollectionRef();if(!t)return this.devicesById.get(e)??null;let n=doc(t,e),r=this.devicesById.get(e)??null,s="server",o=null;try{o=await getDocFromServer(n);}catch(f){s="cache",console.warn("[BrowserDeviceDiscovery][auto-connect][refresh] getDocFromServer failed; falling back to getDoc",{deviceId:e,error:f}),o=await getDoc(n).catch(()=>null);}if(!o?.exists()){let f=this.devicesById.delete(e);return R("[BrowserDeviceDiscovery][auto-connect][refresh] device doc missing during refresh",{deviceId:e,source:s,previousTicket:z(r?.ticket)}),f&&this.emitDevicesToAll(),null}let a=typeof o.data=="function"?o.data():null,c=this.deviceFromSnapshot(e,a,Date.now());if(!c){let f=this.devicesById.delete(e);return R("[BrowserDeviceDiscovery][auto-connect][refresh] refreshed device doc was filtered out",{deviceId:e,source:s,previousTicket:z(r?.ticket)}),f&&this.emitDevicesToAll(),null}let l=this.rtdbPresenceMap[e],d=l?this.mergeRtdbPresenceIntoDevice(e,c,l)??c:c,u=this.upsertDeviceProjection(e,d),p=(r?.ticket??null)!==(d.ticket??null);return R("[BrowserDeviceDiscovery][auto-connect][refresh]",{deviceId:e,source:s,ticketChanged:p,previousTicket:z(r?.ticket),refreshedTicket:z(d.ticket),previousNodeId:r?.nodeId??null,refreshedNodeId:d.nodeId??null}),u&&this.emitDevicesToAll(),this.devicesById.get(e)??d}resolveKnownDeviceId(e){let t=e.trim();if(!t)return null;let n=this.devicesById.get(t);if(n?.deviceId)return n.deviceId;for(let r of this.devicesById.values())if(r.deviceId===t||r.nodeId===t||r.ticket===t)return r.deviceId;return null}stopDeviceWatch(e){this.deviceWatchGeneration+=1,this.deviceWatchSetup=null,this.clearFreshnessRecheckTimer(),this.activeDeviceUnsubscribe?.(),this.activeDeviceUnsubscribe=null,this.activeDeviceScopeKey=null,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[r,s]of this.devicesById){let o=s;if(this.isStaleOnlineDevice(o,t)){this.shouldRetainStaleDevice(o)?this.devicesById.set(r,this.retainedStaleDevice(s,r,t)):this.devicesById.delete(r),n=true;continue}this.isDeviceExpired(o,t)&&(this.devicesById.delete(r),n=true);}n&&this.emitDevicesToAll(),this.scheduleFreshnessRecheck(e);},V.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()),r=t.excludeNodeId?this.filterDevices(n,t.excludeNodeId):n;t.callback(r);}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){let n=this.durableRosterRead;if(n?.scopeKey===t)return n.promise;let r=getDocs(query(e,limit(Le))).then(s=>s.docs);this.durableRosterRead={scopeKey:t,promise:r};try{return await r}finally{this.durableRosterRead?.promise===r&&(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(r=>(this.rtdbPresence===e&&yt(this.rtdbScope,t)&&(this.rtdbPresenceMap=r,this.hasRtdbPresenceSnapshot=true),r));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 r=this.watchedDeviceSnapshot(t);if(r)return r;let s=this.rtdbPresenceMap;if(this.rtdbPresence&&this.rtdbScope)try{s=await this.readRtdbPresenceSnapshot();}catch(d){console.warn("[BrowserDeviceDiscovery] RTDB direct presence read failed:",d);}let o=await this.readDurableRosterDocuments(e,t),a=Date.now(),c=[],l=new Set;for(let d of o){let u=d.data();if(!this.options.matchesTag(u))continue;let p=typeof u.deviceId=="string"&&u.deviceId.trim().length>0?u.deviceId.trim():d.id;if(l.add(p),this.isStaleFirestoreOnlyRtdbDevice(p,u,a))continue;if(this.isStaleOnlineDevice(u,a)||u.online===true&&this.isDeviceExpired(u,a)){if((!this.rtdbPresence||!this.rtdbScope)&&await this.markStaleDeviceOffline(d,u,a),this.shouldRetainStaleDevice(u)){let w=this.retainedStaleDevice(this.options.normalizeDevice({...u,deviceId:u.deviceId??d.id,online:false},d.id),d.id,a);w.deviceId&&c.push(w);}continue}if(this.isDeviceExpired(u,a))continue;let h=this.options.normalizeDevice({...u,deviceId:u.deviceId??d.id},d.id);if(!h?.deviceId)continue;let g=s[h.deviceId],v=g?this.mergeRtdbPresenceIntoDevice(h.deviceId,h,g):h;v&&c.push(v);}if(this.rtdbPresence&&this.rtdbScope)for(let[d,u]of Object.entries(s)){if(l.has(d)||!E(u))continue;let p=this.deviceFromRtdbPresence(d,u);p&&c.push(p);}this.devicesById.clear();for(let d of c)this.devicesById.set(d.deviceId,d);return this.hasDeviceRosterSnapshot=true,c}async readLiveRtdbDeviceSnapshot(){if(!this.rtdbPresence||!this.rtdbScope)return this.readCurrentDeviceSnapshot();let e;try{e=await this.readRtdbPresenceSnapshot();}catch(n){return console.warn("[BrowserDeviceDiscovery] RTDB live search read failed; refusing Firestore liveness fallback:",n),[]}let t=[];for(let[n,r]of Object.entries(e)){if(!E(r))continue;let s=this.devicesById.get(n),o=this.mergeRtdbPresenceIntoDevice(n,s,r)??this.deviceFromRtdbPresence(n,r);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,r){if(!t||!this.options.matchesTag(t))return null;let s=typeof t.deviceId=="string"&&t.deviceId.trim().length>0?t.deviceId.trim():e;if(this.isStaleFirestoreOnlyRtdbDevice(s,t,n))return null;if(this.isStaleOnlineDevice(t,n)||t.online===true&&this.isDeviceExpired(t,n)){if(r&&(!this.rtdbPresence||!this.rtdbScope)&&this.markStaleDeviceOffline(r,t,n),!this.shouldRetainStaleDevice(t))return null;let c=this.retainedStaleDevice(this.options.normalizeDevice({...t,deviceId:t.deviceId??e,online:false},e),e,n);return c.deviceId?c:null}if(this.isDeviceExpired(t,n))return null;let a=this.options.normalizeDevice({...t,deviceId:t.deviceId??e},e);return a.deviceId?a:null}shouldRetainStaleDevice(e){return this.options.discoveryMode!=="user-scoped"||this.rtdbPresence&&this.rtdbScope&&e.online===true?false:(typeof e.kind=="string"?e.kind.trim().toLowerCase():"device")!=="ephemeral"}retainedStaleDevice(e,t,n){let r=this.toMillis(e.lastSeenAt)??this.toMillis(e.updatedAt)??this.toMillis(e.createdAt)??n;return {...e,deviceId:e.deviceId||t,online:false,presenceStatus:"idle",presenceUpdatedAt:r,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&&E(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 r=this.rtdbPresence&&this.rtdbScope?3e4:3e5;return n+r<=t}isStaleFirestoreOnlyRtdbDevice(e,t,n){if(!this.rtdbPresence||!this.rtdbScope||t.online!==true||E(this.rtdbPresenceMap[e]))return false;let r=this.toMillis(t.updatedAt)??this.toMillis(t.lastSeenAt)??this.toMillis(t.createdAt);return typeof r!="number"?false:r+3e4<=n}async markStaleDeviceOffline(e,t,n){let r=typeof t.deviceId=="string"&&t.deviceId.trim().length>0?t.deviceId:e.id,s=e.ref?.path||r;if(!(!s||this.staleDeviceOfflineWrites.has(s))){this.staleDeviceOfflineWrites.add(s);try{let o=await this.hooks.resolveDeviceRef(r);if(!o)return;await updateDoc(o,{online:!1,updatedAt:serverTimestamp$1(),expiresAt:n+2592e6});}catch(o){console.warn("[BrowserDeviceDiscovery] failed to mark stale device offline:",o);}finally{this.staleDeviceOfflineWrites.delete(s);}}}isDeviceExpired(e,t){let n=this.toMillis(e.expiresAt);if(typeof n=="number")return n<=t;let r=e.online===true?3e5:2592e6,s=this.toMillis(e.updatedAt);if(typeof s=="number")return s+r<=t;let o=this.toMillis(e.lastSeenAt);return typeof o=="number"?o+r<=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 r=this.ensureDeviceWatchRtdb(e,t);this.deviceWatchSetup={scopeKey:t,promise:r};try{await r;}finally{this.deviceWatchSetup?.promise===r&&(this.deviceWatchSetup=null);}return}this.startFirestoreDeviceWatch(e,t);}startFirestoreDeviceWatch(e,t){let n=++this.deviceWatchGeneration;this.activeDeviceScopeKey=t,this.activeDeviceUnsubscribe=onSnapshot(query(e,limit(Le)),r=>{if(n!==this.deviceWatchGeneration)return;let s=Date.now();this.devicesById.clear();for(let o of r.docs){let a=this.toDevice(o,s);a&&this.devicesById.set(a.deviceId,a);}this.hasDeviceRosterSnapshot=true,this.emitDevicesToAll(),this.scheduleFreshnessRecheck(n);},r=>{if(n!==this.deviceWatchGeneration)return;let s=r?.code,o=String(r?.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:",r);});}async ensureDeviceWatchRtdb(e,t){let n=++this.deviceWatchGeneration;this.activeDeviceScopeKey=t;let r=null,s=null;for(let l=0;l<3;l+=1)try{r=await E$1(this.readDurableRosterDocuments(e,t),V.RTDB_ROSTER_READ_TIMEOUT_MS,()=>new Error("RTDB-backed device roster read timed out")),s=null;break}catch(d){if(s=d,n!==this.deviceWatchGeneration)return;await u(x$1(l+1,250,Number.MAX_SAFE_INTEGER));}if(!r)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(r,o),this.hasDeviceRosterSnapshot=true;let a=this.rtdbPresence,c=this.rtdbScope;this.rtdbUnsubscribe&&this.rtdbUnsubscribe();try{this.rtdbUnsubscribe=a.onPresenceChange(c,l=>{if(n!==this.deviceWatchGeneration)return;R("[BrowserDeviceDiscovery][rtdb] presence update",{generation:n,devices:Object.keys(l).length,online:Object.values(l).filter(u=>E(u)).length}),this.rtdbPresenceMap=l,this.hasRtdbPresenceSnapshot=!0;let d=[];for(let[u,p]of Object.entries(l)){let f=this.knownTicketVersions.get(u)??-1,h=this.devicesById.has(u),g=!!(p.ticket||p.nodeId);p.ticketVersion!==f?(this.knownTicketVersions.set(u,p.ticketVersion),!g&&(f!==-1||!h&&E(p))&&d.push(u)):!g&&!h&&E(p)&&d.push(u);}this.applyRtdbOverlay(),this.scheduleFreshnessRecheck(n),d.length>0&&this.refetchDeviceTickets(d,n);});}catch(l){if(n!==this.deviceWatchGeneration)return;throw new Error(`[BrowserDeviceDiscovery] RTDB presence subscription setup failed; refusing Firestore-only liveness fallback: ${l instanceof Error?l.message:String(l)}`)}this.activeDeviceUnsubscribe=()=>{this.rtdbUnsubscribe?.(),this.rtdbUnsubscribe=null;},this.emitDevicesToAll(),this.scheduleFreshnessRecheck(n);}replaceDevicesFromDocuments(e,t){this.devicesById.clear();for(let n of e){let r=this.toDevice(n,t);r&&this.devicesById.set(r.deviceId,r);}}applyRtdbOverlay(){let e=false;for(let[t,n]of this.devicesById){let r=this.rtdbPresenceMap[t];if(!r)continue;let s=this.mergeRtdbPresenceIntoDevice(t,n,r);s&&(e=this.upsertDeviceProjection(t,s)||e);}for(let[t,n]of Object.entries(this.rtdbPresenceMap)){if(this.devicesById.has(t)||!E(n))continue;let r=this.deviceFromRtdbPresence(t,n);r&&(e=this.upsertDeviceProjection(t,r)||e);}e&&this.emitDevicesToAll();}mergeRtdbPresenceIntoDevice(e,t,n){if(!n)return t??null;let r=E(n),s={...t??{},appTag:this.options.appTag,tag:this.options.appTag,deviceId:e,deviceName:n.deviceName??t?.deviceName??"Device",online:r,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:r,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:E(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 r=this.options.normalizeDevice(n,e);return r.deviceId?r:null}async refetchDeviceTickets(e,t){await Promise.allSettled(e.map(async n=>{try{if(await this.refreshDeviceForAutoConnect(n),t!==this.deviceWatchGeneration)return}catch(r){console.warn("[BrowserDeviceDiscovery] refetch device ticket failed:",r);}}));}};V.RTDB_ROSTER_READ_TIMEOUT_MS=5e3,V.DEVICE_FRESHNESS_RECHECK_MS=3e4;var fe=V;var he=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,r=new Set(e);for(let[s,o]of this.friendDeviceUnsubscribes)r.has(s)||(o(),this.friendDeviceUnsubscribes.delete(s),n.delete(s));for(let s of e){if(this.friendDeviceUnsubscribes.has(s))continue;let o=`apps/${this.ctx.appTag}/users/${s}/devices`,a=collection(this.firestore,o),c=onSnapshot(a,l=>{let d=[];l.forEach(u=>{let p=u.data();if(!p||p.kind!=="device"||!this.ctx.matchesTag(p))return;let f=this.ctx.normalizeDevice(p,u.id);f.online&&d.push(f);}),n.set(s,d),t(new Map(n));},l=>{console.warn("[BrowserFriendDiscovery] friend device watch failed:",{friendUid:s,message:l?.message,code:l?.code});});this.friendDeviceUnsubscribes.set(s,c);}return ()=>{for(let[,s]of this.friendDeviceUnsubscribes)s();this.friendDeviceUnsubscribes.clear();}}async updateFriendTicket(e){let t=await this.ctx.resolveOrCreateLocalDeviceRef();t&&await updateDoc(t,{friendTicket:e??null});}usesSpaceMode(){return this.ctx.usesSpaceMode?this.ctx.usesSpaceMode():(this.ctx.discoveryMode??"space")==="space"&&typeof this.ctx.apiKey=="string"&&this.ctx.apiKey.trim().length>0&&typeof this.ctx.spaceKey=="string"&&this.ctx.spaceKey.trim().length>0}};var An="createSignalingSession",bt=50,me=class{constructor(e){this.ctx=e;}async createSession(e){if(this.shouldUseHostedSessionCallable()){await this.createHostedSession(e);return}let t=await this.ctx.getSessionsCollectionRef();if(!t)throw new Error("createSession requires an active browser signaling namespace");let n=doc(t,e.connectionId),r=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??r,updatedAt:r,expiresAt:r+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 r=doc(n,this.ctx.parseScopedId(e)),s={};if(t&&typeof t=="object"){for(let[o,a]of Object.entries(t))if(a!==void 0){if(a===null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"){s[o]=a;continue}s[o]=JSON.stringify(a);}}Object.keys(s).length!==0&&(s.updatedAt=Date.now(),await updateDoc(r,s));}async sendMessage(e,t,n,r){let s=await this.ctx.getMessagesCollectionRef();if(!s)throw new Error("sendMessage requires an active browser signaling namespace");let o=this.createDocumentId(),a=doc(s,o),c=this.ctx.getCurrentUserId()??this.ctx.getLocalDeviceId(),l=this.ctx.getCurrentUserId();if(!l&&(this.ctx.discoveryMode??"space")!=="space")throw new Error("sendMessage requires an authenticated user in app-scoped signaling mode");let d=Date.now(),u=1440*60*1e3,p={appTag:this.ctx.appTag,senderId:c,targetId:e,payload:t,state:n??null,replyPayload:r??null,timestamp:d,expiresAt:d+u};return l&&(p.senderUserId=l,p.targetUserId=l),await setDoc(a,p),a.path}async pollMessages(e){let t=await this.ctx.getMessagesCollectionRef();if(!t)return [];let n=this.ctx.getCurrentUserId();if(!n&&(this.ctx.discoveryMode??"space")!=="space")return [];let r=n?[where("targetId","==",e),where("targetUserId","==",n),limit(50)]:[where("targetId","==",e),limit(50)],s=await getDocs(query(t,...r)),o=[];for(let a of s.docs){let c=a.data(),l=typeof c.senderId=="string"?c.senderId:"",d=typeof c.targetId=="string"?c.targetId:"",u=typeof c.payload=="string"?c.payload:"";!l||!d||!u||o.push({appTag:typeof c.appTag=="string"?c.appTag:this.ctx.appTag,senderId:l,targetId:d,senderUserId:typeof c.senderUserId=="string"?c.senderUserId:void 0,targetUserId:typeof c.targetUserId=="string"?c.targetUserId:void 0,payload:u,state:typeof c.state=="string"?c.state:void 0,replyPayload:typeof c.replyPayload=="string"?c.replyPayload:void 0,timestamp:this.ctx.toMillis(c.timestamp),expiresAt:this.ctx.toMillis(c.expiresAt),_documentId:a.id});}return o.sort((a,c)=>(a.timestamp??0)-(c.timestamp??0)),await Promise.allSettled(o.map(async a=>{await deleteDoc(doc(t,a._documentId));})),o.map(({_documentId:a,...c})=>c)}async subscribeSessions(e){let t=await this.ctx.getSessionsCollectionRef(),n=this.ctx.parseScopedId(e);if(!t||!n)return new ReadableStream({start(a){a.close();}});let r=null,s=null,o=false;return new ReadableStream({start:a=>{let c={initiator:new Set,target:new Set},l=new Map,d=(u,p)=>{if(o)return;let f=[];for(let h of p.docChanges()){let g=h.doc.id;if(h.type==="removed"){c[u].delete(g),!(c.initiator.has(g)||c.target.has(g))&&l.delete(g)&&f.push({type:"removed",sessionId:g});continue}let v=this.toSession(h.doc.id,h.doc.data());if(!v)continue;c[u].add(g);let w=l.has(g);l.set(g,v),f.push({type:w?"modified":"added",session:v});}f.length>0&&a.enqueue(f);};r=onSnapshot(query(t,where("initiatorDeviceId","==",n),limit(bt)),u=>d("initiator",u),u=>{o||a.error(u);}),s=onSnapshot(query(t,where("targetDeviceId","==",n),limit(bt)),u=>d("target",u),u=>{o||a.error(u);});},cancel:()=>{o=true,r?.(),s?.(),r=null,s=null;}})}shouldUseHostedSessionCallable(){return (this.ctx.discoveryMode??"space")!=="space"&&!!this.ctx.getCurrentUserId()}async createHostedSession(e){await httpsCallable(getFunctions(this.ctx.app),An)({...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:"",r=typeof t.targetDeviceId=="string"?t.targetDeviceId:"";return !n&&!r?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:r,connectionType:typeof t.connectionType=="string"?t.connectionType:void 0,offer:this.parseMaybeJson(t.offer),offerE2ee:this.parseMaybeJson(t.offerE2ee),answer:this.parseMaybeJson(t.answer),answerE2ee:this.parseMaybeJson(t.answerE2ee),iceCandidates:Array.isArray(t.iceCandidates)?t.iceCandidates:[],initiatorNodeId:typeof t.initiatorNodeId=="string"?t.initiatorNodeId:void 0,targetNodeId:typeof t.targetNodeId=="string"?t.targetNodeId:void 0,initiatorEndpointAddr:typeof t.initiatorEndpointAddr=="string"?t.initiatorEndpointAddr:void 0,targetEndpointAddr:typeof t.targetEndpointAddr=="string"?t.targetEndpointAddr:void 0,intent:typeof t.intent=="string"?t.intent:void 0,appTag:typeof t.appTag=="string"?t.appTag:this.ctx.appTag,createdAt:this.ctx.toMillis(t.createdAt),expiresAt:this.ctx.toMillis(t.expiresAt),state:typeof t.state=="string"?t.state:""}}parseMaybeJson(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}createDocumentId(){return `${Date.now()}-${Math.random().toString(36).slice(2,10)}`}};function xn(i){return typeof i=="object"&&i!==null&&"code"in i&&i.code==="not-found"}var be=class{constructor(e){this.options=e;this.rtdbPresence=null;this.namespaceRootPromise=null;this.resolvedDeviceDocIds=new Map;this.firestore=getFirestore(e.app);try{let t=globalThis?.__OPENRTC_FIRESTORE_EMULATOR_HOST__,n=typeof t=="string"?t.trim():"";if(n){let[r,s]=n.split(":"),o=(r??"").trim()||"127.0.0.1",a=Number(s??8082);try{connectFirestoreEmulator(this.firestore,o,a);}catch{}}else {let r=import.meta?.env;if(!!r?.DEV&&String(r?.VITE_USE_EMULATORS)==="true"){let o=String(r?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",a=Number(r?.VITE_OPENRTC_FIRESTORE_EMULATOR_PORT??8082);try{connectFirestoreEmulator(this.firestore,o,a);}catch{}}}}catch{}this.discovery=new fe({options:this.options,firestore:this.firestore,getDevicesCollectionRef:()=>this.getDevicesCollectionRef(),resolveDeviceRef:t=>this.resolveDeviceRef(t)}),this.friendDiscovery=new he({app:e.app,appTag:e.appTag,discoveryMode:e.discoveryMode,apiKey:e.apiKey,spaceKey:e.spaceKey,matchesTag:e.matchesTag,normalizeDevice:e.normalizeDevice,resolveOrCreateLocalDeviceRef:()=>this.resolveOrCreateLocalDeviceRef(),usesSpaceMode:()=>this.usesSpaceMode()}),this.sessionSignaling=new me({app:e.app,appTag:e.appTag,discoveryMode:e.discoveryMode,getCurrentUserId:()=>e.getCurrentUserId(),getLocalDeviceId:()=>e.getLocalDeviceId(),getSessionsCollectionRef:()=>this.getSessionsCollectionRef(),getMessagesCollectionRef:()=>this.getMessagesCollectionRef(),parseScopedId:t=>this.parseScopedId(t),toMillis:t=>this.toMillis(t)});}setRtdbPresence(e,t){this.rtdbPresence=e,this.discovery.setRtdbPresence(e,t);}getRtdbPresence(){return this.rtdbPresence}stopRtdbPresence(){this.rtdbPresence=null,this.discovery.stopRtdbPresence();}searchDevices(e){return this.discovery.searchDevices(e)}listDevices(e){return this.discovery.listDevices(e)}subscribeDevices(){return this.discovery.subscribeDevices()}onDevicesChange(e,t){return this.discovery.onDevicesChange(e,t)}async handleScopeChange(){await this.discovery.handleScopeChange();}stopAuthScopedActivity(){this.discovery.stopAuthScopedActivity();}async updatePresence(e,t,n,r,s,o){let a=await this.resolveOrCreateLocalDeviceRef();if(!a)return;let c=this.options.getLocalDeviceId(),l=Date.now(),d=o?.trim()||this.options.getDefaultDeviceName(),u=this.options.getCurrentUserId(),p=n?l+Math.max(0,Math.trunc(r)):l+2592e6,f=await getDoc(a).catch(()=>null),h={appTag:this.options.appTag,tag:this.options.appTag,kind:"device",deviceId:c,deviceName:d,nodeId:e,platformType:"web",online:n,ticket:t,metadata:s??null,capabilities:{canHost:false,canSync:false,readOnly:false},lastSeenAt:serverTimestamp$1(),updatedAt:serverTimestamp$1(),expiresAt:p};u&&(h.userId=u),f?.exists()||(h.createdAt=serverTimestamp$1()),await setDoc(a,h,{merge:true});}async setOffline(e){let t=await this.resolveOrCreateLocalDeviceRef();if(!t)return;let n={appTag:this.options.appTag,tag:this.options.appTag,kind:"device",deviceId:this.options.getLocalDeviceId(),deviceName:this.options.getDefaultDeviceName(),nodeId:e,platformType:"web",online:false,updatedAt:serverTimestamp$1(),lastSeenAt:serverTimestamp$1(),expiresAt:Date.now()+2592e6},r=this.options.getCurrentUserId();r&&(n.userId=r);try{await updateDoc(t,n);}catch(s){if(!xn(s))throw s}}async cleanupStaleDevices(){await this.discovery.cleanupStaleDevices();}async updateDevice(e,t){let n=await this.resolveDeviceRef(e);if(!n)throw new Error("updateDevice requires a known device record");let r={updatedAt:serverTimestamp$1()};typeof t.deviceName=="string"&&(r.deviceName=t.deviceName),t.capabilities&&(r.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"&&(r.metadata=t.metadata),await updateDoc(n,r);}async deleteDevice(e){let t=await this.resolveDeviceRef(e);t&&await deleteDoc(t);}async createSession(e){await this.sessionSignaling.createSession(e);}async updateSession(e,t){await this.sessionSignaling.updateSession(e,t);}async sendMessage(e,t,n,r){return this.sessionSignaling.sendMessage(e,t,n,r)}async pollMessages(e){return this.sessionSignaling.pollMessages(e)}async subscribeSessions(e){return this.sessionSignaling.subscribeSessions(e)}refreshDeviceForAutoConnect(e){return this.discovery.refreshDeviceForAutoConnect(e)}toMillis(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Date.parse(e);return Number.isNaN(t)?void 0:t}if(e instanceof Date)return e.getTime();if(e&&typeof e=="object"&&typeof e.toMillis=="function")return e.toMillis()}async getDevicesCollectionRef(){let e=await this.getDevicesCollectionPath();return e?collection(this.firestore,e):null}async getSessionsCollectionRef(){let e=await this.getNamespaceRoot();return e?collection(this.firestore,`${e}/sessions`):null}async getMessagesCollectionRef(){let e=await this.getNamespaceRoot();return e?collection(this.firestore,`${e}/messages`):null}async getDevicesCollectionPath(){let e=await this.getNamespaceRoot();if(!e)return null;if(this.usesSpaceMode())return `${e}/devices`;let t=this.options.getDiscoveryScopeId();return t?`${e}/users/${t}/devices`:null}async getNamespaceRoot(){if(this.usesSpaceMode()){if(!this.namespaceRootPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";this.namespaceRootPromise=b(e,t).then(n=>`spaces/${n}`);}return this.namespaceRootPromise}return `apps/${this.options.appTag}`}usesSpaceMode(){return (this.options.discoveryMode??"space")==="space"&&typeof this.options.apiKey=="string"&&this.options.apiKey.trim().length>0&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0}parseScopedId(e){let t=e.split("::");return t.length===2?t[1]:e}async resolveOrCreateLocalDeviceRef(){let e=await this.getDevicesCollectionRef();return e?doc(e,this.options.getLocalDeviceId()):null}async resolveDeviceRef(e){let t=await this.getDevicesCollectionRef();if(!t)return null;let n=e.trim();if(!n)return null;let r=this.resolvedDeviceDocIds.get(n);if(r)return doc(t,r);let s=this.discovery.resolveKnownDeviceId(n);if(s)return this.resolvedDeviceDocIds.set(n,s),doc(t,s);let o=doc(t,n);if((await getDoc(o)).exists())return this.resolvedDeviceDocIds.set(n,n),o;let a=await getDocs(query(t,where("deviceId","==",n),limit(1)));if(!a.empty){let l=a.docs[0].id;return this.resolvedDeviceDocIds.set(n,l),a.docs[0].ref}let c=await getDocs(query(t,where("nodeId","==",n),limit(1)));if(!c.empty){let l=c.docs[0].id;return this.resolvedDeviceDocIds.set(n,l),c.docs[0].ref}return null}watchFriendDevices(e,t){return this.friendDiscovery.watchFriendDevices(e,t)}updateFriendTicket(e){return this.friendDiscovery.updateFriendTicket(e)}};var A=class A{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(),r=`${e}::${n}`;this.startedAutoConnectKey===r&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.startedAutoConnectKey=r,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(r=>({deviceId:String(r.deviceId??"").trim(),nodeId:typeof r.nodeId=="string"&&r.nodeId.trim()||null,ticket:typeof r.ticket=="string"&&r.ticket.trim()||null,online:r.online===true,sessionId:typeof r.sessionId=="string"&&r.sessionId.trim()||null,excludedPeers:Array.isArray(r.excludedPeers)?[...new Set(r.excludedPeers.map(s=>String(s??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(r=>r.deviceId.length>0).sort((r,s)=>r.deviceId.localeCompare(s.deviceId));this.desiredPeersByDeviceId=new Map(t.map(r=>[r.deviceId,r]));let n=JSON.stringify(t);n!==this.desiredPeerSignature&&(this.desiredPeerSignature=n,this.queuedDesiredPeers=t,this.flushDesiredPeerSubmission());}resolveDesiredPeer(e,t){let n=typeof e=="string"?e.trim():"",r=typeof t=="string"?t.trim():"";if(n){let s=this.desiredPeersByDeviceId.get(n);if(s&&(!r||!s.nodeId||s.nodeId===r))return s}return r?Array.from(this.desiredPeersByDeviceId.values()).find(s=>s.nodeId===r)??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 r=>{if(this.startedAutoConnectKey===e){if(!r||typeof r.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 r.submit_browser_desired_peers(n,JSON.stringify(t));}}).catch(r=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:n,error:r});}).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,r,s){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let o=++this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:r,metadata:s,deviceName:n};let a=this.deps.resolveWebLogicalDeviceId(),c=async l=>{let d=await this.deps.withWebPresenceMetadata(s,a),u=()=>o===this.presenceStartGeneration&&this.presenceState!==null;if(!u())return;if(!this.deps.isRtdbPresenceDisabledForSession()&&l&&a){let f=false,h=false,g=null,v=null,w=(b,I)=>{this.scheduleDurableRosterRetry(a,o,10080*60*1e3,b,I);},F=(b,I)=>{u()&&(this.deps.isRtdbPresenceDisabledForSession()||this.scheduleRtdbPresenceRetry(l,a,o,b,I));};g=setTimeout(()=>{f||w("initial durable roster write timed out");},A.INITIAL_PRESENCE_WRITE_TIMEOUT_MS),v=setTimeout(()=>{h||F("RTDB presence register timed out");},A.RTDB_PRESENCE_REGISTER_TIMEOUT_MS),this.deps.updatePresence(t,r,false,10080*60*1e3,d,n).then(()=>{f=true,g&&(clearTimeout(g),g=null),this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(b=>{g&&(clearTimeout(g),g=null),w("initial durable roster write failed",b);}),this.deps.registerRtdbPresence(l,a,this.deps.getRtdbTicketVersion(),{ticket:r,nodeId:t,deviceName:n,platformType:"web",metadata:d,excludedPeers:this.currentExcludedPeersSnapshot()}).then(()=>{h=true,this.rtdbPresenceRetryAttempt=0,this.clearRtdbPresenceRetryTimer(),v&&(clearTimeout(v),v=null);}).catch(b=>{v&&(clearTimeout(v),v=null),F("RTDB presence register failed",b);});return}let p=X.browserIdentity.ephemeralDeviceIdTtlMs;this.deps.updatePresence(t,r,false,p,d,n).then(()=>{this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(f=>{this.scheduleDurableRosterRetry(a,o,p,"durable roster write failed without RTDB presence",f);});};if(this.deps.resolveRtdbScope){this.deps.resolveRtdbScope(e).then(l=>c(l));return}c(this.deps.buildRtdbScope(e));}clearDurablePresenceRetryTimer(){this.durablePresenceRetryTimer&&(clearTimeout(this.durablePresenceRetryTimer),this.durablePresenceRetryTimer=null);}scheduleDurableRosterRetry(e,t,n,r,s){if(t!==this.presenceStartGeneration||this.presenceState===null||this.durablePresenceRetryTimer)return;let o=this.durablePresenceRetryAttempt+1;this.durablePresenceRetryAttempt=o;let a=Math.min(A.RTDB_PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,o-1),A.RTDB_PRESENCE_RETRY_MAX_DELAY_MS),c=(o*17%21-10)/100,l=Math.max(A.RTDB_PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${r}; retrying durable roster registration in ${l}ms without Firestore heartbeat`,s),this.durablePresenceRetryTimer=setTimeout(()=>{this.durablePresenceRetryTimer=null,!(t!==this.presenceStartGeneration||this.presenceState===null)&&(async()=>{if(this.presenceState===null)return;let d=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,e);t!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(this.presenceState.localNodeId,this.presenceState.ticket,false,n,d,this.presenceState.deviceName);})().then(()=>{this.durablePresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer();}).catch(d=>{this.scheduleDurableRosterRetry(e,t,n,"durable roster registration retry failed",d);});},l);}clearRtdbPresenceRetryTimer(){this.rtdbPresenceRetryTimer&&(clearTimeout(this.rtdbPresenceRetryTimer),this.rtdbPresenceRetryTimer=null);}scheduleRtdbPresenceRetry(e,t,n,r,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(A.RTDB_PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,o-1),A.RTDB_PRESENCE_RETRY_MAX_DELAY_MS),c=(o*29%21-10)/100,l=Math.max(A.RTDB_PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${r}; retrying RTDB presence in ${l}ms without Firestore heartbeat fallback`,s),this.rtdbPresenceRetryTimer=setTimeout(()=>{this.rtdbPresenceRetryTimer=null,!(n!==this.presenceStartGeneration||this.presenceState===null||this.deps.isRtdbPresenceDisabledForSession())&&(async()=>{if(this.presenceState===null)return;let d=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,t);n!==this.presenceStartGeneration||this.presenceState===null||this.deps.isRtdbPresenceDisabledForSession()||await this.deps.registerRtdbPresence(e,t,this.deps.getRtdbTicketVersion(),{ticket:this.presenceState.ticket,nodeId:this.presenceState.localNodeId,deviceName:this.presenceState.deviceName,platformType:"web",metadata:d,excludedPeers:this.currentExcludedPeersSnapshot()});})().then(()=>{this.rtdbPresenceRetryAttempt=0;}).catch(d=>{this.scheduleRtdbPresenceRetry(e,t,n,"RTDB presence retry failed",d);});},l);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}async republishRtdbPresence(e){let t=this.presenceState;if(!t||this.deps.isRtdbPresenceDisabledForSession())return;let n=this.deps.resolveWebLogicalDeviceId();if(!n)return;let r=this.deps.resolveRtdbScope?await this.deps.resolveRtdbScope(t.userId):this.deps.buildRtdbScope(t.userId);if(!r)return;let s=await this.deps.withWebPresenceMetadata(t.metadata,n);await this.deps.registerRtdbPresence(r,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;}};A.RTDB_PRESENCE_REGISTER_TIMEOUT_MS=5e3,A.INITIAL_PRESENCE_WRITE_TIMEOUT_MS=5e3,A.RTDB_PRESENCE_RETRY_MIN_DELAY_MS=2e3,A.RTDB_PRESENCE_RETRY_MAX_DELAY_MS=6e4;var Se=A;var Re="trustedDevice",Nn="plutonium:e2ee:identity:v1",Fn="plutonium:e2ee:identity:session:v1",Bn="openrtc-trust",q="identity",Ct="transport-trust:v1",Ln=1,_=null,ie=null;function M(i){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function re(i){let e="";for(let t=0;t<i.length;t+=1)e+=String.fromCharCode(i[t]);return btoa(e)}async function Et(i){let e=await crypto.subtle.digest("SHA-256",i),t=new Uint8Array(e);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}function On(){return typeof sessionStorage>"u"?null:sessionStorage}function Un(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(Nn);}catch{}}var Ie=null;async function At(){return Ie||(Ie=(async()=>{let i=globalThis.crypto?.subtle;if(!i||typeof i.generateKey!="function")return false;try{let e=await i.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),Ie)}async function Wn(i){let e=await crypto.subtle.exportKey("raw",i);return new Uint8Array(e)}function Hn(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function _t(){let i=Hn();return i?new Promise(e=>{let t;try{t=i.open(Bn,1);}catch{e(null);return}t.onupgradeneeded=()=>{let n=t.result;n.objectStoreNames.contains(q)||n.createObjectStore(q);},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);}):Promise.resolve(null)}async function Gn(){let i=await _t();if(!i)return null;try{return await new Promise(e=>{let r=i.transaction(q,"readonly").objectStore(q).get(Ct);r.onsuccess=()=>{let s=r.result;e(s&&s.privateKey&&s.publicKey?s:null);},r.onerror=()=>e(null);})}catch{return null}finally{i.close();}}async function Kn(i){let e=await _t();if(!e)return false;try{return await new Promise(t=>{let n=e.transaction(q,"readwrite");n.objectStore(q).put(i,Ct),n.oncomplete=()=>t(!0),n.onerror=()=>t(!1),n.onabort=()=>t(!1);})}catch{return false}finally{e.close();}}async function kt(i,e){let t=await Wn(i.publicKey),n=await Et(t),r=i.privateKey;return {publicKey:t,fingerprint:n,backend:"webcrypto-nonextractable",durable:e,privateKey:r,async signChallenge(s){let o=await crypto.subtle.sign({name:"Ed25519"},r,M(s));return re(new Uint8Array(o))}}}function zn(i,e,t){let n=i.secretKey;return {publicKey:i.publicKey,secretKey:n,fingerprint:e,backend:"tweetnacl",durable:t,async signChallenge(r){return Vn(r,n)}}}function $i(i=32){let e=crypto.getRandomValues(new Uint8Array(i));return re(e)}function Vn(i,e){let t=we.sign.detached(M(i),e);return re(t)}function jn(i,e,t){try{return we.sign.detached.verify(M(i),M(e),M(t))}catch{return false}}async function Xi(i,e,t){let n=globalThis.crypto?.subtle;if(n&&typeof n.importKey=="function"&&typeof n.verify=="function")try{let r=await n.importKey("raw",M(t),{name:"Ed25519"},!1,["verify"]);return await n.verify({name:"Ed25519"},r,M(e),M(i))}catch{}return jn(i,e,t)}function Ji(i){return re(i)}function Qi(i){if(!i||!i.trim())return null;try{let e=JSON.parse(i),t=e&&typeof e=="object"&&!Array.isArray(e)?e[Re]:null;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,r=typeof n.version=="number"?n.version:null,s=typeof n.identityPublicKey=="string"?n.identityPublicKey:null,o=typeof n.identityFingerprint=="string"?n.identityFingerprint:null;return !r||!s||!o?null:{version:r,identityPublicKey:s,identityFingerprint:o}}catch{return null}}async function qn(){let i=await Qn().catch(()=>null);return i?{version:Ln,identityPublicKey:re(i.publicKey),identityFingerprint:i.fingerprint}:null}async function We(i){let e=await qn();if(!e)return i??void 0;let t=typeof i=="string"?i.trim():"";if(!t)return JSON.stringify({[Re]:e});try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return JSON.stringify({...n,[Re]:e})}catch{}return JSON.stringify({metadata:i,[Re]:e})}function Yn(){if(typeof window>"u")return null;let i=window.__TAURI_INTERNALS__;return !i||typeof i.invoke!="function"?null:i.invoke.bind(i)}async function $n(){if(!a()||typeof window>"u"||/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||""))return null;let i=Yn();if(!i)return null;try{let e=await i("openrtc_get_transport_trust_identity");return {publicKey:M(e.publicKeyBase64),fingerprint:e.fingerprint,backend:"native-keychain",durable:!0,async signChallenge(n){return i("openrtc_sign_transport_trust_challenge",{challenge:n})}}}catch{return null}}function Xn(){let i=On();i&&i.removeItem(Fn);}async function Jn(){if(Un(),Xn(),_)return _;let i=await $n();if(i)return _=i,_;if(await At()){let e=await Gn();if(e)return _=await kt(e,true),_}return null}async function Qn(i={}){let e=await Jn();if(e)return e;if(ie)return ie;let t=Zn(i);ie=t;try{return await t}finally{ie===t&&(ie=null);}}async function Zn(i){if(_)return _;let e=i.ephemeral===true;if(await At())try{let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),n=!1;return e||(n=await Kn(t)),_=await kt(t,n),_}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=we.sign.keyPair(),n=await Et(v(t.publicKey));return _=zn(t,n,!1),_}catch{return null}}function se(i){return !i||typeof i!="object"?{}:i instanceof Map?Object.fromEntries(i):i}function He(i){let e=se(i),t=se(e.device);if(!Object.keys(t).length)return e;let n={...t,...e};return delete n.device,n}function y(i,...e){for(let t of e){let n=i[t];if(typeof n=="string"&&n.trim().length>0)return n}}function H(i,...e){for(let t of e){let n=i[t];if(typeof n=="boolean")return n}}function S(i,...e){for(let t of e){let n=i[t];if(typeof n=="number"&&Number.isFinite(n))return n}}function N(i){if(typeof i=="number"&&Number.isFinite(i))return i;if(i instanceof Date){let e=i.getTime();return Number.isFinite(e)?e:void 0}if(typeof i=="string"){let e=Date.parse(i);return Number.isFinite(e)?e:void 0}if(i&&typeof i=="object"){let e=i;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 Ge(...i){let e=i.map(N).filter(t=>typeof t=="number"&&Number.isFinite(t));return e.length?Math.max(...e):void 0}function Ke(i){if(typeof i!="string")return;let e=i.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Mt(i){let e=Ke("presenceStatus"in i?i.presenceStatus:void 0),t="presenceUpdatedAt"in i?N(i.presenceUpdatedAt):void 0,n="presenceExpiresAt"in i?N(i.presenceExpiresAt):void 0,r=t??Ge(i.lastSeenAt,i.updatedAt,i.createdAt),s=n??N(i.expiresAt),o=e;o||(i.online?r!==void 0&&r+3e5<=Date.now()?o="idle":o="online":o="offline");let a=typeof i.ticket=="string"?i.ticket.trim():"",c="connectable"in i&&typeof i.connectable=="boolean"?i.connectable:o==="online"&&a.length>0;return {presenceStatus:o,presenceUpdatedAt:r,presenceExpiresAt:s,connectable:c}}function xt(i){return b$1(i)}function Y(i,...e){return xt(y(i,...e))}function oe(i){if(!Array.isArray(i))return;let e=Array.from(new Set(i.map(xt).filter(t=>!!t)));return e.length?e:void 0}function Nt(i){return (i.discoveryMode??"space")==="space"&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof i.spaceKey=="string"&&i.spaceKey.trim().length>0}function Ft(i,e,t){return t?true:(typeof i.appTag=="string"?i.appTag:typeof i.tag=="string"?i.tag:void 0)===e}function ze(i,e){let t=He(i),n=y(t,"deviceId","device_id")||e||"",r=y(t,"nodeId","node_id")||"",s=y(t,"ticket")||"";return {deviceId:n,deviceName:y(t,"deviceName","device_name")||"Unknown Device",online:!!t.online,ticket:s,presenceStatus:Ke(y(t,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:S(t,"presenceUpdatedAt","presence_updated_at")??Ge(t.presenceUpdatedAt,t.presence_updated_at,t.lastSeenAt,t.last_seen_at,t.updatedAt,t.updated_at,t.createdAt,t.created_at),presenceExpiresAt:S(t,"presenceExpiresAt","presence_expires_at")??N(t.presenceExpiresAt??t.presence_expires_at)??N(t.expiresAt??t.expires_at),connectable:H(t,"connectable"),kind:y(t,"kind"),nodeId:r||void 0,platformType:y(t,"platformType","platform_type"),capabilities:t.capabilities||void 0,sessionId:y(t,"sessionId","session_id"),userId:y(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:y(t,"metadata"),excludedPeers:Ve(t.excludedPeers??t.excluded_peers),availableTransports:oe(t.availableTransports??t.available_transports),transports:oe(t.transports)}}function Ve(i){return Array.isArray(i)?i.filter(e=>typeof e=="string"):[]}function ei(i){let e=Mt(i);return {...i,...e,connectionStatus:"connectionStatus"in i&&typeof i.connectionStatus=="string"?i.connectionStatus:i.online?"online":"disconnected",settledReady:"settledReady"in i&&typeof i.settledReady=="boolean"?i.settledReady:false,readinessState:"readinessState"in i&&typeof i.readinessState=="string"?i.readinessState:void 0,readinessReason:"readinessReason"in i&&typeof i.readinessReason=="string"?i.readinessReason:void 0,peerHealth:"peerHealth"in i&&typeof i.peerHealth=="string"?i.peerHealth:"unknown",peerId:"peerId"in i&&typeof i.peerId=="string"?i.peerId:void 0,promotionEligible:"promotionEligible"in i&&typeof i.promotionEligible=="boolean"?i.promotionEligible:true,scopes:"scopes"in i?Ve(i.scopes):[],connectionId:"connectionId"in i&&typeof i.connectionId=="string"?i.connectionId:void 0,deviceIdHint:"deviceIdHint"in i&&typeof i.deviceIdHint=="string"?i.deviceIdHint:void 0,activeTransportStableId:"activeTransportStableId"in i&&typeof i.activeTransportStableId=="number"?i.activeTransportStableId:"activeTransportStableId"in i?i.activeTransportStableId??null:void 0,transportGeneration:"transportGeneration"in i&&typeof i.transportGeneration=="number"?i.transportGeneration:void 0,routeGeneration:"routeGeneration"in i&&typeof i.routeGeneration=="number"?i.routeGeneration:void 0,activeTransport:"activeTransport"in i?i.activeTransport:void 0,parallelTransport:"parallelTransport"in i?i.parallelTransport:void 0,availableTransports:"availableTransports"in i?oe(i.availableTransports):"transports"in i?oe(i.transports):void 0}}function ti(i,e,t){let n=t?t({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):i.promotionEligible??true;if(!n)return {...i,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:n,scopes:e.scopes?.length?[...e.scopes]:i.scopes,connectionId:e.activeConnectionId??i.connectionId,deviceIdHint:e.deviceIdHint??i.deviceIdHint,activeTransportStableId:e.activeTransportStableId??i.activeTransportStableId,transportGeneration:e.transportGeneration??i.transportGeneration,routeGeneration:e.routeGeneration??i.routeGeneration,activeTransport:e.activeTransport??i.activeTransport,parallelTransport:e.parallelTransport===void 0?i.parallelTransport:e.parallelTransport,readinessReason:e.readinessReason??i.readinessReason};let r=e.status??i.connectionStatus,s=typeof r=="string"?r.trim().toLowerCase():"",o=s==="failed"||s==="closed"||s==="disconnected",c=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true;if((i.settledReady===true||i.readinessState==="routable")&&!o&&!c)return {...i,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:n,scopes:e.scopes?.length?[...e.scopes]:i.scopes,connectionId:e.activeConnectionId??i.connectionId,deviceIdHint:e.deviceIdHint??i.deviceIdHint,activeTransportStableId:e.activeTransportStableId??i.activeTransportStableId,transportGeneration:e.transportGeneration??i.transportGeneration,routeGeneration:e.routeGeneration??i.routeGeneration,activeTransport:e.activeTransport??i.activeTransport,parallelTransport:e.parallelTransport===void 0?i.parallelTransport:e.parallelTransport,readinessReason:e.readinessReason??i.readinessReason};let d=o?false:c,u=c&&!o&&(s==="connecting"||s==="connected")?"connected":r,p=c?"routable":e.readinessState??i.readinessState,f=d?e.readinessReason??"peer-session-settled":e.readinessReason??i.readinessReason;return {...i,connectionStatus:u,settledReady:d,readinessState:p,readinessReason:f,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:n,scopes:e.scopes?.length?[...e.scopes]:i.scopes,connectionId:e.activeConnectionId??i.connectionId,deviceIdHint:e.deviceIdHint??i.deviceIdHint,activeTransportStableId:e.activeTransportStableId??i.activeTransportStableId,transportGeneration:e.transportGeneration??i.transportGeneration,routeGeneration:e.routeGeneration??i.routeGeneration,activeTransport:e.activeTransport??i.activeTransport,parallelTransport:e.parallelTransport===void 0?i.parallelTransport:e.parallelTransport}}function ni(i,e){if(e.promotionEligible===false)return {...i,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:false,connectionId:e.connectionId??i.connectionId,deviceIdHint:e.deviceIdHint??i.deviceIdHint,activeTransportStableId:e.activeTransportStableId??i.activeTransportStableId,transportGeneration:e.transportGeneration??i.transportGeneration,routeGeneration:e.routeGeneration??i.routeGeneration,activeTransport:e.activeTransport??i.activeTransport,parallelTransport:e.parallelTransport===void 0?i.parallelTransport:e.parallelTransport,scopes:e.scopes?.length?[...e.scopes]:i.scopes};let t=e.status??i.connectionStatus,n=typeof t=="string"?t.trim().toLowerCase():"",r=n==="failed"||n==="closed"||n==="disconnected",s=i.settledReady===true||i.readinessState==="routable",o=e.routable===false;if(s&&r&&!o)return {...i,peerHealth:i.peerHealth??e.health,peerId:i.peerId??e.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,connectionId:i.connectionId??e.connectionId,deviceIdHint:i.deviceIdHint??e.deviceIdHint,scopes:i.scopes?.length?i.scopes:e.scopes??i.scopes};if(s&&r)return {...i,connectionStatus:t,settledReady:false,readinessState:void 0,readinessReason:e.error??i.readinessReason,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,connectionId:e.connectionId??i.connectionId,deviceIdHint:e.deviceIdHint??i.deviceIdHint,activeTransportStableId:null,activeTransport:void 0,parallelTransport:void 0,scopes:e.scopes?.length?[...e.scopes]:i.scopes};let a=e.routable===true||e.protocolState==="routable";if(s&&!r&&!a)return {...i,peerHealth:i.peerHealth??e.health,peerId:i.peerId??e.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,connectionId:i.connectionId??e.connectionId,deviceIdHint:i.deviceIdHint??e.deviceIdHint,activeTransportStableId:i.activeTransportStableId??e.activeTransportStableId,transportGeneration:i.transportGeneration??e.transportGeneration,routeGeneration:i.routeGeneration??e.routeGeneration,activeTransport:i.activeTransport??e.activeTransport,parallelTransport:i.parallelTransport===void 0?e.parallelTransport:i.parallelTransport,scopes:i.scopes?.length?i.scopes:e.scopes??i.scopes};let c=e.transportState==="connected"&&e.health==="healthy",l=r?false:a,d=!r&&(a||c)&&(n==="connecting"||n==="connected"||e.transportState==="connected")?"connected":t,u=l?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??i.readinessState??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),p=l?i.readinessReason??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??i.readinessReason??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...i,connectionStatus:d,settledReady:l,readinessState:u,readinessReason:p,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,connectionId:e.connectionId??i.connectionId,deviceIdHint:e.deviceIdHint??i.deviceIdHint,activeTransportStableId:e.activeTransportStableId??i.activeTransportStableId,transportGeneration:e.transportGeneration??i.transportGeneration,routeGeneration:e.routeGeneration??i.routeGeneration,activeTransport:e.activeTransport??i.activeTransport,parallelTransport:e.parallelTransport===void 0?i.parallelTransport:e.parallelTransport,scopes:e.scopes?.length?[...e.scopes]:i.scopes}}function ii(i){let{device:e,session:t=null,peer:n=null,isPromotionEligible:r}=i,s=ei(e);return t&&(s=ti(s,t,r)),n&&(s=ni(s,n)),s}function Bt(i){let e=He(i),t=ze(e),n=Ke(y(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=Mt({...t,...n?{presenceStatus:n}:{},presenceUpdatedAt:S(e,"presenceUpdatedAt","presence_updated_at")??Ge(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:S(e,"presenceExpiresAt","presence_expires_at")??N(e.presenceExpiresAt??e.presence_expires_at)??N(e.expiresAt??e.expires_at),connectable:H(e,"connectable")}),s={...t,...r,connectionStatus:y(e,"connectionStatus","connection_status")||"disconnected",settledReady:H(e,"settledReady","settled_ready")??false,readinessState:y(e,"readinessState","readiness_state")??void 0,readinessReason:y(e,"readinessReason","readiness_reason")??void 0,peerHealth:y(e,"peerHealth","peer_health")||"unknown",peerId:y(e,"peerId","peer_id"),scopes:Ve(e.scopes),connectionId:y(e,"connectionId","connection_id"),deviceIdHint:y(e,"deviceIdHint","device_id_hint"),activeTransportStableId:S(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:S(e,"transportGeneration","transport_generation")??void 0,routeGeneration:S(e,"routeGeneration","route_generation")??void 0,activeTransport:Y(e,"activeTransport","active_transport"),parallelTransport:Y(e,"parallelTransport","parallel_transport")??null,availableTransports:oe(e.availableTransports??e.available_transports)};return ii({device:s})}function Lt(i){let e=He(i);return {peerId:y(e,"peerId","peer_id")||"",deviceId:y(e,"deviceId","device_id"),deviceIdHint:y(e,"deviceIdHint","device_id_hint"),nodeId:y(e,"nodeId","node_id"),activeConnectionId:y(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:y(e,"status")||"disconnected",health:y(e,"health")||"unknown",settledReady:H(e,"settledReady","settled_ready")??false,readinessState:y(e,"readinessState","readiness_state")??void 0,activeTransportStableId:S(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:S(e,"transportGeneration","transport_generation")??void 0,routeGeneration:S(e,"routeGeneration","route_generation")??void 0,activeTransport:Y(e,"activeTransport","active_transport"),parallelTransport:Y(e,"parallelTransport","parallel_transport")??null,replacementPending:H(e,"replacementPending","replacement_pending")??void 0,lastLifecycleTransitionAtMs:S(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:y(e,"readinessReason","readiness_reason")??void 0,transitionCount:S(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:S(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:S(e,"replacementCount","replacement_count")??void 0,retireCount:S(e,"retireCount","retire_count")??void 0,lastDisconnectReason:y(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:y(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:y(e,"error")}}function tr(i){let e=se(i);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 nr(i){let e=se(i);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 ri(i){switch(i){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function Ot(i){let e=i.activeConnectionId||i.candidateConnectionIds[0]||null;if(!e)return null;let t=ri(i.status),n=t==="connected"?"connected":t==="connecting"?"connecting":"closed",r=t==="connected"?i.settledReady?"routable":"transport-only":t==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:i.deviceId??null,deviceIdHint:i.deviceIdHint??null,remoteNodeId:i.nodeId??null,state:t,transportState:n,protocolState:r,routable:!!i.settledReady,readinessState:i.readinessState,readinessReason:i.readinessReason,transportGeneration:i.transportGeneration,routeGeneration:i.routeGeneration,activeTransportStableId:i.activeTransportStableId,activeTransport:i.activeTransport,parallelTransport:i.parallelTransport??null,replacementInProgress:i.replacementPending,lastLifecycleTransitionAtMs:i.lastLifecycleTransitionAtMs,transitionCount:i.transitionCount,connectingTransitionCount:i.connectingTransitionCount,replacementCount:i.replacementCount,retireCount:i.retireCount,lastDisconnectReason:i.lastDisconnectReason??void 0,lastReconnectReason:i.lastReconnectReason??void 0,updatedAt:i.lastSeenAtMs,error:i.error??void 0}}function Ut(i){let e=se(i),t=y(e,"connectionId","connection_id");if(!t)return null;let n=y(e,"state")||"connecting",r=S(e,"createdAt","created_at")??S(e,"updatedAt","updated_at")??Date.now(),s=S(e,"updatedAt","updated_at")??r;return {connectionId:t,deviceId:y(e,"deviceId","device_id"),deviceIdHint:y(e,"deviceIdHint","device_id_hint"),remoteNodeId:y(e,"remoteNodeId","remote_node_id"),state:n,transportState:y(e,"transportState","transport_state")??(n==="connected"?"connected":n==="connecting"?"connecting":"closed"),protocolState:y(e,"protocolState","protocol_state")??(n==="connected"?"routable":n==="connecting"?"connecting":"closed"),routable:H(e,"routable")??false,readinessState:y(e,"readinessState","readiness_state")??void 0,readinessReason:y(e,"readinessReason","readiness_reason")??void 0,transportGeneration:S(e,"transportGeneration","transport_generation")??void 0,routeGeneration:S(e,"routeGeneration","route_generation")??void 0,activeTransportStableId:S(e,"activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:Y(e,"activeTransport","active_transport"),parallelTransport:Y(e,"parallelTransport","parallel_transport")??null,replacementInProgress:H(e,"replacementInProgress","replacement_in_progress")??void 0,lastLifecycleTransitionAtMs:S(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:S(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:S(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:S(e,"replacementCount","replacement_count")??void 0,retireCount:S(e,"retireCount","retire_count")??void 0,lastDisconnectReason:y(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:y(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:y(e,"error")??void 0,createdAt:r,updatedAt:s}}function Wt(i,e){return i?i.connectionId===e.connectionId&&(i.deviceId??null)===(e.deviceId??null)&&(i.deviceIdHint??null)===(e.deviceIdHint??null)&&(i.remoteNodeId??null)===(e.remoteNodeId??null)&&i.state===e.state&&(i.transportState??null)===(e.transportState??null)&&(i.protocolState??null)===(e.protocolState??null)&&!!i.routable==!!e.routable&&(i.activeTransport??null)===(e.activeTransport??null)&&(i.parallelTransport??null)===(e.parallelTransport??null)&&(i.activeTransportStableId??null)===(e.activeTransportStableId??null)&&(i.transportGeneration??null)===(e.transportGeneration??null)&&(i.routeGeneration??null)===(e.routeGeneration??null)&&!!i.replacementInProgress==!!e.replacementInProgress&&(i.transitionCount??null)===(e.transitionCount??null)&&(i.connectingTransitionCount??null)===(e.connectingTransitionCount??null)&&(i.replacementCount??null)===(e.replacementCount??null)&&(i.retireCount??null)===(e.retireCount??null)&&(i.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(i.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(i.error??null)===(e.error??null):false}function si(i){try{let e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,n=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(n));let r=globalThis.Buffer;if(r)return JSON.parse(r.from(n,"base64").toString("utf8"))}catch{return null}return null}function oi(i){let e=typeof i=="string"?i.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null,s=r?si(r):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:x(n),tokenFingerprint:x(o),tokenSuffixFingerprint:x(r),scope:a,maxConnections:c}}var m=class m{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserFirestoreSignaling=null;this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this._rtdbPresence=null;this.rtdbPresenceScope=null;this.rtdbTicketVersion=0;this.rtdbPresenceDisabledForSession=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;try{let n=typeof import.meta<"u"?import.meta.env:null;if(!!n&&String(n.VITE_USE_EMULATORS)==="true"&&(n.DEV||String(n.VITE_E2E)==="true")){let s=String(n.VITE_OPENRTC_FIRESTORE_EMULATOR_HOST||"").trim()||"127.0.0.1:8082";globalThis.__OPENRTC_FIRESTORE_EMULATOR_HOST__=s;}}catch{}if(this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.presenceManager=new Se({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(n,r)=>this.waitForWasmClient(n,r),warnMissingWasmOnce:n=>this.warnMissingWasmOnce(n),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(n,r)=>this.withWebPresenceMetadata(n,r),updatePresence:(n,r,s,o,a,c)=>this.updatePresence(n,r,s,o,a,c),buildRtdbScope:n=>this.buildRtdbScope(n),resolveRtdbScope:n=>this.resolveRtdbScope(n),registerRtdbPresence:(n,r,s,o)=>this.registerRtdbPresence(n,r,s,o),isRtdbPresenceDisabledForSession:()=>this.rtdbPresenceDisabledForSession,getRtdbTicketVersion:()=>this.rtdbTicketVersion,getBrowserFirestoreSignaling:()=>this.getBrowserFirestoreSignaling(),rememberRouteRepairTokenFromTicket:n=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(n)??Promise.resolve(false)}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()){this.app=null,this.auth=null;return}let t=G$1();this.app=t.getApp(),this.auth=t.getAuth(),t.onAuthStateChanged(n=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(o=>o(this.toRuntimeIdentity(n)));return}let r=n?.uid??null,s=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=r,s&&s!==r&&this.stopAuthScopedActivity({userId:s}),this.browserFirestoreSignaling?.handleScopeChange(),this.authListeners.forEach(o=>o(this.toRuntimeIdentity(n)));});}get rtdbPresence(){return this._rtdbPresence}get tag(){return this.appTag}getRuntimeCapabilities(){return J(le)}getDeviceIdentityStorageKey(){let e=f(this.options);return `${m.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}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(),r=Date.now(),s=null;try{let d=localStorage.getItem(n);s=d?JSON.parse(d):null;}catch{s=null;}let o=typeof s?.deviceId=="string"?s.deviceId.trim():"",a=typeof s?.expiresAt=="number"?s.expiresAt:void 0;if(t==="persistent"){let d=o||this.createRandomDeviceId();return localStorage.setItem(n,JSON.stringify({deviceId:d})),d}if(o&&typeof a=="number"&&a>r){let d=r+m.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:o,expiresAt:d})),o}let c=this.createRandomDeviceId(),l=r+m.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:c,expiresAt:l})),c}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}getBrowserFirestoreSignaling(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Browser signaling is disabled when signalingMode="ticket-only".');return this.browserFirestoreSignaling||(this.browserFirestoreSignaling=new be({app:this.app,auth:this.auth,appTag:this.appTag,apiKey:this.options.apiKey,spaceKey:this.options.spaceKey,discoveryMode:this.options.discoveryMode,getCurrentUserId:()=>this.getCurrentUserId(),getDiscoveryScopeId:()=>this.getDiscoveryScopeId(),getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),matchesTag:e=>this.matchesTag(e),normalizeDevice:(e,t)=>this.normalizeDevice(e,t)})),this.browserFirestoreSignaling}async withWebPresenceMetadata(e,t){let n;if(!e||!e.trim())n=JSON.stringify({deviceId:t});else {try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return n=JSON.stringify({...r,deviceId:t}),await We(n)??n}catch{}n=JSON.stringify({deviceId:t,metadata:e});}return await We(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.browserFirestoreSignaling?.handleScopeChange(),this.authListeners.forEach(n=>n(this.currentUser));}async ensureBrowserFirestoreAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await G$1().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){if(!this.wasmClient||typeof this.wasmClient.set_auth_token!="function"||!this.authContext&&this.isSpaceMode())return;let e=this.authContext?.userId??null,t=this.authContext?.token??null;this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===e&&this.lastWasmAuthToken===t||(this.lastWasmAuthUserId=e,this.lastWasmAuthToken=t,this.hasSyncedAuthToWasmClient=true,this.wasmClient.set_auth_token(t));}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return Nt(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 Ft(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}disableRtdbPresenceForSession(e,t){this.rtdbPresenceDisabledForSession||console.warn(`[WasmBridge] Disabling RTDB presence for this browser session (${e})`,t),this.rtdbPresenceDisabledForSession=true,this.rtdbPresenceScope=null,this.browserFirestoreSignaling?.stopRtdbPresence();}async registerRtdbPresence(e,t,n,r){if(this.isTicketOnlyMode())return;if(!this._rtdbPresence)try{this._rtdbPresence=new pe(this.app);}catch(a){throw this.disableRtdbPresenceForSession("RTDB service unavailable",a),a}this.rtdbPresenceScope=e;let s=n??this.rtdbTicketVersion;this.getBrowserFirestoreSignaling().setRtdbPresence(this._rtdbPresence,e);try{await this._rtdbPresence.registerDevice(e,t,s,r);}catch(a){throw a}}buildRtdbPresenceFields(e,t,n,r){return {ticket:t,nodeId:e,deviceName:r?.trim()||this.getDefaultBrowserDeviceName(),platformType:"web",metadata:n}}async refreshRtdbPresenceTicket(e,t,n,r){if(this.isTicketOnlyMode()||this.rtdbPresenceDisabledForSession)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,r);if(this._rtdbPresence&&this.rtdbPresenceScope){await this._rtdbPresence.bumpTicketVersion(o,s,a,c);return}await this.registerRtdbPresence(o,s,a,c);}async stopAuthScopedActivity(e){at("WasmBridge.stopAuthScopedActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1;let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(n){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",n);}this.presenceManager.stop(),this.rtdbPresenceDisabledForSession=false,this.rtdbPresenceScope=null,this.rtdbTicketVersion=0,this.browserFirestoreSignaling?.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 ze(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}normalizeDeviceStatusSnapshot(e){return Bt(e)}normalizePeerSessionSnapshot(e){return Lt(e)}toBackendConnectionStateFromPeerSession(e){return Ot(e)}normalizeConnectionStateSnapshot(e){return Ut(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 Wt(e,t)}deliverConnectionState(e,t,n,r){let s=this.stabilizeConnectionState(e);this.escalateManagedApplicationRoute(s),this.lastDeliveredConnectionStates.set(s.connectionId,s);let a=(r??this.lastDeliveredConnectionStates).get(s.connectionId);this.sameConnectionState(a,s)||(r&&r.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 r=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(r&&r.uid===this.authContext?.userId)try{return await r.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$1().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await G$1().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await G$1().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await G$1().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthScopedActivity({userId:e}),this.authContext=null,this.hasSyncedAuthToWasmClient=false,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,n=true,r=3e5,s,o){if(this.isTicketOnlyMode())return;let a=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?m.EPHEMERAL_DEVICE_ID_TTL_MS:r,l=await this.withWebPresenceMetadata(s,a);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:l,deviceName:o?.trim()||this.getDefaultBrowserDeviceName()}),await this.getBrowserFirestoreSignaling().updatePresence(e,t,n,c,l,o),await this.refreshRtdbPresenceTicket(e,t,l,o);}async refreshLivePresence(e,t,n,r){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),o=await this.withWebPresenceMetadata(n,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:o,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.refreshRtdbPresenceTicket(e,t,o,r);}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,r){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getBrowserFirestoreSignaling().sendMessage(e,t,n,r)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getBrowserFirestoreSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getBrowserFirestoreSignaling().searchDevices(e)}async listDevicesWithStatus(){return this.isTicketOnlyMode()?[]:this.getDiscoveryScopeId()?(await this.getBrowserFirestoreSignaling().listDevices()).map(n=>this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"})):[]}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let n=await t.peer_session(e);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(r=>this.normalizePeerSessionSnapshot(r)).filter(r=>!!(r.peerId||r.deviceId||r.deviceIdHint||r.nodeId||r.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 r=await n.wait_for_settled_peer(e,t);return !r||typeof r!="object"?null:this.normalizePeerSessionSnapshot(r)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.open_peer_bi=="function"){let r=await n.open_peer_bi(e,t);if(!r?.recv||!r?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:r.recv,writable:r.send}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerNativeBi(e,t,n){let r=await this.waitForWasmClient(500),s=r&&r.open_peer_native_bi;if(typeof s=="function"){let o=await s.call(r,e,t,n);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_native_bi returned an invalid bidirectional stream");return {readable:o.recv,writable:o.send}}throw this.warnMissingWasmOnce("openPeerNativeBi"),new Error("WASM runtime does not support open_peer_native_bi()")}async openPeerBiTransportOnly(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiTransportOnly is debug-only and cannot be used when application crypto is required");let n=await this.waitForWasmClient(500),r=n&&typeof n.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiTransportOnly",{peerId:e,hasWasmClient:!!n,hasTransportOnly:r,timeoutMs:t}),r){let s=await n.open_peer_bi_transport_only(e,t);if(!s?.recv||!s?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:s.recv,writable:s.send}}return console.debug("[WasmBridge] openPeerBiTransportOnly falling back to openPeerBi",{peerId:e}),this.openPeerBi(e,t)}async openPeerUni(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.open_peer_uni=="function"){let r=await n.open_peer_uni(e,t);if(!r)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:r}}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(r=>({connectionId:typeof r.connectionId=="string"?r.connectionId:"",nodeId:typeof r.nodeId=="string"?r.nodeId:null,deviceId:typeof r.deviceId=="string"?r.deviceId:null,deviceIdHint:typeof r.deviceIdHint=="string"?r.deviceIdHint:null,endpointId:typeof r.endpointId=="string"?r.endpointId:null,transportGeneration:typeof r.transportGeneration=="number"?r.transportGeneration:0,routeGeneration:typeof r.routeGeneration=="number"?r.routeGeneration:void 0,transportStableId:typeof r.transportStableId=="number"?r.transportStableId:null,transportSource:typeof r.transportSource=="string"?r.transportSource:null,lastTransportChangeAtMs:typeof r.lastTransportChangeAtMs=="number"?r.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof r.lastRouteChangeAtMs=="number"?r.lastRouteChangeAtMs:void 0,state:typeof r.state=="string"?r.state:"pending",statusReason:typeof r.statusReason=="string"?r.statusReason:null,createdAtMs:typeof r.createdAtMs=="number"?r.createdAtMs:0,updatedAtMs:typeof r.updatedAtMs=="number"?r.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerConnectionRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let n=r=>{if(!r||typeof r!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let s=r;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 r=await t.peer_session(e),s=n(r);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;let n=this.authScopedRuntimeGeneration;try{let r=await this.waitForWasmClient();if(n!==this.authScopedRuntimeGeneration||!r||typeof r.start_auto_connect!="function")return;await r.start_auto_connect(e,t),n===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(r){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:r});}}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.coreClient=null;}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,r=this.coreClient,s;s=(async()=>{let o=typeof r.ensureManagedApplicationRoute=="function"?await r.ensureManagedApplicationRoute({ticket:t.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??t.nodeId,expectedDeviceId:t.deviceId,timeoutMs:2e4}):await r.connect(t.ticket,2e4,t.deviceId,void 0,{admissionAlreadyPresented:true});if(n!==this.authScopedRuntimeGeneration)return;let a=o,c=a.id?.trim()||e.connectionId,l=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||t.deviceId;if(r.hasApplicationRouteForPeer?.(c,l)!==true&&r.hasApplicationRouteForPeer?.(c,l)!==true)throw new Error(`application crypto was not ready for ${l}`)})().catch(o=>{n===this.authScopedRuntimeGeneration&&console.warn("[WasmBridge][ROUTE-ESCALATION] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:t.deviceId,remoteNodeId:e.remoteNodeId??t.nodeId,error:o?.message??String(o)});}).finally(()=>{this.applicationRouteEscalations.get(e.connectionId)===s&&this.applicationRouteEscalations.delete(e.connectionId);}),this.applicationRouteEscalations.set(e.connectionId,s);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let n=Date.now();R("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:oi(e.endpointTicket),hasCoreClient:!!this.coreClient});let r=await t.connect_device(e.deviceId??null,e.endpointTicket);R("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.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:r?.remoteNodeId??null,connectionId:r?.connectionId??null});let a=typeof o.ensureManagedApplicationRoute=="function"?await o.ensureManagedApplicationRoute({ticket:s,connectionId:r?.connectionId??null,remoteNodeId:r?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,timeoutMs:2e4}):await o.connect(s,2e4,e.deviceId??null,void 0,{admissionAlreadyPresented:!0}),c=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():"",l=typeof a?.deviceId=="string"?a.deviceId.trim():"",d=c||r?.remoteNodeId?.trim?.()||l||e.deviceId?.trim?.()||"",u=typeof o.hasApplicationRouteForPeer=="function"?o.hasApplicationRouteForPeer.bind(o):null;if(!(!!d&&u?.(a?.id??void 0,d)===!0)&&d&&typeof o.waitForApplicationCryptoForPeer=="function"&&!(!!await o.waitForApplicationCryptoForPeer(d,2e4)&&(!u||u(a?.id??void 0,d)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:c||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,peerForCrypto:d,elapsedMs:Date.now()-n}),Object.assign(new Error(`application crypto was not ready for ${d}`),{applicationCryptoNotReady:!0});R("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:c||(r?.remoteNodeId??null),connectionId:r?.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:r?.remoteNodeId??null,connectionId:r?.connectionId??null,error:a?.message??String(a)}),r}}return r}forceReconnectSnapshot(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,n,r,s){this.presenceManager.startPresenceLoop(e,t,n,r,s);}usesSpaceScopedRtdb(){return (this.options.discoveryMode??"space")==="space"}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b(e,t).then(n=>(this.cachedSpaceNamespaceId=n,n)).catch(()=>null);}return this.spaceNamespaceIdPromise}buildRtdbScope(e){if(this.isTicketOnlyMode())return null;let t=this.options.discoveryMode??"space",n=this.appTag;if(t==="space")return this.usesSpaceScopedRtdb()&&this.cachedSpaceNamespaceId?{kind:"space",namespaceId:this.cachedSpaceNamespaceId}:null;let r=e||this.getDiscoveryScopeId()||this.getCurrentUserId();return r?{kind:"user-scoped",appTag:n,userId:r}: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(),r=[];if(typeof e.peer_session=="function")try{let s=await e.peer_session(n);s&&typeof s=="object"&&r.push(this.normalizePeerSessionSnapshot(s));}catch{}if(typeof e.peer_sessions=="function")try{let s=await e.peer_sessions();Array.isArray(s)&&r.push(...s.filter(o=>!!o&&typeof o=="object").map(o=>this.normalizePeerSessionSnapshot(o)));}catch{}return r.some(s=>{let o=typeof s.peerId=="string"?s.peerId.trim():"",a=typeof s.deviceId=="string"?s.deviceId.trim():"",c=typeof s.deviceIdHint=="string"?s.deviceIdHint.trim():"",l=typeof s.nodeId=="string"?s.nodeId.trim():"";return (n===o||n===a||n===c||n===l)&&s.status==="connected"&&s.settledReady===true&&s.replacementPending!==true&&g(s.activeTransport)})}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let r=await e.connection_states(),s=(Array.isArray(r)?r:[]).map(o=>this.normalizeConnectionStateSnapshot(o)).filter(o=>!!o);return s.length>0&&De("[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(r=>this.toBackendConnectionStateFromPeerSession(r)).filter(r=>!!r);return n.length>0&&De("[WasmBridge] replaying current wasm connection states",n.map(r=>({connectionId:r.connectionId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportState:r.transportState??null,protocolState:r.protocolState??null,routable:r.routable??null}))),n}onConnectionStateChange(e){let t=new Map,n=new Map,r=this.authScopedRuntimeGeneration,s=false,o=l=>{let d=l.detail,u=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!u||s)return;let p=(n.get(u)??0)+1;n.set(u,p);let f=this.authScopedRuntimeGeneration;(async()=>{let h=this.normalizeConnectionStateSnapshot(d),g=await this.waitForWasmClient(500);if(!(s||f!==this.authScopedRuntimeGeneration||n.get(u)!==p)){if(g&&typeof g.connection_state=="function"){let v=await g.connection_state(u),w=this.normalizeConnectionStateSnapshot(v);if(!s&&f===this.authScopedRuntimeGeneration&&n.get(u)===p&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!s&&f===this.authScopedRuntimeGeneration&&n.get(u)===p&&h&&this.deliverConnectionState(h,e,"rust-event-detail",t);}})().catch(h=>{s||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:u,error:h});});},a=typeof window<"u"?window:null,c=typeof a?.addEventListener=="function"&&typeof a?.removeEventListener=="function";return c&&a.addEventListener("connection-state-changed",o),this.getConnectionStates().then(l=>{!s&&r===this.authScopedRuntimeGeneration&&l.forEach(d=>{n.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(l=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",l);}),()=>{s=true,n.clear(),c&&a.removeEventListener("connection-state-changed",o);}}async sendExplicitFilePath(e,t,n=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let n=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(o=>o.trim().length>0)?.trim()??"";if(!n||n==="."||n==="..")return m.FALLBACK_EXPLICIT_FILE_NAME;let r="";for(let o of n){if([...r].length>=m.MAX_EXPLICIT_FILE_NAME_CHARS)break;let a=o.charCodeAt(0);o==="/"||o==="\\"||o==="\0"||a<32||a===127?r+="_":r+=o;}let s=r.trim();return !s||s==="."||s===".."?m.FALLBACK_EXPLICIT_FILE_NAME:s}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return m.FALLBACK_EXPLICIT_MIME_TYPE;let n="";for(let r of t){if(n.length>=m.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let s=r.charCodeAt(0);s<33||s>126||r==='"'||r==="\\"?n+="_":n+=r;}return n.length>0?n:m.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>m.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,r,s){let o=s?.headerFrame===true?4:0,a=new Uint8Array(25+o+r.byteLength);a[0]=m.EXPLICIT_FILE_PROTOCOL_TYPE,a.set(e,1);let c=new DataView(a.buffer);c.setUint32(17,t,false),c.setUint32(21,n,false);let l=s?.headerFrame===true?29:25;return s?.headerFrame===true&&c.setUint32(25,r.byteLength,false),a.set(r,l),a}async sendExplicitFileData(e){let t=e.connection,n=e.file,r=e.applicationCrypto??this.options.applicationCrypto,s=e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true;if(s&&!r)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let o=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`,a=typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null,c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(R("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:n.name,fileSize:n.size,transferId:o}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let l=await this.waitForWasmClient();if(!l)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,u={transfer_id:o,filename:this.sanitizeExplicitFileName(n.name),size:n.size,mime_type:this.sanitizeExplicitMimeType(n.type)},p=d.encode(JSON.stringify(u));this.assertExplicitTransferHeaderSize(p);let f=new Uint8Array(4);new DataView(f.buffer).setUint32(0,p.byteLength,false);let h=new Uint8Array(f.byteLength+p.byteLength);h.set(f,0),h.set(p,f.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 b=r?Te(r):null,I=B=>b?b.protectFrame(B):B,T=new Uint8Array(await n.arrayBuffer()),P=this.createWebRTCExplicitTransferId(),C=Math.max(1,Math.ceil(T.byteLength/m.EXPLICIT_FILE_CHUNK_SIZE_BYTES)),D=typeof t.getWebRTCTransport=="function"?t.getWebRTCTransport():null,k=async()=>{D&&typeof D.getBufferedAmount=="function"&&typeof D.waitForDrain=="function"&&D.getBufferedAmount()>m.EXPLICIT_FILE_CHUNK_SIZE_BYTES*4&&await D.waitForDrain(m.EXPLICIT_FILE_CHUNK_SIZE_BYTES*2);};if(await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(P,4294967295,C,I(p),{headerFrame:true})),await k(),T.byteLength===0)return await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(P,0,C,I(new Uint8Array(0)))),true;let je=0;for(let B=0;B<T.byteLength;B+=m.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let Kt=T.slice(B,Math.min(B+m.EXPLICIT_FILE_CHUNK_SIZE_BYTES,T.byteLength));await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(P,je,C,I(Kt))),je+=1,await k();}return R("[WasmBridge] sendExplicitFileData sent over WebRTC explicit route",{connectionId:e.connectionId??null,remoteNodeId:c,transferId:o,chunks:C,encrypted:!!b}),true},v=async()=>{let b=l.open_peer_bi_explicit_file_sender;if(typeof b!="function")return false;let I=await b.call(l,c,5e3),T=I?.writable??I?.send;if(!T||typeof T.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:I.applicationCryptoWrapped===true});let P=T.getWriter();try{await P.write(h);let C=new Uint8Array(await n.arrayBuffer());for(let D=0;D<C.byteLength;D+=m.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let k=C.slice(D,Math.min(D+m.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await P.write(k);}}finally{await P.close().catch(()=>{}),P.releaseLock();}return true},w=async()=>{if(typeof l.open_bi!="function")throw new Error("WASM explicit transfer requires open_bi support");let b=await l.open_bi(c);R("[WasmBridge] sendExplicitFileData open_bi resolved",{remoteNodeId:c,transferId:e.transferId??null});let I=b.send.getWriter();try{await I.write(new Uint8Array([m.EXPLICIT_FILE_PROTOCOL_TYPE])),await I.write(f),await I.write(p);let T=new Uint8Array(await n.arrayBuffer());for(let P=0;P<T.byteLength;P+=m.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let C=T.slice(P,Math.min(P+m.EXPLICIT_FILE_CHUNK_SIZE_BYTES,T.byteLength));await I.write(C);}}finally{await I.close().catch(()=>{}),I.releaseLock();}},F=async()=>{if(typeof l.open_bi!="function")throw new Error("WASM explicit transfer requires open_bi support");if(!r)throw new Error("WASM encrypted explicit transfer requires application crypto");let b=await l.open_bi(c);R("[WasmBridge] sendExplicitFileData encrypted fallback open_bi resolved",{remoteNodeId:c,transferId:e.transferId??null});let I=Te(r),T=C=>{let D=I.protectFrame(C),k=new Uint8Array(4+D.byteLength);return new DataView(k.buffer).setUint32(0,D.byteLength,false),k.set(D,4),k},P=b.send.getWriter();try{await P.write(new Uint8Array([m.EXPLICIT_FILE_PROTOCOL_TYPE])),await P.write(T(h));let C=new Uint8Array(await n.arrayBuffer());for(let D=0;D<C.byteLength;D+=m.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let k=C.slice(D,Math.min(D+m.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await P.write(T(k));}}finally{await P.close().catch(()=>{}),P.releaseLock();}};try{try{if(await g())return}catch(b){R("[WasmBridge] sendExplicitFileData WebRTC explicit route failed; falling back",{remoteNodeId:c,transferId:o,error:b instanceof Error?b.message:String(b)});}if(await v())return;if(s)throw new Error("[WasmBridge] Explicit transfer requires the crypto-wrapped open_peer_bi_explicit_file_sender path under mandatory application crypto, but it is unavailable on this WASM build. Rebuild the openrtc WASM (pnpm --filter openrtc build:wasm) \u2014 a raw open_bi fallback is intentionally not used for mandatory-crypto app data.");r?await F():await w();}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);}};m.EXPLICIT_FILE_PROTOCOL_TYPE=2,m.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,m.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,m.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",m.MAX_EXPLICIT_FILE_NAME_CHARS=180,m.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",m.MAX_EXPLICIT_MIME_TYPE_CHARS=255,m.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",m.EPHEMERAL_DEVICE_ID_TTL_MS=X.browserIdentity.ephemeralDeviceIdTtlMs;var Ht=m;var Gt=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthScopedActivity(){typeof this.backend.stopAuthScopedActivity=="function"&&await this.backend.stopAuthScopedActivity();}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,r,s){return this.backend.updatePresence(e,t,n,r,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,r){return this.backend.sendMessage(e,t,n,r)}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,r,s){this.backend.startPresenceLoop(e,t,n,r,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,r,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,r,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 r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n);}async revokeSessionTokensByScope(e){let t=this.backend;return typeof t.revokeSessionTokensByScope!="function"?[]:t.revokeSessionTokensByScope(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async openPeerNativeBi(e,t,n){let r=this.backend;if(typeof r.openPeerNativeBi!="function")throw new Error("Selected runtime adapter does not support openPeerNativeBi().");return r.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():J(le)}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};export{J as A,yi as B,mi as C,Ht as D,Gt as E,zt as a,De as b,R as c,ai as d,pe as e,$i as f,Xi as g,Ji as h,Qi as i,We as j,Qn as k,Jt as l,ui as m,Te as n,at as o,He as p,ii as q,Bt as r,Lt as s,tr as t,nr as u,Ut as v,X as w,hi as x,le as y,tn as z};
|