openrtc 1.0.26 → 2.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +143 -205
  2. package/dist/DelegatingRuntimeAdapter-DqfHkjLy.d.ts +373 -0
  3. package/dist/ITransport-BsPcaov7.d.ts +16 -0
  4. package/dist/OpenRTCShared-TKAQLONA.js +1 -0
  5. package/dist/WasmBridge-2A22U7RU.js +1 -0
  6. package/dist/auth/index.js +1 -1
  7. package/dist/auth/internal.js +1 -1
  8. package/dist/{capabilities-CaqXOIUU.d.ts → capabilities-YSskrE8H.d.ts} +1 -1
  9. package/dist/chunk-2QHDEGVX.js +1 -0
  10. package/dist/chunk-4K2QPYGT.js +2 -0
  11. package/dist/chunk-7Z6N46RB.js +2 -0
  12. package/dist/chunk-A3IAG6EL.js +1 -0
  13. package/dist/chunk-BXFXPIXO.js +1 -0
  14. package/dist/chunk-CEMN2JKR.js +3 -0
  15. package/dist/chunk-DTWEQS3J.js +1 -0
  16. package/dist/chunk-GW7P3D54.js +1 -0
  17. package/dist/chunk-K37WVIZL.js +1 -0
  18. package/dist/chunk-N26S7V4N.js +1 -0
  19. package/dist/chunk-N4SX7C3W.js +2 -0
  20. package/dist/chunk-NB4H5TP3.js +1 -0
  21. package/dist/chunk-NT5YHZQH.js +1 -0
  22. package/dist/chunk-PODAMIL6.js +2 -0
  23. package/dist/chunk-RD3JEGGF.js +2 -0
  24. package/dist/chunk-UEYM6WTT.js +2 -0
  25. package/dist/chunk-VK6KX433.js +1 -0
  26. package/dist/chunk-WMRCP3YX.js +1 -0
  27. package/dist/chunk-XE43HAXV.js +2 -0
  28. package/dist/chunk-YBXGNKM7.js +2 -0
  29. package/dist/chunk-YGJ6OAPR.js +1 -0
  30. package/dist/factories-O5575ECL.js +1 -0
  31. package/dist/index.d.ts +11 -65
  32. package/dist/index.js +1 -1
  33. package/dist/ipcFactory-FBNUVH7V.js +1 -0
  34. package/dist/native.d.ts +9 -15
  35. package/dist/native.js +1 -1
  36. package/dist/openrtc_bg.wasm +0 -0
  37. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  38. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  39. package/dist/runtime/device-status.d.ts +3 -2
  40. package/dist/runtime/index.d.ts +110 -17
  41. package/dist/runtime/index.js +2 -1
  42. package/dist/runtime/tauri.d.ts +4 -4
  43. package/dist/runtime/tauri.js +1 -1
  44. package/dist/{tauri-BpsecNrp.d.ts → tauri-Cz9n17g8.d.ts} +2 -2
  45. package/dist/testing.d.ts +29 -0
  46. package/dist/testing.js +1 -0
  47. package/dist/transport/index.d.ts +47 -7
  48. package/dist/transport/index.js +1 -1
  49. package/dist/{assembly-CscFVHYK.d.ts → types-BDc7AZYI.d.ts} +446 -28
  50. package/dist/{types-BJU2GoVb.d.ts → types-BUXwspL0.d.ts} +11 -17
  51. package/dist/{types-zT2QwuCv.d.ts → types-BVJr065k.d.ts} +43 -3
  52. package/package.json +15 -4
  53. package/dist/DelegatingRuntimeAdapter-Cg3jFk1b.d.ts +0 -133
  54. package/dist/chunk-2W2YWRIZ.js +0 -1
  55. package/dist/chunk-BW6OKBHV.js +0 -2
  56. package/dist/chunk-D4JYPV6F.js +0 -2
  57. package/dist/chunk-DIBUXEEO.js +0 -1
  58. package/dist/chunk-DXJZDB7Q.js +0 -3
  59. package/dist/chunk-OCSZA6PK.js +0 -2
  60. package/dist/chunk-PPGIC6DR.js +0 -2
  61. package/dist/chunk-QBAVJDN2.js +0 -2
  62. package/dist/chunk-QT2ASNI3.js +0 -1
  63. package/dist/framing-zRvEKOld.d.ts +0 -29
  64. package/dist/spaceTokens-CiwcKKr2.d.ts +0 -297
@@ -0,0 +1,373 @@
1
+ import { D as Device, n as DiscoveryMode, o as AuthMode, p as SignalingMode, i as ClientOptions, E as ExplicitFileDataSendParams, q as ISignalingBackend, j as RoomMember, R as RuntimeIdentity, r as SignalingEnvelope, h as DeviceStatusSnapshot, m as PeerSessionSnapshot, s as BackendPeerBiStream, t as BackendPeerUniStream, u as ManagedConnectionRecord, v as ResolvedPeerIdentity, w as DeviceEvent, x as DesiredPeerProjection, y as CoreClientBridgeHost, N as NativeConnectParams, z as NativeConnectResult, S as SignalingSession, F as SessionEvent, B as BackendConnectionState, L as LocalDeviceInfo, G as NativeManagedSessionStartResult, H as GrantScope } from './types-BVJr065k.js';
2
+ import { R as RuntimeCapabilities } from './capabilities-YSskrE8H.js';
3
+ import { A as AuthContext } from './IEngineBridge-BbsT8hof.js';
4
+
5
+ interface NativeTrustToken {
6
+ token: string;
7
+ expiresAtMs: number;
8
+ }
9
+
10
+ /** Internal-only gateway record before normalization; includes namespace fields omitted from the public Device type. */
11
+ type RawDeviceDoc = Device & {
12
+ appTag?: string;
13
+ tag?: string;
14
+ };
15
+
16
+ interface WasmBridgeOptions {
17
+ apiKey?: string;
18
+ discoveryMode?: DiscoveryMode;
19
+ space?: string;
20
+ spaceKey?: string;
21
+ authMode?: AuthMode;
22
+ signalingMode?: SignalingMode;
23
+ projectId?: string;
24
+ coordinationGateway?: ClientOptions['coordinationGateway'];
25
+ coordinationAvenueOverride?: ClientOptions['coordinationAvenueOverride'];
26
+ platformAttestationTokenProvider?: ClientOptions['platformAttestationTokenProvider'];
27
+ /** Internal host hint used by the provider-neutral gateway projection. */
28
+ coordinationPlatformType?: 'web' | 'desktop' | 'mobile';
29
+ storagePrefix?: string;
30
+ deviceIdPersistence?: 'persistent' | 'ephemeral';
31
+ endpointIdPersistence?: 'persistent' | 'ephemeral';
32
+ nodeIdPersistence?: 'persistent' | 'ephemeral';
33
+ localDeviceId?: string;
34
+ deviceName?: string;
35
+ turnCredentialsProvider?: () => Promise<{
36
+ iceServers?: RTCIceServer[];
37
+ } | null | undefined>;
38
+ applicationCrypto?: ExplicitFileDataSendParams['applicationCrypto'];
39
+ spaceAuth?: 'scoped-token';
40
+ }
41
+ /**
42
+ * WasmBridge is the browser host wrapper over the Rust/WASM runtime.
43
+ *
44
+ * Allowed:
45
+ * - normalize JS/WASM binding shapes
46
+ * - forward auth, discovery, signaling, and lifecycle calls into Rust
47
+ * - expose typed browser-facing results
48
+ *
49
+ * Not allowed:
50
+ * - become a second lifecycle engine
51
+ * - invent peer identity or connect policy that is not backed by Rust
52
+ * - normalize app-specific payload protocols into runtime behavior
53
+ *
54
+ * Source of truth:
55
+ * - Rust/WASM owns transport/runtime connection state and lifecycle primitives
56
+ * - The selected coordination provider owns browser delivery projections
57
+ * - RuntimeClient owns app-facing orchestration across those surfaces
58
+ */
59
+ declare class WasmBridge implements ISignalingBackend {
60
+ private static readonly EXPLICIT_FILE_PROTOCOL_TYPE;
61
+ private static readonly EXPLICIT_FILE_CHUNK_SIZE_BYTES;
62
+ private static readonly MAX_EXPLICIT_TRANSFER_HEADER_BYTES;
63
+ private static readonly FALLBACK_EXPLICIT_FILE_NAME;
64
+ private static readonly MAX_EXPLICIT_FILE_NAME_CHARS;
65
+ private static readonly FALLBACK_EXPLICIT_MIME_TYPE;
66
+ private static readonly MAX_EXPLICIT_MIME_TYPE_CHARS;
67
+ app: any | null;
68
+ auth: any | null;
69
+ private readonly appTag;
70
+ protected options: {
71
+ appTag: string;
72
+ apiKey?: string;
73
+ discoveryMode?: DiscoveryMode;
74
+ space?: string;
75
+ spaceKey?: string;
76
+ authMode: AuthMode;
77
+ signalingMode?: SignalingMode;
78
+ projectId: string;
79
+ coordinationGateway?: ClientOptions['coordinationGateway'];
80
+ coordinationAvenueOverride?: ClientOptions['coordinationAvenueOverride'];
81
+ platformAttestationTokenProvider?: ClientOptions['platformAttestationTokenProvider'];
82
+ coordinationPlatformType?: 'web' | 'desktop' | 'mobile';
83
+ storagePrefix?: string;
84
+ deviceIdPersistence?: 'persistent' | 'ephemeral';
85
+ endpointIdPersistence?: 'persistent' | 'ephemeral';
86
+ nodeIdPersistence?: 'persistent' | 'ephemeral';
87
+ localDeviceId?: string;
88
+ deviceName?: string;
89
+ strictMode?: boolean;
90
+ turnCredentialsProvider?: () => Promise<{
91
+ iceServers?: RTCIceServer[];
92
+ } | null | undefined>;
93
+ applicationCrypto?: ExplicitFileDataSendParams['applicationCrypto'];
94
+ spaceTokenProvider?: ClientOptions['spaceTokenProvider'];
95
+ spaceAuth?: 'scoped-token';
96
+ };
97
+ private spaceNamespaceIdPromise;
98
+ private cachedSpaceNamespaceId;
99
+ private authListeners;
100
+ private persistenceReady;
101
+ wasmClient: any;
102
+ private readonly createdAtMs;
103
+ private missingWasmWarnings;
104
+ private readonly wasmReadyWarningDelayMs;
105
+ private browserCoordinationSignaling;
106
+ private readonly nativeTrustTokens;
107
+ private lastObservedFirebaseUserId;
108
+ private sessionReaders;
109
+ protected authContext: {
110
+ userId: string;
111
+ token?: string | null;
112
+ refreshToken?: string | null;
113
+ customToken?: string | null;
114
+ tokenProvider?: (forceRefresh?: boolean) => Promise<string | null>;
115
+ appCheckTokenProvider?: (forceRefresh?: boolean) => Promise<string | null>;
116
+ expiresAtMs?: number | null;
117
+ } | null;
118
+ private injectedBrowserAuthSessionActive;
119
+ private readonly presenceManager;
120
+ private hasSyncedAuthToWasmClient;
121
+ private lastWasmAuthUserId;
122
+ private lastWasmAuthToken;
123
+ private lastDeliveredConnectionStates;
124
+ private authScopedRuntimeGeneration;
125
+ private coreClient;
126
+ private readonly applicationRouteEscalations;
127
+ private applicationRouteEscalationUnsubscribe;
128
+ private applicationRouteEscalationSubscriptionGeneration;
129
+ private applicationRouteEscalationSubscriptionEpoch;
130
+ constructor(options: WasmBridgeOptions);
131
+ get tag(): string;
132
+ getRuntimeCapabilities(): RuntimeCapabilities;
133
+ private static readonly WEB_DEVICE_ID_STORAGE_PREFIX;
134
+ private static readonly EPHEMERAL_DEVICE_ID_TTL_MS;
135
+ private getDeviceIdentityStorageKey;
136
+ private getDeviceIdPersistenceMode;
137
+ private isTicketOnlyMode;
138
+ private usesProviderNeutralGrant;
139
+ private createRandomDeviceId;
140
+ protected resolveWebLogicalDeviceId(): string;
141
+ private getDefaultBrowserDeviceName;
142
+ private getCoordinationSignaling;
143
+ usesCoordinationGateway(): boolean;
144
+ /** Restore the existing gateway delivery subscription after a native host resumes. */
145
+ reconnectCoordinationAfterHostResume(): Promise<void>;
146
+ getCoordinationNativeTrustToken(forceRefresh?: boolean): Promise<NativeTrustToken>;
147
+ invalidateCoordinationNativeTrustToken(): void;
148
+ subscribeCoordinationNativeTrustToken(listener: (token: NativeTrustToken | null) => void, options?: {
149
+ emitCurrent?: boolean;
150
+ }): () => void;
151
+ setCoordinationLocalDeviceId(deviceId: string): void;
152
+ /** Internal native-host hint for provider-neutral roster presentation. */
153
+ setCoordinationPlatformType(platformType: 'desktop' | 'mobile'): void;
154
+ setCoordinationExcludedPeers(excludedPeers: string[]): Promise<void>;
155
+ joinCoordinationRoom(roomId: string, nodeId: string, ticket: string): Promise<void>;
156
+ leaveCoordinationRoom(roomId: string): Promise<void>;
157
+ getCoordinationRoomMembers(roomId: string): Promise<RoomMember[]>;
158
+ watchCoordinationRoomMembers(roomId: string, callback: (members: RoomMember[]) => void): () => void;
159
+ private withWebPresenceMetadata;
160
+ setAuthContext(context: {
161
+ userId: string;
162
+ token?: string | null;
163
+ refreshToken?: string | null;
164
+ customToken?: string | null;
165
+ tokenProvider?: (forceRefresh?: boolean) => Promise<string | null>;
166
+ appCheckTokenProvider?: (forceRefresh?: boolean) => Promise<string | null>;
167
+ expiresAtMs?: number | null;
168
+ } | null): Promise<void>;
169
+ private ensureBrowserPlatformAuth;
170
+ private syncWasmAuthToken;
171
+ private toRuntimeIdentity;
172
+ protected getCurrentUserId(): string | null;
173
+ getCurrentUserIdForScope(): string | null;
174
+ getAuthContext(): Readonly<typeof this.authContext> | null;
175
+ protected isSpaceMode(): boolean;
176
+ getResolvedOptions(): Readonly<typeof this.options>;
177
+ protected getDiscoveryScopeId(): string | null;
178
+ protected matchesTag(device: Pick<RawDeviceDoc, 'tag' | 'appTag'>): boolean;
179
+ matchesLegacyOrCurrentTag(device: Pick<RawDeviceDoc, 'tag' | 'appTag'>): boolean;
180
+ private stopSessionSubscriptions;
181
+ private stopRuntimeAuthScopedLoops;
182
+ stopAuthScopedActivity(options?: {
183
+ userId?: string | null;
184
+ }): Promise<void>;
185
+ setWasmClient(client: any): void;
186
+ private warnMissingWasmOnce;
187
+ private waitForWasmClient;
188
+ protected normalizeDevice(raw: Record<string, any>, fallbackId?: string): Device;
189
+ normalizeDeviceRecord(raw: Record<string, any>, fallbackId?: string): Device;
190
+ getResolvedWebLogicalDeviceId(): string;
191
+ private normalizeDeviceStatusSnapshot;
192
+ private normalizePeerSessionSnapshot;
193
+ private toBackendConnectionStateFromPeerSession;
194
+ private normalizeConnectionStateSnapshot;
195
+ private stabilizeConnectionState;
196
+ private sameConnectionState;
197
+ private deliverConnectionState;
198
+ private get browserPresenceLoopState();
199
+ private set browserPresenceLoopState(value);
200
+ get currentUser(): RuntimeIdentity | null;
201
+ onAuthChange(callback: (user: RuntimeIdentity | null) => void): () => void;
202
+ checkForSSOToken(): Promise<void>;
203
+ waitForAuth(): Promise<void>;
204
+ signInAnonymously(): Promise<void>;
205
+ signInWithPluto(): Promise<void>;
206
+ signOut(): Promise<void>;
207
+ getTurnCredentials(): Promise<any>;
208
+ updatePresence(localNodeId: string, ticketStr: string, isOnline?: boolean, ttlMs?: number, metadata?: string, deviceNameOverride?: string): Promise<void>;
209
+ refreshLivePresence(localNodeId: string, ticketStr: string, metadata?: string, deviceNameOverride?: string): Promise<void>;
210
+ setOffline(localNodeId: string): Promise<void>;
211
+ updateDevice(deviceId: string, updates: {
212
+ deviceName?: string;
213
+ capabilities?: Device['capabilities'];
214
+ metadata?: string;
215
+ excludedPeers?: string[];
216
+ }): Promise<void>;
217
+ deleteDevice(deviceId: string): Promise<void>;
218
+ cleanupStaleDevices(): Promise<void>;
219
+ sendMessage(targetId: string, payload: string, state?: string, replyPayload?: string): Promise<string>;
220
+ pollMessages(targetId: string): Promise<SignalingEnvelope[]>;
221
+ searchDevices(excludeNodeId?: string): Promise<Device[]>;
222
+ listDevicesWithStatus(): Promise<DeviceStatusSnapshot[]>;
223
+ getPeerSession(id: string): Promise<PeerSessionSnapshot | null>;
224
+ listPeerSessions(): Promise<PeerSessionSnapshot[]>;
225
+ waitForSettledPeer(id: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
226
+ openPeerBi(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
227
+ openPeerNativeBi(id: string, label: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
228
+ openPeerBiTransportOnly(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
229
+ openPeerUni(id: string, timeoutMs?: number): Promise<BackendPeerUniStream>;
230
+ resolvePeerConnectionRecords(id: string): Promise<ManagedConnectionRecord[]>;
231
+ resolvePeerIdentity(id: string): Promise<ResolvedPeerIdentity>;
232
+ onDevicesChange(callback: (devices: Device[]) => void, excludeNodeId?: string): () => void;
233
+ subscribeDevices(userId: string): Promise<ReadableStream<DeviceEvent[]>>;
234
+ startAutoConnect(userId: string, localDeviceId: string): Promise<void>;
235
+ startAutoConnectOnce(userId: string, localDeviceId: string): Promise<void>;
236
+ notifyDisconnectRequested(remoteNodeId: string): void;
237
+ setAutoConnectExcluded(deviceId: string, excluded: boolean): Promise<void>;
238
+ disconnectDevice(deviceId: string): Promise<void>;
239
+ submitDesiredPeerProjection(revision: number, peers: DesiredPeerProjection[]): Promise<void>;
240
+ setCoreClient(client: CoreClientBridgeHost | null): void;
241
+ private startApplicationRouteEscalationSubscription;
242
+ private stopApplicationRouteEscalationSubscription;
243
+ private retryManagedApplicationRouteEscalations;
244
+ private escalateManagedApplicationRoute;
245
+ connectToDevice(params: NativeConnectParams): Promise<NativeConnectResult>;
246
+ forceReconnectSnapshot(): void;
247
+ startPresenceLoop(userId: string, localNodeId: string, deviceName: string, ticket: string, metadata?: string): void;
248
+ private ensureSpaceNamespaceIdPromise;
249
+ createSession(session: SignalingSession): Promise<void>;
250
+ updateSession(sessionId: string, updateData: any): Promise<void>;
251
+ subscribeSessions(localDeviceId: string): Promise<ReadableStream<SessionEvent[]>>;
252
+ getLocalDeviceId(): Promise<string | null>;
253
+ isConnected(node_id: string): Promise<boolean>;
254
+ private hasConnectedIndependentPeerRoute;
255
+ getConnectionStates(): Promise<BackendConnectionState[]>;
256
+ onConnectionStateChange(callback: (state: BackendConnectionState) => void): Promise<() => void> | (() => void);
257
+ sendExplicitFilePath(connectionId: string, filePath: string, transferId?: string): Promise<string>;
258
+ private sanitizeExplicitFileName;
259
+ private sanitizeExplicitMimeType;
260
+ private assertExplicitTransferHeaderSize;
261
+ private createWebRTCExplicitTransferId;
262
+ private createWebRTCExplicitTransferFrame;
263
+ sendExplicitFileData(params: ExplicitFileDataSendParams): Promise<void>;
264
+ getTransferHistory(limit?: number): Promise<Array<[string, unknown]>>;
265
+ deleteTransferJob(jobId: string): Promise<void>;
266
+ watchFriendDevices(friendUserIds: string[], callback: (friendDevices: Map<string, any[]>) => void): () => void;
267
+ updateFriendTicket(friendTicket: string | null): Promise<void>;
268
+ }
269
+
270
+ declare abstract class DelegatingRuntimeAdapter implements ISignalingBackend {
271
+ protected readonly backend: ISignalingBackend;
272
+ protected constructor(backend: ISignalingBackend);
273
+ get currentUser(): RuntimeIdentity | null;
274
+ setAuthContext(context: AuthContext | null): Promise<void> | void;
275
+ signInAnonymously(): Promise<void>;
276
+ signInWithPluto(): Promise<void>;
277
+ signOut(): Promise<void>;
278
+ stopAuthScopedActivity(): Promise<void>;
279
+ usesCoordinationGateway(): boolean;
280
+ joinCoordinationRoom(roomId: string, nodeId: string, ticket: string): Promise<void>;
281
+ leaveCoordinationRoom(roomId: string): Promise<void>;
282
+ getCoordinationRoomMembers(roomId: string): Promise<RoomMember[]>;
283
+ watchCoordinationRoomMembers(roomId: string, callback: (members: RoomMember[]) => void): () => void;
284
+ getTurnCredentials(): Promise<any>;
285
+ updatePresence(localNodeId: string, ticketStr: string, isOnline: boolean, ttlMs: number, metadata?: string): Promise<void>;
286
+ refreshLivePresence(localNodeId: string, ticketStr: string, metadata?: string): Promise<void>;
287
+ setOffline(localNodeId: string): Promise<void>;
288
+ cleanupStaleDevices(): Promise<void>;
289
+ searchDevices(excludeNodeId?: string): Promise<Device[]>;
290
+ listDevicesWithStatus(): Promise<DeviceStatusSnapshot[]>;
291
+ getPeerSession(id: string): Promise<PeerSessionSnapshot | null>;
292
+ listPeerSessions(): Promise<PeerSessionSnapshot[]>;
293
+ waitForSettledPeer(id: string, timeoutMs?: number): Promise<PeerSessionSnapshot | null>;
294
+ resolvePeerIdentity(id: string): Promise<ResolvedPeerIdentity>;
295
+ resolvePeerConnectionRecords(id: string): Promise<ManagedConnectionRecord[]>;
296
+ updateDevice(deviceId: string, updates: {
297
+ deviceName?: string;
298
+ capabilities?: Device['capabilities'];
299
+ metadata?: string;
300
+ }): Promise<void>;
301
+ deleteDevice(deviceId: string): Promise<void>;
302
+ onDevicesChange(callback: (devices: Device[]) => void, excludeNodeId?: string): () => void;
303
+ onAuthChange(callback: (user: RuntimeIdentity | null) => void): () => void;
304
+ checkForSSOToken(): Promise<void>;
305
+ waitForAuth(): Promise<void>;
306
+ sendMessage(targetId: string, payload: string, state?: string, replyPayload?: string): Promise<string>;
307
+ pollMessages(targetId: string): Promise<SignalingEnvelope[]>;
308
+ watchFriendDevices(friendUserIds: string[], callback: (friendDevices: Map<string, Device[]>) => void): () => void;
309
+ updateFriendTicket(friendTicket: string | null): Promise<void>;
310
+ subscribeDevices(userId: string): Promise<ReadableStream<DeviceEvent[]>>;
311
+ startAutoConnect(userId: string, localDeviceId: string): void;
312
+ submitDesiredPeerProjection(revision: number, peers: DesiredPeerProjection[]): Promise<void>;
313
+ startPresenceLoop(userId: string, localNodeId: string, deviceName: string, ticket: string, metadata?: string): void;
314
+ createSession(session: SignalingSession): Promise<void>;
315
+ updateSession(sessionId: string, updateData: any): Promise<void>;
316
+ subscribeSessions(localDeviceId: string): Promise<ReadableStream<SessionEvent[]>>;
317
+ forceReconnectSnapshot(): void;
318
+ getLocalDeviceId(): Promise<string | null>;
319
+ getLocalDeviceInfo(): Promise<LocalDeviceInfo | null>;
320
+ updateLocalDeviceName(deviceName: string): Promise<LocalDeviceInfo | null>;
321
+ startManagedSessionNative(options: {
322
+ userId: string;
323
+ deviceName?: string;
324
+ localDeviceId?: string | null;
325
+ metadata?: string;
326
+ autoConnect?: boolean;
327
+ presence?: boolean;
328
+ }): Promise<NativeManagedSessionStartResult>;
329
+ notifyNetworkChange(options?: {
330
+ reason?: string;
331
+ }): Promise<unknown>;
332
+ getManagedNodeId(options?: {
333
+ initializeIfMissing?: boolean;
334
+ }): Promise<string | null>;
335
+ startPresenceLoopOnce(userId: string, localNodeId: string, deviceName: string, ticket: string, metadata?: string): Promise<void>;
336
+ startAutoConnectOnce(userId: string, localDeviceId: string): Promise<void>;
337
+ getEndpointTicket(): Promise<string>;
338
+ getEndpointTicketWithToken(scope: GrantScope, maxConnections: number): Promise<string | null>;
339
+ registerSessionToken(token: string, scope: GrantScope, maxConnections: number): Promise<void>;
340
+ revokeSessionTokensByScope(scope: GrantScope): Promise<string[]>;
341
+ openPeerBi(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
342
+ incoming_streams(): Promise<ReadableStream<unknown>>;
343
+ is_current_transport_stable_id(endpointId: string, transportStableId: bigint): Promise<boolean>;
344
+ openPeerNativeBi(id: string, label: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
345
+ openPeerBiTransportOnly(id: string, timeoutMs?: number): Promise<BackendPeerBiStream>;
346
+ openPeerUni(id: string, timeoutMs?: number): Promise<BackendPeerUniStream>;
347
+ connectToDevice(params: NativeConnectParams): Promise<NativeConnectResult>;
348
+ disconnectDevice(deviceId: string): Promise<void>;
349
+ setAutoConnectExcluded(deviceId: string, excluded: boolean): Promise<void>;
350
+ isConnected(nodeId: string): Promise<boolean>;
351
+ getConnectionStates(): Promise<BackendConnectionState[]>;
352
+ onConnectionStateChange(callback: (state: BackendConnectionState) => void): Promise<() => void> | (() => void);
353
+ /** @deprecated Use named channels or `openrtc-file-transfer`. */
354
+ sendExplicitFilePath(connectionId: string, filePath: string, transferId?: string): Promise<string>;
355
+ /** @deprecated Use named channels or `openrtc-file-transfer`. */
356
+ sendExplicitFileData(params: ExplicitFileDataSendParams): Promise<void>;
357
+ /** @deprecated Transfer history belongs to the consumer application. */
358
+ getTransferHistory(limit?: number): Promise<Array<[string, unknown]>>;
359
+ /** @deprecated Transfer history belongs to the consumer application. */
360
+ deleteTransferJob(jobId: string): Promise<void>;
361
+ getRuntimeCapabilities(): RuntimeCapabilities;
362
+ onIncomingNativeMessage(callback: (connectionId: string, remoteNodeId: string | null, message: any) => void): Promise<() => void>;
363
+ unwrap(): ISignalingBackend;
364
+ /**
365
+ * Forward setCoreClient() to the inner backend if it implements it. This
366
+ * lets the core Client inject a reference into backends (e.g. WasmBridge)
367
+ * that need to escalate transport-level dials into full Client.connect()
368
+ * handshakes.
369
+ */
370
+ setCoreClient(client: unknown): void;
371
+ }
372
+
373
+ export { DelegatingRuntimeAdapter as D, type WasmBridgeOptions as W, WasmBridge as a };
@@ -0,0 +1,16 @@
1
+ interface ITransport {
2
+ readonly name: string;
3
+ readonly isReady: boolean;
4
+ init(localNodeId: string, remoteNodeId: string, options: any): Promise<void>;
5
+ send(data: Uint8Array): Promise<void>;
6
+ close(): void;
7
+ onMessage(callback: (data: Uint8Array) => void): void;
8
+ onStateChange(callback: (state: 'connecting' | 'connected' | 'failed' | 'disconnected') => void): void;
9
+ handleSignalingMessage?(msg: any): void;
10
+ getSignalingHandler?(): (msg: any) => Promise<void>;
11
+ getNativeTransport?(): any;
12
+ getNegotiationId?(): string | null;
13
+ getDataChannelReadyState?(): string | null;
14
+ }
15
+
16
+ export type { ITransport as I };
@@ -0,0 +1 @@
1
+ export{a as resolveOptions,b as wrapAssembly}from'./chunk-2QHDEGVX.js';import'./chunk-RD3JEGGF.js';import'./chunk-C7YN5MSV.js';
@@ -0,0 +1 @@
1
+ export{w as WasmBridge}from'./chunk-YBXGNKM7.js';import'./chunk-VK6KX433.js';import'./chunk-NT5YHZQH.js';import'./chunk-N26S7V4N.js';import'./chunk-NB4H5TP3.js';import'./chunk-RD3JEGGF.js';import'./chunk-C7YN5MSV.js';
@@ -1 +1 @@
1
- export{H as authHost,G as getAuthHost,F as registerDesktopAuthRelay}from'../chunk-OCSZA6PK.js';import'../chunk-C7YN5MSV.js';
1
+ import {c}from'../chunk-N4SX7C3W.js';export{d as authHost,b as getAuthHost,a as registerDesktopAuthRelay}from'../chunk-N4SX7C3W.js';import'../chunk-BXFXPIXO.js';import'../chunk-N26S7V4N.js';import'../chunk-NB4H5TP3.js';import'../chunk-RD3JEGGF.js';import'../chunk-C7YN5MSV.js';c();
@@ -1 +1 @@
1
- export{F as registerDesktopAuthRelay}from'../chunk-OCSZA6PK.js';import'../chunk-C7YN5MSV.js';
1
+ import {c}from'../chunk-N4SX7C3W.js';export{a as registerDesktopAuthRelay}from'../chunk-N4SX7C3W.js';import'../chunk-BXFXPIXO.js';import'../chunk-N26S7V4N.js';import'../chunk-NB4H5TP3.js';import'../chunk-RD3JEGGF.js';import'../chunk-C7YN5MSV.js';c();
@@ -98,4 +98,4 @@ declare function runtimeCapabilitiesForBrowserHost(host?: BrowserRuntimeCapabili
98
98
  declare function runtimeCapabilitiesFromNativeStatus(status: NativeRuntimeStatusSnapshot | null | undefined, allowWasmFallback?: boolean): RuntimeCapabilities;
99
99
  declare function runtimeCapabilityProfile(capabilities: RuntimeCapabilities): RuntimeCapabilityProfile;
100
100
 
101
- export { BROWSER_WASM_RUNTIME_CAPABILITIES as B, NATIVE_IPC_RUNTIME_CAPABILITIES as N, type RuntimeCapabilities as R, type RuntimeCapabilityProfile as a, type RuntimeAdapterKind as b, type BrowserRuntimeCapabilityHost as c, type NativeRuntimeStatusSnapshot as d, type NativeRuntimeTransportFeatureStatus as e, cloneRuntimeCapabilities as f, runtimeCapabilitiesFromNativeStatus as g, runtimeCapabilityProfile as h, runtimeCapabilitiesForBrowserHost as r };
101
+ export { BROWSER_WASM_RUNTIME_CAPABILITIES as B, NATIVE_IPC_RUNTIME_CAPABILITIES as N, type RuntimeCapabilities as R, type RuntimeCapabilityProfile as a, type BrowserRuntimeCapabilityHost as b, type NativeRuntimeStatusSnapshot as c, type NativeRuntimeTransportFeatureStatus as d, type RuntimeAdapterKind as e, cloneRuntimeCapabilities as f, runtimeCapabilitiesFromNativeStatus as g, runtimeCapabilityProfile as h, runtimeCapabilitiesForBrowserHost as r };
@@ -0,0 +1 @@
1
+ import {r}from'./chunk-RD3JEGGF.js';function O(i){let s=r({...i});if("auth"in i&&!i.authMode){let n=i.auth;s.authMode=n==="none"?"anonymous":n;}if("identity"in i){let n=i.identity,r=n==="temporary"?"ephemeral":n;!i.deviceIdPersistence&&!i.nodeIdPersistence&&(s.deviceIdPersistence=r),!i.endpointIdPersistence&&!i.nodeIdPersistence&&(s.endpointIdPersistence=r);}return "namespace"in i&&!i.storagePrefix&&(s.storagePrefix=i.namespace),"privacy"in i&&i.strictMode===void 0&&(s.strictMode=!!i.privacy),s}function I(i,s){let n=i.runtime,r=Object.create(n),l=async e=>{if(typeof e!="string")return e;let o=(await n.listDevices()).find(c=>c.deviceId===e);if(!o)throw new Error(`OpenRTC device '${e}' is not currently discoverable.`);return o},u=async e=>({...e,localDeviceId:e?.localDeviceId??await n.getLocalDeviceId()??""}),R=async e=>{let{device:t,scope:o,...c}=e,a=c.deviceId??(typeof t=="string"?t:t?.deviceId)??null,m=c.ticket??(typeof t=="string"?void 0:t?.ticket);a&&!m&&(m=(await l(a).catch(()=>null))?.ticket);let d={...c,scope:o??"session"};return a&&(d.deviceId=a),m&&(d.ticket=m),d},g={list:()=>n.listDevices(),startSession:(e={})=>n.startManagedSession({...e,platform:e.platform??s}),stopSession:e=>n.stopManagedSession(e),listWithStatus:()=>n.listDevicesWithStatus(),watch:e=>n.watchDevices(e),watchWithStatus:e=>n.watchDevicesWithStatus(e),connect:async(e,t)=>n.connectDevice(await l(e),await u(t)),connectWithRetry:async(e,t,o)=>n.connectDeviceWithRetry(await l(e),t,o),disconnect:e=>n.disconnectDevice(e),update:(e,t)=>n.updateDevice(e,t),delete:e=>n.deleteDevice(e),localId:()=>n.getLocalDeviceId(),localInfo:()=>n.getLocalDeviceInfo(),localProfile:e=>n.getLocalDeviceProfile(e),updateLocalName:e=>n.updateLocalDeviceName(e)},v={watch:e=>n.watchPeerStates(e),watchLifecycle:e=>n.watchPeerLifecycle(e),get:e=>n.getPeerState(e),listConnected:()=>n.listConnectedPeers(),connect:e=>n.connectPeer(e),disconnect:(e,t)=>n.disconnectPeer(e,t),forceDisconnect:e=>n.forceDisconnectPeer(e),session:e=>n.getPeerSession(e),sessions:()=>n.listPeerSessions(),waitConnected:(e,t)=>n.waitForConnectedPeer(e,t),readiness:(e,t)=>n.getPeerReadiness(e,t),health:e=>n.getPeerHealth(e),identity:e=>n.resolvePeerIdentity(e),addScope:(e,t)=>n.addPeerScope(e,t),releaseScope:(e,t)=>n.releasePeerScope(e,t),scopes:e=>n.getPeerScopes(e),refresh:()=>n.refreshPeerSnapshot()},C={register:e=>n.registerChannel(e),unregister:e=>n.unregisterChannel(e),list:()=>n.listChannels(),openBi:(e,t,o)=>n.openPeerBi(e,{...o,channelId:t}),openUni:(e,t,o)=>n.openPeerUni(e,{...o,channelId:t}),onIncoming:e=>n.onIncomingStream(e),onIncomingChannel:(e,t)=>n.onIncomingChannelStream(e,o=>{if(o.channel)return t(o)}),connect:async e=>n.connectScopedChannel(await R(e)),connectScoped:e=>n.connectScopedChannel(e)},P={create:e=>n.createRoom(e),join:(e,t)=>n.joinRoom(e,t),leave:e=>n.leaveRoom(e),watch:(e,t)=>n.watchRoom(e,t),members:e=>n.getRoomMembers(e)},h={raw:()=>n.getInvite(),share:e=>n.getTicketWithToken("share",e?.maxConnections??1),grant:(e,t)=>n.getTicketWithToken(e,t?.maxConnections??0),revoke:e=>n.revokeTokensByScope(e)},S={status:()=>n.getRuntimeStatus(),policy:()=>n.getRuntimePolicy(),capabilities:()=>n.getRuntimeCapabilities(),capabilityProfile:()=>n.getCapabilityProfile(),connectionStates:()=>n.getConnectionStates(),onConnectionStateChange:e=>n.onConnectionStateChange(e),connections:()=>n.getConnections(),applicationReadyConnections:e=>n.getApplicationReadyConnections(e),onConnection:e=>n.onConnection(e),onDisconnection:e=>n.onDisconnection(e),onConnectionEvent:e=>n.onConnectionEvent(e),forceReconnectSnapshot:()=>n.forceReconnectSnapshot(),peerReconciliation:()=>n.getPeerReconciliationStats()},b={runtime:n,assembly:i,nodeId:()=>n.getNodeId(),nodeIdFromTicket:e=>n.getNodeIdFromTicket(e),endpointTicket:()=>n.getEndpointTicket(),connectRaw:e=>n.connectRaw(e),openBi:e=>n.openBi(e),openUni:e=>n.openUni(e),isConnected:e=>n.isConnected(e),disconnectNode:e=>n.disconnectNode(e),setAutoConnectExcluded:(e,t)=>n.setAutoConnectExcluded(e,t),notifyNetworkChange:e=>n.notifyNetworkChange(e)};return Object.defineProperties(r,{devices:{get:()=>g,enumerable:true},peers:{get:()=>v,enumerable:true},channels:{get:()=>C,enumerable:true},rooms:{get:()=>P,enumerable:true},tickets:{get:()=>h,enumerable:true},diagnostics:{get:()=>S,enumerable:true},advanced:{get:()=>b,enumerable:true},setAuth:{value:e=>i.setAuthContext(e),enumerable:true,writable:true,configurable:true},setAuthContext:{value:e=>i.setAuthContext(e),enumerable:true,writable:true,configurable:true},syncPlutoAuth:{value:e=>i.syncPlutoAuth(e),enumerable:true,writable:true,configurable:true},bindPlutoAuthHost:{value:()=>i.bindPlutoAuthHost(),enumerable:true,writable:true,configurable:true},signIn:{value:()=>i.signInWithPluto(),enumerable:true,writable:true,configurable:true},signOut:{value:()=>i.signOut(),enumerable:true,writable:true,configurable:true},runtime:{get:()=>n,enumerable:false},_assembly:{get:()=>i,enumerable:false}}),r}export{O as a,I as b};
@@ -0,0 +1,2 @@
1
+ import {c,d as d$1,b}from'./chunk-K37WVIZL.js';import {a as a$2}from'./chunk-BXFXPIXO.js';import {a as a$1}from'./chunk-A3IAG6EL.js';import {o,u,w,s,h as h$1,g,j as j$2,k as k$1,l,m,n}from'./chunk-YBXGNKM7.js';import {c as c$1,b as b$1}from'./chunk-VK6KX433.js';import {c as c$2,b as b$2}from'./chunk-N26S7V4N.js';import {d,a}from'./chunk-NB4H5TP3.js';import {d as d$2,j as j$1}from'./chunk-RD3JEGGF.js';var H="relay-only endpoint ticket unavailable",Q=12e3,X=250,Z=1500;function ee(g){return String(g?.message??g??"").toLowerCase().includes(H)}async function E(g,e={}){let t=e.windowMs??Q,i=e.minDelayMs??X,a$1=e.maxDelayMs??Z,n=Date.now(),s=0,o=null;for(;e.isActive?.()??true;){s+=1;try{return await g()}catch(c){if(o=c,!ee(c))throw c;let d$1=Date.now()-n;if(d$1>=t)throw c;let r=Math.min(d(s,i,a$1),Math.max(0,t-d$1));r>0&&await a(r);}}throw o||new Error("endpoint ticket minting stopped before a ticket was available")}function Y(g){let e=g?.split(".")[1];if(!e)return null;try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4,a=atob(t+"=".repeat(i)),n=JSON.parse(a);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function k(g,e){let t=g?.[e];return typeof t=="string"&&t.trim()?t.trim():null}function j(g,e,t){let i=k(g,"namespaceId")===e||k(g,"appTag")===`space::${e}`,a=k(g,"developerAppTag");return i&&!!a&&(!t||a===t)}function ae(g){let e=k(g,"developerAppTag");if(e)return e;let t=k(g,"appTag");return t&&!t.startsWith("space::")?t:null}var h=class h{constructor(e){this.subscriptionNonce=0;this.lastSyncedAuthToken=null;this.cachedLocalDeviceId=null;this.cachedLocalDeviceName=null;this.tauriCoreAvailability=null;this.tauriCoreAvailabilityValue=null;this.tauriCoreAvailabilityCheckedAtMs=0;this.authSyncInFlight=null;this.nativeTrustTokenUnsubscribe=null;this.nativeTrustRelayQueue=Promise.resolve();this.nativeTrustRelayError=null;this.nativeRuntimeCapabilitiesSyncInFlight=null;this.gatewayDesiredPeersCleanup=null;this.gatewayDesiredPeerRelayKey=null;this.gatewayDesiredPeerRelayGeneration=0;this.gatewayDesiredPeerRevision=0;this.gatewayDesiredPeerSubmission=Promise.resolve();this.gatewayDesiredPeerLifecycle=Promise.resolve();this.gatewayExcludedPeers=new Set;this.lastNativeAuthSyncAtMs=0;this.runtimeCapabilities=u(null,false);this.fallback=new w({...e,coordinationPlatformType:"desktop"}),this.app=this.fallback.app,this.auth=this.fallback.auth,this.appTag=this.fallback.tag,this.options=this.fallback.getResolvedOptions(),this.transportOptions=e.transports,this.strictMode=e.strictMode===true,this.turnCredentialsProvider=e.turnCredentialsProvider,this.allowWasmFallback=e.allowWasmFallback??false,this.ipcBridge=c(e.ipcBridge??d$1(),"NativeIpcBridge"),this.runtimeCapabilities=u(null,this.allowWasmFallback),this.syncNativeRuntimeCapabilities("constructor");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}getRuntimeCapabilities(){let e=s(this.runtimeCapabilities);return e.fallback.wasm=this.allowWasmFallback,e}usesCoordinationGateway(){return this.fallback.usesCoordinationGateway()}assertManagedCoordinationGateway(){if(!this.usesCoordinationGateway())throw new Error("[OpenRTC] Native managed coordination requires coordinationGateway; the legacy native Firebase data plane has been removed.")}async joinCoordinationRoom(e,t,i){await this.syncCoordinationDeviceIdentity(),await this.fallback.joinCoordinationRoom(e,t,i);}leaveCoordinationRoom(e){return this.fallback.leaveCoordinationRoom(e)}getCoordinationRoomMembers(e){return this.fallback.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){return this.fallback.watchCoordinationRoomMembers(e,t)}async syncCoordinationDeviceIdentity(){if(!this.usesCoordinationGateway())return;let e=await this.getLocalDeviceInfo().catch(()=>null),t=e?.deviceId||await this.resolveLocalDeviceId();this.fallback.setCoordinationLocalDeviceId(t),this.fallback.setCoordinationPlatformType(this.normalizeNativeCoordinationPlatform(e?.platformType));}setWasmClient(e){if(!this.allowWasmFallback){let t="[NativeIpcBridge][NATIVE-GUARD] Refusing WasmClient attachment because native IPC is authoritative and WASM fallback is disabled.";throw console.error(t,{capabilities:this.getRuntimeCapabilities()}),new Error(t)}this.fallback.setWasmClient(e);}onAuthChange(e){return this.fallback.onAuthChange(e)}checkForSSOToken(){return this.fallback.checkForSSOToken()}waitForAuth(){return this.fallback.waitForAuth()}signInAnonymously(){return this.fallback.signInAnonymously()}getTurnCredentials(){return this.fallback.getTurnCredentials()}cleanupStaleDevices(){return this.fallback.cleanupStaleDevices()}sendMessage(e,t,i,a){return this.fallback.sendMessage(e,t,i,a)}pollMessages(e){return this.fallback.pollMessages(e)}watchFriendDevices(e,t){return this.assertManagedCoordinationGateway(),this.fallback.watchFriendDevices(e,t)}async updateFriendTicket(e){this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),await this.fallback.updateFriendTicket(e);}createSession(e){return this.fallback.createSession(e)}updateSession(e,t){return this.fallback.updateSession(e,t)}async openPeerBi(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_stream",{peerId:e,timeoutMs:t??null}):this.fallback.openPeerBi(e,t)}async openPeerBiTransportOnly(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_transport_only_stream",{peerId:e,timeoutMs:t??null},{fallbackCommand:"open_peer_bi_stream"}):this.fallback.openPeerBiTransportOnly(e,t)}async openPeerNativeBi(e,t,i){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_native_bi_stream",{peerId:e,label:t,timeoutMs:i??null},{fallbackCommand:"open_peer_bi_stream",fallbackArgs:{peerId:e,timeoutMs:i??null}}):this.fallback.openPeerNativeBi(e,t,i)}async incoming_streams(){if(!await this.canUseTauriIpc()){let n=this.fallback;if(typeof n.incoming_streams=="function")return n.incoming_streams();throw new Error("Native incoming stream bridge is unavailable")}let e=`native-incoming-${Date.now()}-${++this.subscriptionNonce}`,t=null,i=false,a=async()=>{i=true;let n=t;t=null,await Promise.allSettled([n?Promise.resolve(n()):Promise.resolve(),this.invokeIpc("stop_rtc_subscription",{requestId:e},{timeoutMs:null}).catch(()=>{})]);};return new ReadableStream({start:async n=>{try{t=await this.listenIpc("openrtc://peer-bi-stream/incoming",s=>{if(i)return;let o=s.payload,c=typeof o?.requestId=="string"?o.requestId:typeof o?.request_id=="string"?o.request_id:"";if(c!==e){c$1("[NativeIpcBridge][incoming-application-stream] ignored request id",{expectedRequestId:e,eventRequestId:c});return}let d=typeof o?.streamId=="string"?o.streamId.trim():typeof o?.stream_id=="string"?o.stream_id.trim():"";if(!d)return;let r=typeof o?.remoteNodeId=="string"?o.remoteNodeId.trim():typeof o?.remote_node_id=="string"?o.remote_node_id.trim():"",l=Number.isSafeInteger(o?.transportStableId)?Number(o.transportStableId):Number.isSafeInteger(o?.transport_stable_id)?Number(o.transport_stable_id):0;if(!r||l<=0){c$1("[NativeIpcBridge][incoming-application-stream] ignored invalid generation",{requestId:e,remoteNodeId:r,transportStableId:l});return}c$1("[NativeIpcBridge][incoming-application-stream] accepted event",{requestId:e,remoteNodeId:r,transportStableId:l});let u=this.peerBiStreamFromId(d,{startReadAfterListeners:!0});n.enqueue({type:"bi",stream:{send:u.writable,recv:u.readable,endpoint_id:r},endpointId:r,transportStableId:l,protocolHint:"unknown",channel:null});}),await this.invokeIpc("start_incoming_peer_bi_streams",{requestId:e},{timeoutMs:null});}catch(s){i=true,n.error(s),await a();}},cancel:async()=>{await a();}})}async is_current_transport_stable_id(e,t){if(!await this.canUseTauriIpc()){let i=this.fallback;return typeof i.is_current_transport_stable_id=="function"?i.is_current_transport_stable_id(e,t):false}return !e.trim()||t<=0n||t>BigInt(Number.MAX_SAFE_INTEGER)?false:this.invokeIpc("is_current_transport_stable_id",{endpointId:e.trim(),transportStableId:Number(t)})}openPeerUni(e,t){return this.fallback.openPeerUni(e,t)}isConnected(e){return this.fallback.isConnected(e)}getAuthContext(){return this.fallback.getAuthContext()}resolveNativeAuthScopedUserId(e){return this.currentUser?.id??this.getAuthContext()?.userId??e??null}resolveConfiguredSpaceKey(){let e=this.options.spaceKey??this.options.space;return typeof e=="string"?e.trim():""}usesAnonymousSpaceMode(){return this.options.authMode==="anonymous"&&this.resolveConfiguredSpaceKey().length>0}requiresNativeAuthToken(){return !this.usesAnonymousSpaceMode()||typeof this.options.spaceTokenProvider=="function"}async nativeAuthTokenMatchesExpectedScope(e){if(!this.usesAnonymousSpaceMode())return true;let t=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",i=this.resolveConfiguredSpaceKey();if(!t||!i)return true;let a=await d$2(t,i).catch(()=>null);return a?j(Y(e),a):true}resolveNativeSignalingUserId(e){return this.usesAnonymousSpaceMode()?(typeof e=="string"?e.trim():"")||this.resolveConfiguredSpaceKey()||null:this.resolveNativeAuthScopedUserId(e)}getCurrentUserId(){return this.resolveNativeSignalingUserId(this.fallback.getCurrentUserIdForScope())}nativeAuthWaitMs(){return this.requiresNativeAuthToken()?h.AUTH_REQUIRED_WAIT_MS:0}resolveWebLogicalDeviceId(){return this.fallback.getResolvedWebLogicalDeviceId()}normalizeDevice(e,t){return this.fallback.normalizeDeviceRecord(e,t)}matchesTag(e){return this.fallback.matchesLegacyOrCurrentTag(e)}nativeRosterTagDisposition(e){let t=h$1(e);if(this.matchesTag(t))return {keep:true,classification:"match"};let i=typeof t.appTag=="string"&&t.appTag.trim().length>0?t.appTag.trim():typeof t.tag=="string"&&t.tag.trim().length>0?t.tag.trim():void 0;return i===void 0?{keep:true,classification:"untagged"}:{keep:false,classification:"foreign",foreignTag:i}}filterNativeRosterByTag(e,t){let i=new Set,a=e.filter(n=>{let s=this.nativeRosterTagDisposition(n);return !s.keep&&s.foreignTag&&i.add(s.foreignTag),s.keep});return e.length>0&&a.length===0&&i.size>0?console.warn(`[NativeIpcBridge] ${t}: dropped ALL ${e.length} native device(s) as foreign-app \u2014 this is the app-tag drift signature (empty native device list). The native Rust OpenRTC app tag does not match the SDK app tag; check that the desktop binary and the web bundle use the same VITE_PLUTO_OPENRTC_API_KEY / VITE_PLUTO_OPENRTC_APP_TAG for this environment lane.`,{sdkAppTag:this.appTag,foreignTags:Array.from(i),droppedCount:e.length}):i.size>0&&c$1(`[NativeIpcBridge] ${t}: filtered ${e.length-a.length} foreign-app device(s) from the native roster`,{sdkAppTag:this.appTag,foreignTags:Array.from(i)}),a}normalizeNativeIceServer(e){let t=e.urls,i=Array.isArray(t)?t.filter(a=>typeof a=="string"&&a.trim().length>0):typeof t=="string"&&t.trim().length>0?[t]:[];return i.length===0?null:{urls:i,username:typeof e.username=="string"&&e.username.trim().length>0?e.username:void 0,credential:typeof e.credential=="string"&&e.credential.trim().length>0?e.credential:void 0}}filterNativeStunServers(e){return e.map(t=>({...t,urls:t.urls.filter(i=>!i.startsWith("stun:"))})).filter(t=>t.urls.length>0)}nativeIceServerHasTurnUrl(e){return e.urls.some(t=>t.startsWith("turn:")||t.startsWith("turns:"))}async loadNativeTurnIceServers(){if(typeof this.turnCredentialsProvider!="function")return [];let e=await this.turnCredentialsProvider().catch(t=>(console.warn("[NativeIpcBridge] TURN credential provider failed:",t),null));return !e||!Array.isArray(e.iceServers)?[]:e.iceServers.map(t=>this.normalizeNativeIceServer(t)).filter(t=>!!t)}async buildNativeTransportConfigPayload(){let e=this.transportOptions;if(!e&&!this.strictMode)return null;let t;!this.strictMode&&e?.iroh&&(typeof e.iroh=="object"&&e.iroh.localDiscovery===false?t=null:t={enabled:true,advertise:typeof e.iroh!="object"||e.iroh.localDiscoveryMode!=="passive"});let i=null;if(e?.webrtc===true||e?.webrtc&&typeof e.webrtc=="object"){let d=e.webrtc===true?null:e.webrtc,r=d?.useDefaultIceServers!==false,l=Array.isArray(d?.iceServers)&&d.iceServers.length>0?d.iceServers.map(y=>this.normalizeNativeIceServer(y)).filter(y=>!!y):r?j$1.map(y=>this.normalizeNativeIceServer(y)).filter(y=>!!y):[],u=this.strictMode||d?.privacyMode===true;(this.strictMode||d?.privacyMode===true||d?.useTurn===true)&&(l=[...l,...await this.loadNativeTurnIceServers()]),u&&(l=this.filterNativeStunServers(l));let m=l.some(y=>this.nativeIceServerHasTurnUrl(y)),v=u&&m;u&&!m&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let _=d?.lanMode===true;(l.length>0||v||_||!r)&&(i={iceServers:l.length>0||!r?l:void 0,privacyMode:v,lanMode:_||void 0});}let a=null;if(e?.moq&&typeof e.moq=="object"){let d=typeof e.moq.relayUrl=="string"&&e.moq.relayUrl.trim().length>0?e.moq.relayUrl:void 0;if(d){let r=typeof e.moq.accessToken=="string"&&e.moq.accessToken.trim().length>0?e.moq.accessToken.trim():void 0;a={relayUrl:d,accessToken:r};}}let n=null;if(!this.strictMode&&(e?.ble===true||e?.ble&&typeof e.ble=="object")){let d=e.ble===true?null:e.ble,r=Number(d?.connectTimeoutMs);n={enabled:d?.enabled!==false,connectTimeoutMs:Number.isFinite(r)&&r>0?Math.round(r):void 0};}let s=this.strictMode||e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true,o=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,c=this.strictMode?o??"auto":o;return !s&&!c&&!i&&!a&&!t&&!n?null:{irohRelayOnly:s||void 0,irohRelayTransportPolicy:c,...t!==void 0?{irohLan:t}:{},webrtc:i,moq:a,ble:n}}isTauriEnv(){return c$2()}nextConnectionEventRetryDelayMs(e){return d(e,h.CONNECTION_EVENT_RETRY_MIN_DELAY_MS,h.CONNECTION_EVENT_RETRY_MAX_DELAY_MS)}async clearNativeAuthRelay(e){if(await this.canUseTauriIpc())try{typeof this.options.coordinationGateway?.grantProvider=="function"?await this.invokeIpc("openrtc_v2_set_identity_credential",{identityCredential:null}):await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:null,refreshToken:null}),this.lastSyncedAuthToken=null,this.lastNativeAuthSyncAtMs=0,c$1(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}async clearNativeTrustRelay(e){if(this.nativeTrustTokenUnsubscribe?.(),this.nativeTrustTokenUnsubscribe=null,this.nativeTrustRelayError=null,this.fallback.invalidateCoordinationNativeTrustToken(),typeof this.options.coordinationGateway?.grantProvider!="function"&&await this.canUseTauriIpc())try{await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:null,expiresAtMs:null}),c$1(`[NativeIpcBridge] cleared native trust relay (${e})`);}catch(t){b(t)||console.warn(`[NativeIpcBridge] failed clearing native trust relay (${e}):`,t);}}relayNativeTrustToken(e,t){let i=async()=>{await this.canUseTauriIpc()&&(await this.invokeIpc("openrtc_set_native_trust_token",{trustToken:e?.token??null,expiresAtMs:e?.expiresAtMs??null}),c$1(`[NativeIpcBridge] native trust token ${e?"relayed":"cleared"} (${t})`));},a=this.nativeTrustRelayQueue.then(i,i);return this.nativeTrustRelayQueue=a.catch(()=>{}),a}async ensureNativeTrustRelay(e=false){if(!this.usesCoordinationGateway()||typeof this.options.coordinationGateway?.grantProvider=="function")return true;if(typeof this.options.coordinationGateway?.nativeTrustTokenProvider!="function")return false;if(!await this.canUseTauriIpc())return true;try{let t=await this.fallback.getCoordinationNativeTrustToken(e);return await this.relayNativeTrustToken(t,"auth-ready"),this.nativeTrustRelayError=null,this.nativeTrustTokenUnsubscribe||(this.nativeTrustTokenUnsubscribe=this.fallback.subscribeCoordinationNativeTrustToken(i=>{this.relayNativeTrustToken(i,"provider-refresh").catch(a=>{console.warn("[NativeIpcBridge] native trust token refresh relay failed:",a);});},{emitCurrent:!1})),!0}catch(t){return this.nativeTrustRelayError=(t instanceof Error?t.message:String(t)).trim().slice(0,300)||"unknown provider failure",console.warn("[NativeIpcBridge] native trust token unavailable:",t),false}}async relayNativeAuthToken(e,t,i,a){if(!await this.canUseTauriIpc())return true;if(!await this.nativeAuthTokenMatchesExpectedScope(e))return c$1(`[NativeIpcBridge] auth sync deferred (${i}): token claims do not match configured space`),false;if(e===this.lastSyncedAuthToken)return true;try{typeof this.options.coordinationGateway?.grantProvider=="function"?await this.invokeIpc("openrtc_v2_set_identity_credential",{identityCredential:e}):await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:e,refreshToken:t??null});}catch(n){return b(n)?console.warn(`[NativeIpcBridge] desktop auth relay unavailable (${i}); install/register openrtc-tauri-plugin and include its default permission set.`,n):console.warn(`[NativeIpcBridge] desktop auth relay failed (${i}):`,n),false}return this.lastSyncedAuthToken=e,this.lastNativeAuthSyncAtMs=Date.now(),c$1(`[NativeIpcBridge] auth token relayed to native runtime (${i}) user_id=${a??this.currentUser?.id??"unknown"}`),true}async relayExplicitNativeAuthContext(e){let t=this.authSyncInFlight,i=(async()=>(await t?.catch(()=>{}),this.relayNativeAuthToken(e.token,e.refreshToken,"setAuthContext",e.userId)))();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}applyNativeRuntimeStatus(e){this.runtimeCapabilities=u(e,this.allowWasmFallback);}syncNativeRuntimeCapabilities(e){return this.ipcBridge?this.nativeRuntimeCapabilitiesSyncInFlight?this.nativeRuntimeCapabilitiesSyncInFlight:(this.nativeRuntimeCapabilitiesSyncInFlight=(async()=>{try{let t=await this.invokeIpc("rtc_native_status",void 0,{timeoutMs:h.NATIVE_STATUS_IPC_TIMEOUT_MS});this.applyNativeRuntimeStatus(t),c$1(`[NativeIpcBridge] refreshed native runtime capabilities (${e})`);}catch(t){b$1("[NativeIpcBridge] native runtime capability refresh skipped",t);}})().finally(()=>{this.nativeRuntimeCapabilitiesSyncInFlight=null;}),this.nativeRuntimeCapabilitiesSyncInFlight):Promise.resolve()}async canUseTauriIpc(){if(this.ipcBridge){let e=typeof this.ipcBridge.isAvailable=="function"?!!await this.ipcBridge.isAvailable():true;return e&&this.syncNativeRuntimeCapabilities("ipc-available"),e}return typeof window>"u"?false:this.tauriCoreAvailabilityValue===true?true:this.tauriCoreAvailabilityValue===false&&Date.now()-this.tauriCoreAvailabilityCheckedAtMs<h.TAURI_IPC_NEGATIVE_CACHE_MS?false:(this.tauriCoreAvailability||(this.tauriCoreAvailability=(async()=>{try{if(this.isTauriEnv())return this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),this.syncNativeRuntimeCapabilities("tauri-env"),!0;try{let e=await this.invokeIpc("rtc_native_status");return this.applyNativeRuntimeStatus(e),c$1("[NativeIpcBridge] Resolved Tauri IPC via rtc_native_status probe"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0}catch(e){let t=String(e?.message??e??"");return t.includes("__TAURI_INTERNALS__")||t.includes("Cannot read properties of undefined")||t.includes("window is not defined")?(this.tauriCoreAvailabilityValue=!1,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!1):(c$1("[NativeIpcBridge] Tauri IPC probe reached native layer (command-level error acceptable)"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0)}}catch{return this.tauriCoreAvailabilityValue=false,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),false}})().finally(()=>{this.tauriCoreAvailability=null;})),this.tauriCoreAvailability)}async invokeIpc(e,t,i){let a=this.ipcBridge.invoke(e,t),n=i&&Object.prototype.hasOwnProperty.call(i,"timeoutMs")?i.timeoutMs:h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS;return n==null||n<=0?a:a$2(a,n,()=>new Error(`${e} timeout after ${n}ms`))}async listenIpc(e,t){return this.ipcBridge.listen(e,i=>{t({payload:i});})}async openPeerBiViaIpc(e,t,i){let a=await this.invokePeerBiOpen(e,t,i),n=typeof a?.streamId=="string"?a.streamId.trim():typeof a?.stream_id=="string"?a.stream_id.trim():"";if(!n)throw new Error(`${e} returned no streamId`);return this.peerBiStreamFromId(n)}peerBiStreamFromId(e,t={}){let i=this,a=null,n=null,s=false,o=null,c=null,d=async()=>{let m=[a,n];a=null,n=null,await Promise.allSettled(m.filter(v=>typeof v=="function").map(v=>Promise.resolve(v())));},r=(async()=>{a=await this.listenIpc("openrtc://peer-bi-stream/chunk",m=>{let v=m.payload;if((typeof v?.streamId=="string"?v.streamId:typeof v?.stream_id=="string"?v.stream_id:"")!==e||s||!o)return;let f=v?.bytes;f instanceof Uint8Array?o.enqueue(f):Array.isArray(f)&&o.enqueue(new Uint8Array(f));}),n=await this.listenIpc("openrtc://peer-bi-stream/closed",m=>{let v=m.payload;if((typeof v?.streamId=="string"?v.streamId:typeof v?.stream_id=="string"?v.stream_id:"")!==e||s||!o)return;s=true;let f=typeof v?.error=="string"?v.error.trim():"";f?o.error(new Error(f)):o.close(),d();}),t.startReadAfterListeners&&await this.invokeIpc("start_peer_bi_stream_read",{streamId:e},{timeoutMs:null});})().catch(m=>{c=m,o&&!s&&(s=true,o.error(m));}),l=async()=>{await this.invokeIpc("close_peer_bi_stream",{streamId:e},{timeoutMs:null}).catch(()=>{}),await d();},u=new ReadableStream({async start(m){o=m,await r,c&&!s&&(s=true,m.error(c));},async cancel(){s=true,await l();}}),I=new WritableStream({write:async m=>{await i.invokeIpc("write_peer_bi_stream",{streamId:e,bytes:Array.from(m)},{timeoutMs:null});},close:l,abort:l});return {readable:u,writable:I}}async invokePeerBiOpen(e,t,i){try{return await this.invokeIpc(e,t)}catch(a){if(!i?.fallbackCommand||!this.isMissingNativeCommandError(a))throw a;return this.invokeIpc(i.fallbackCommand,i.fallbackArgs??t)}}isMissingNativeCommandError(e){let t=e instanceof Error?e.message:String(e??"");return t.includes("Command")&&t.includes("not found")}async shouldUseTauriSignaling(){if(await this.canUseTauriIpc())return true;if(this.allowWasmFallback)return false;throw new Error("[pluto-rtc] Tauri runtime adapter requires native IPC, but it is unavailable.")}async signInWithPluto(){if(!await this.canUseTauriIpc()){await this.fallback.signInWithPluto();return}let e=await this.invokeIpc("rtc_sign_in_with_pluto"),t=typeof e?.customToken=="string"?e.customToken.trim():"";if(!t)throw new Error("[pluto-rtc] Native Pluto SSO did not return a custom token.");await b$2().signInWithCustomTokenValue(t),await this.ensureNativeAuth("pluto-sso",{requireToken:true,maxWaitMs:1e4});}async setAuthContext(e){let t=this.getAuthContext()?.userId??null,i=typeof e?.userId=="string"&&e.userId.trim()||null,a=this.fallback.setAuthContext(e);if(t&&i&&t!==i&&await this.stopNativeAuthScopedActivity(t),await a,!e?.token)await this.clearNativeAuthRelay("setAuthContext"),await this.clearNativeTrustRelay("setAuthContext");else {if(!await this.relayExplicitNativeAuthContext(e))throw new Error("Native auth token unavailable for setAuthContext");if(!await this.ensureNativeTrustRelay())throw new Error(`Native trust token unavailable for setAuthContext: ${this.nativeTrustRelayError??"unknown provider failure"}`)}}async signOut(){await this.fallback.signOut(),await Promise.all([this.clearNativeAuthRelay("signOut"),this.clearNativeTrustRelay("signOut")]);}async stopAuthScopedActivity(e){let t=this.resolveNativeSignalingUserId(e?.userId??null);await this.stopNativeAuthScopedActivity(t);}async stopNativeAuthScopedActivity(e){await this.stopGatewayDesiredPeerRelay(),this.gatewayExcludedPeers.clear();let t=await this.shouldUseTauriSignaling();if(g("NativeIpcBridge.stopAuthScopedActivity",{userId:e,useTauri:t}),t)try{await Promise.allSettled([this.revokeSessionTokensByScope("user-device"),this.invokeIpc("stop_rtc_presence_loop"),this.invokeIpc("stop_rtc_auto_connect")]);}catch(i){console.warn("[NativeIpcBridge] Failed to stop native auth-scoped RTC activity:",i);}await this.fallback.stopAuthScopedActivity({userId:e});}async ensureNativeAuthOnce(e,t){if(!await this.canUseTauriIpc())return true;if(this.authSyncInFlight)return this.authSyncInFlight;let i=(async()=>{try{if(!this.currentUser)return c$1(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let a=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,n=this.currentUser?.getToken?await this.currentUser.getToken(a):null,o=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;return n?this.relayNativeAuthToken(n,o,e,this.currentUser?.id):(c$1(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t)}catch(a){return console.error("[NativeIpcBridge] auth sync failed:",a),false}})();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}async ensureNativeAuth(e="runtime",t){if(!await this.canUseTauriIpc())return true;let i=t?.requireToken??false,a$1=t?.maxWaitMs??(i?h.AUTH_REQUIRED_WAIT_MS:0),n=t?.pollMs??250,s=Date.now()+Math.max(0,a$1);for(;;){if(await this.ensureNativeAuthOnce(e,i))return true;if(!i||Date.now()>=s)return false;await a(n);}}decodeNativeDeviceIdentity(e){let t=e?.systemInfo??e?.system_info??null,i=typeof e?.deviceId=="string"?e.deviceId.trim():typeof e?.device_id=="string"?e.device_id.trim():"",a=typeof e?.deviceName=="string"?e.deviceName.trim():typeof e?.device_name=="string"?e.device_name.trim():"",n=typeof e?.platformType=="string"?e.platformType.trim():typeof e?.platform_type=="string"?e.platform_type.trim():typeof t?.platformType=="string"?t.platformType.trim():typeof t?.platform_type=="string"?t.platform_type.trim():"";return {deviceId:i,deviceName:a,platformType:n}}async resolveLocalDeviceId(){if(this.cachedLocalDeviceId)return this.cachedLocalDeviceId;if(await this.canUseTauriIpc())try{let t=await this.invokeIpc("get_rtc_local_device_info"),{deviceId:i,deviceName:a}=this.decodeNativeDeviceIdentity(t);if(i)return this.cachedLocalDeviceId=i,a&&(this.cachedLocalDeviceName=a),i}catch(t){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",t);}let e=this.resolveWebLogicalDeviceId();return this.cachedLocalDeviceId=e,e}async resolveLocalDeviceName(){if(this.cachedLocalDeviceName)return this.cachedLocalDeviceName;if(await this.canUseTauriIpc())try{let e=await this.invokeIpc("get_rtc_local_device_info"),{deviceName:t}=this.decodeNativeDeviceIdentity(e);if(t){let i=this.normalizeNativeDeviceName(t);return this.cachedLocalDeviceName=i,i}}catch(e){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",e);}return this.defaultDeviceNameFallback()}normalizeNativeDeviceName(e){let t=e.trim();if(!t)return this.defaultDeviceNameFallback();if(t==="Desktop Device"){let i=this.defaultDeviceNameFallback();if(i!=="Desktop Device")return i}return t}defaultDeviceNameFallback(){if(typeof window>"u"||typeof navigator>"u")return "Desktop Device";let e=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(e)?"iPhone":/Android/i.test(e)?"Android":"Desktop Device"}inferNativePlatformTypeFallback(){if(typeof window>"u"||typeof navigator>"u")return "desktop";if(!this.isTauriEnv())return "web";let e=navigator.userAgent||"";return /iPhone|iPad|iPod|Android|Mobile/i.test(e)?"mobile":"desktop"}normalizeNativeCoordinationPlatform(e){let t=e?.trim().toLowerCase()??"";return t==="mobile"||t==="ios"||t==="android"||t.includes("iphone")||t.includes("ipad")||this.inferNativePlatformTypeFallback()==="mobile"?"mobile":"desktop"}withPresenceMetadata(e,t){try{let i=e?JSON.parse(e):{};return JSON.stringify({...i,deviceId:t,plutoVersion:"0.1.0-desktop"})}catch{return JSON.stringify({deviceId:t,plutoVersion:"0.1.0-desktop",rawMetadata:e})}}async searchDevices(e){return this.assertManagedCoordinationGateway(),this.fallback.searchDevices(e)}async listDevicesWithStatus(){return this.assertManagedCoordinationGateway(),(await this.fallback.searchDevices()).map(e=>j$2(e))}async getPeerSession(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("get_rtc_peer_session",{id:e});return !t||typeof t!="object"?null:k$1(t)}return this.fallback.getPeerSession(e)}async listPeerSessions(){if(await this.shouldUseTauriSignaling()){let e=await this.invokeIpc("list_rtc_peer_sessions");return (Array.isArray(e)?e:[]).map(t=>k$1(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let i=typeof t=="number"?Math.max(h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,t+1e3):h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,a=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:i});return !a||typeof a!="object"?null:k$1(a)}return this.fallback.waitForSettledPeer(e,t)}async resolvePeerConnectionRecords(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_connection_records",{id:e});return (Array.isArray(t)?t:[]).map(i=>l(i))}return this.fallback.resolvePeerConnectionRecords(e)}async resolvePeerIdentity(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("resolve_rtc_peer_identity",{id:e});return m(t)}return this.fallback.resolvePeerIdentity(e)}async setOffline(e){return this.assertManagedCoordinationGateway(),this.fallback.setOffline(e)}async updateDevice(e,t){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.updateDevice(e,t)}async deleteDevice(e){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.deleteDevice(e)}async getLocalDeviceInfo(){if(!await this.canUseTauriIpc()){let e=await this.getLocalDeviceId?.();return e?{deviceId:e,deviceName:this.defaultDeviceNameFallback(),platformType:this.inferNativePlatformTypeFallback()}:null}try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=this.decodeNativeDeviceIdentity(e),{deviceId:i}=t;return i?{deviceId:i,deviceName:this.normalizeNativeDeviceName(t.deviceName),platformType:t.platformType||this.inferNativePlatformTypeFallback(),capabilities:e?.capabilities??void 0,lastSeenAt:typeof e?.last_seen_at=="string"?e.last_seen_at:void 0}:null}catch(e){return console.warn("[NativeIpcBridge] getLocalDeviceInfo failed:",e),null}}async updateLocalDeviceName(e){if(!await this.canUseTauriIpc())return null;try{let t=await this.invokeIpc("update_rtc_local_device_name",{deviceName:e}),i=this.decodeNativeDeviceIdentity(t),{deviceId:a}=i;return a?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:a,deviceName:this.cachedLocalDeviceName,platformType:i.platformType||this.inferNativePlatformTypeFallback(),capabilities:t?.capabilities??void 0,lastSeenAt:typeof t?.last_seen_at=="string"?t.last_seen_at:void 0}):null}catch(t){return console.warn("[NativeIpcBridge] updateLocalDeviceName failed:",t),null}}async startManagedSessionNative(e){if(this.assertManagedCoordinationGateway(),!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startManagedSessionNative().");if(!await this.ensureNativeAuth("startManagedSessionNative",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startManagedSessionNative");let i=this.resolveNativeSignalingUserId(e.userId);if(!i)throw new Error("Native managed session startup requires a runtime auth-scoped user id.");i!==e.userId&&console.info("[NativeIpcBridge][managed-session][user-id-remap]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i}),console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,presence:e.presence!==false,autoConnect:e.autoConnect!==false,hasMetadata:typeof e.metadata=="string"&&e.metadata.trim().length>0});let a=await this.buildNativeTransportConfigPayload(),n={userId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...a?{transports:a}:{},autoConnect:false,presence:false},s=await this.invokeIpc("start_rtc_managed_session",n,{timeoutMs:null});this.syncNativeRuntimeCapabilities("managed-session-started");let o=typeof s?.ticket=="string"&&s.ticket.trim().length>0?s.ticket.trim():null,c=s?.localDevice&&typeof s.localDevice=="object"?s.localDevice:s?.local_device&&typeof s.local_device=="object"?s.local_device:null,d=c?{deviceId:typeof c.deviceId=="string"?c.deviceId:typeof c.device_id=="string"?c.device_id:"",deviceName:this.normalizeNativeDeviceName(typeof c.deviceName=="string"?c.deviceName:typeof c.device_name=="string"?c.device_name:""),platformType:typeof c.platformType=="string"?c.platformType:typeof c.platform_type=="string"?c.platform_type:"desktop",capabilities:c.capabilities??void 0,lastSeenAt:typeof c.lastSeenAt=="string"?c.lastSeenAt:typeof c.last_seen_at=="string"?c.last_seen_at:void 0}:null,r={localNodeId:typeof s?.localNodeId=="string"?s.localNodeId:typeof s?.local_node_id=="string"?s.local_node_id:null,ticket:o,ticketScope:typeof s?.ticketScope=="string"?s.ticketScope:typeof s?.ticket_scope=="string"?s.ticket_scope:null,presenceStarted:typeof s?.presenceStarted=="boolean"?s.presenceStarted:!!s?.presence_started,autoConnectStarted:typeof s?.autoConnectStarted=="boolean"?s.autoConnectStarted:!!s?.auto_connect_started,localDevice:d?.deviceId?d:null};if(this.usesCoordinationGateway()){e.presence!==false&&!r.ticket&&(r.ticket=await this.getEndpointTicketWithToken("user-device",0),r.ticketScope=r.ticket?"user-device":null);let l=r.localDevice?.deviceId||e.localDeviceId?.trim()||await this.resolveLocalDeviceId();if(l&&this.fallback.setCoordinationLocalDeviceId(l),this.fallback.setCoordinationPlatformType(this.normalizeNativeCoordinationPlatform(r.localDevice?.platformType)),e.presence!==false){if(!r.localNodeId||!r.ticket)throw new Error("Native managed session did not return the node identity required for gateway presence.");await this.fallback.updatePresence(r.localNodeId,r.ticket,true,3e5,e.metadata,r.localDevice?.deviceName||e.deviceName),r.presenceStarted=true;}else r.presenceStarted=false;e.autoConnect!==false&&l?(await this.startGatewayAutoConnect(i,l),r.autoConnectStarted=true):r.autoConnectStarted=false;}return console.info("[NativeIpcBridge][managed-session][ipc-started]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,localNodeId:r.localNodeId,ticketScope:r.ticketScope,presenceStarted:r.presenceStarted,autoConnectStarted:r.autoConnectStarted,localDeviceId:r.localDevice?.deviceId??null}),r}async reconcileNativeManagedSession(e){return this.assertManagedCoordinationGateway(),await this.fallback.reconnectCoordinationAfterHostResume(),console.info("[NativeIpcBridge] reattached gateway coordination after host resume.",{reason:e?.reason??"frontend"}),null}async notifyNetworkChange(e){return await this.canUseTauriIpc()?(c$1("[NativeIpcBridge] forwarding host network-change hint",{reason:e?.reason??"host"}),this.invokeIpc("notify_rtc_network_change")):null}async getManagedNodeId(e){let t=e?.initializeIfMissing??true;console.info("[NativeIpcBridge][getManagedNodeId] enter",{initializeIfMissing:t});let i=await this.canUseTauriIpc();if(console.info("[NativeIpcBridge][getManagedNodeId] canUseTauriIpc",{canUse:i}),!i)return null;try{console.info("[NativeIpcBridge][getManagedNodeId] invoking get_iroh_node_id");let a=await this.invokeIpc("get_iroh_node_id");if(console.info("[NativeIpcBridge][getManagedNodeId] get_iroh_node_id returned",{existing:a}),a||!t)return a;console.info("[NativeIpcBridge][getManagedNodeId] invoking start_iroh_node");let n=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:n}),n}catch(a){if(console.warn("[NativeIpcBridge] getManagedNodeId failed:",a),!t)return null;throw a}}async getEndpointTicket(){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] getEndpointTicket requires native IPC in Tauri runtime.");return E(()=>this.invokeIpc("get_iroh_endpoint_ticket"))}async connectToDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] connectToDevice requires native IPC in Tauri runtime.");this.options.authMode!=="anonymous"?await this.ensureNativeAuth("connectToDevice",{requireToken:true,maxWaitMs:h.AUTH_REQUIRED_WAIT_MS}):c$1("[NativeIpcBridge] connectToDevice using anonymous native ticket path");let t=Math.max(1,Math.floor(e.timeoutMs??h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS));return this.invokeIpc("connect_to_device",{deviceId:e.deviceId??null,endpointTicket:e.endpointTicket,timeoutMs:t},{timeoutMs:t+1e3})}async registerSessionToken(e,t,i){await this.canUseTauriIpc()&&await this.invokeIpc("register_session_token",{token:e,scope:t,maxConnections:i});}async getEndpointTicketWithToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await E(()=>this.invokeIpc("get_endpoint_ticket_with_token",{scope:e,maxConnections:t}))}catch{return null}}async validateSessionToken(e,t){if(!await this.canUseTauriIpc())return null;try{return await this.invokeIpc("validate_session_token",{token:e,connectionId:t??null})}catch{return null}}async revokeSessionTokensByScope(e){if(g("NativeIpcBridge.revokeSessionTokensByScope",{grantScope:e}),!await this.canUseTauriIpc())return [];try{return await this.invokeIpc("revoke_session_tokens_by_scope",{scope:e})}catch{return []}}async disconnectDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] disconnectDevice requires native IPC in Tauri runtime.");await this.invokeIpc("disconnect_device",{deviceId:e});}async setAutoConnectExcluded(e,t){if(!await this.canUseTauriIpc())return;let i=e.trim().toLowerCase();i&&(this.usesCoordinationGateway()&&(t?this.gatewayExcludedPeers.add(i):this.gatewayExcludedPeers.delete(i)),await this.invokeIpc(this.usesCoordinationGateway()?"set_rtc_external_auto_connect_excluded":"set_auto_connect_excluded",{deviceId:e,excluded:t}),this.usesCoordinationGateway()&&await this.fallback.setCoordinationExcludedPeers([...this.gatewayExcludedPeers].sort()));}onDevicesChange(e,t){return this.assertManagedCoordinationGateway(),this.fallback.onDevicesChange(e,t)}async subscribeDevices(e){return this.assertManagedCoordinationGateway(),this.fallback.subscribeDevices(e)}async subscribeSessions(e){return this.assertManagedCoordinationGateway(),this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,i=true,a=3e5,n){return this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),this.fallback.updatePresence(e,t,i,a,n)}startAutoConnect(e,t){this.assertManagedCoordinationGateway(),this.startGatewayAutoConnect(e,t).catch(i=>{console.warn("[NativeIpcBridge] gateway auto-connect failed:",i);});}forceReconnectSnapshot(){this.assertManagedCoordinationGateway(),this.fallback.forceReconnectSnapshot();}startPresenceLoop(e,t,i,a,n){this.assertManagedCoordinationGateway(),this.syncCoordinationDeviceIdentity().then(()=>this.fallback.startPresenceLoop(e,t,i,a,n)).catch(s=>{console.warn("[NativeIpcBridge] gateway presence failed:",s);});}async startAutoConnectOnce(e,t){this.assertManagedCoordinationGateway(),await this.startGatewayAutoConnect(e,t);}async clearGatewayDesiredPeerRelay(){let e=this.gatewayDesiredPeerSubmission;this.gatewayDesiredPeerRelayGeneration+=1,this.gatewayDesiredPeersCleanup?.(),this.gatewayDesiredPeersCleanup=null,this.gatewayDesiredPeerRelayKey=null,this.gatewayDesiredPeerRevision=0,this.gatewayDesiredPeerSubmission=Promise.resolve(),await e;}serializeGatewayDesiredPeerLifecycle(e){let t=this.gatewayDesiredPeerLifecycle.then(e);return this.gatewayDesiredPeerLifecycle=t.catch(()=>{}),t}stopGatewayDesiredPeerRelay(){return this.serializeGatewayDesiredPeerLifecycle(async()=>{await this.clearGatewayDesiredPeerRelay();})}startGatewayAutoConnect(e,t){return this.serializeGatewayDesiredPeerLifecycle(()=>this.startGatewayAutoConnectSerialized(e,t))}async startGatewayAutoConnectSerialized(e,t){if(!await this.shouldUseTauriSignaling())throw new Error("[openrtc] Native IPC unavailable for coordination gateway auto-connect.");if(!await this.ensureNativeAuth("startGatewayAutoConnect",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for coordination gateway auto-connect");let a=this.resolveNativeSignalingUserId(e);if(!a)throw new Error("Coordination gateway auto-connect requires an authenticated user id.");let n=await this.resolveLocalDeviceId()||t.trim();if(!n)throw new Error("Coordination gateway auto-connect requires a local device id.");let s=JSON.stringify([a,n]);this.fallback.setCoordinationLocalDeviceId(n);let o=this.gatewayDesiredPeerRelayKey===s&&this.gatewayDesiredPeersCleanup;if(o||(await this.clearGatewayDesiredPeerRelay(),this.gatewayDesiredPeerRelayKey=s),await this.invokeIpc("start_rtc_external_auto_connect",{userId:a,localDeviceId:n}),o)return;let c=this.gatewayDesiredPeerRelayGeneration;this.gatewayDesiredPeersCleanup=this.fallback.onDevicesChange(d=>{let r=d.map(u=>({deviceId:String(u.deviceId??"").trim(),nodeId:typeof u.nodeId=="string"&&u.nodeId.trim()||null,ticket:typeof u.ticket=="string"&&u.ticket.trim()||null,online:u.online===true,sessionId:typeof u.sessionId=="string"&&u.sessionId.trim()||null,excludedPeers:Array.isArray(u.excludedPeers)?[...new Set(u.excludedPeers.map(I=>String(I??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(u=>u.deviceId.length>0&&u.deviceId!==n).sort((u,I)=>u.deviceId.localeCompare(I.deviceId)),l=++this.gatewayDesiredPeerRevision;this.gatewayDesiredPeerSubmission=this.gatewayDesiredPeerSubmission.then(async()=>{this.gatewayDesiredPeerRelayGeneration!==c||this.gatewayDesiredPeerRelayKey!==s||await this.invokeIpc("submit_rtc_desired_peers",{revision:l,peersJson:JSON.stringify(r)});}).catch(u=>{console.warn("[NativeIpcBridge] failed to relay gateway desired peers to Rust:",{revision:l,error:u});});},n);}async startPresenceLoopOnce(e,t,i,a,n){this.assertManagedCoordinationGateway(),await this.syncCoordinationDeviceIdentity(),await this.fallback.startPresenceLoop(e,t,i,a,n);}shouldUseResolvedDeviceName(e){let t=e.trim();return t.length===0||t==="Unknown Device"||t==="Desktop Device"}async sendExplicitFilePath(e,t,i=""){if(c$1("[NativeIpcBridge] sendExplicitFilePath start",{connectionId:e,filePath:t,transferId:i||null,authMode:this.options.authMode}),await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFilePath"):c$1("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let a=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:i});return c$1("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:i||null,result:a}),a}return this.fallback.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){c$1("[NativeIpcBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:e.connection?.remoteNodeId??null,remoteNodeId:e.remoteNodeId??null,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size,authMode:this.options.authMode});let t=e.applicationCrypto??this.options.applicationCrypto;if(await this.canUseTauriIpc()){this.options.authMode!=="anonymous"?await this.ensureNativeAuth("sendExplicitFileData"):c$1("[NativeIpcBridge] sendExplicitFileData using anonymous native path");let i=e.connectionId||e.connection?.deviceId||e.connection?.remoteNodeId||e.remoteNodeId||"";if(!i)throw new Error("sendExplicitFileData requires a settled peer identifier in native runtime");let a=new Uint8Array(await e.file.arrayBuffer());await this.invokeIpc("send_file_data",{connectionId:i,filename:e.file.name,data:Array.from(a),transferId:e.transferId}),c$1("[NativeIpcBridge] sendExplicitFileData completed",{connectionId:i,transferId:e.transferId??null,fileName:e.file.name,fileSize:e.file.size});return}return this.fallback.sendExplicitFileData({...e,applicationCrypto:t})}async getConnectionStates(){if(await this.canUseTauriIpc())try{this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionStates");let e=await this.invokeIpc("list_rtc_connection_states");return (Array.isArray(e)?e:[]).map(t=>n(t)).filter(t=>!!t)}catch(e){return b(e)?c$1("[NativeIpcBridge] native connection-state replay unavailable; continuing without replay. Install/register openrtc-tauri-plugin default permissions to enable it."):console.warn("[NativeIpcBridge] Failed to fetch native connection states:",e),[]}return []}async getConnectionState(e){let t=e.trim();if(!t||!await this.canUseTauriIpc())return null;try{return this.options.authMode!=="anonymous"&&await this.ensureNativeAuth("getConnectionState"),n(await this.invokeIpc("get_rtc_connection_state",{connectionId:t}))}catch(i){return console.warn("[NativeIpcBridge] Failed to fetch native connection state:",{connectionId:t,error:i}),null}}async onConnectionStateChange(e){let t=false,i=null,a$1=new Map,n$1=Date.now(),s=0,o=()=>{let r=i;r&&Promise.resolve(r());},c=async()=>{try{let r=await this.getConnectionStates();r.length>0&&(b$1("[NativeIpcBridge] replaying current native connection states",r.map(l=>({connectionId:l.connectionId,deviceId:l.deviceId??null,deviceIdHint:l.deviceIdHint??null,remoteNodeId:l.remoteNodeId??null,state:l.state,transportState:l.transportState??null,protocolState:l.protocolState??null,routable:l.routable??null}))),r.forEach(l=>e(l)));}catch(r){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",r);}},d=async r=>{let l=(a$1.get(r)??0)+1;a$1.set(r,l);let u=await this.getConnectionState(r);if(!u||t||a$1.get(r)!==l)return;if(["closed","failed","disconnected"].includes(String(u.state??"").trim().toLowerCase())){if(await a(h.CONNECTION_TERMINAL_CONFIRMATION_MS),t||a$1.get(r)!==l)return;u=await this.getConnectionState(r)??u;}!t&&a$1.get(r)===l&&e(u);};for(;!t&&Date.now()-n$1<=h.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(s+=1,!await this.canUseTauriIpc()){await a(this.nextConnectionEventRetryDelayMs(s));continue}return i=await this.listenIpc("connection-state-changed",r=>{let l=n(r?.payload);l&&(b$1("[NativeIpcBridge] connection-state-changed trigger",{connectionId:l.connectionId}),d(l.connectionId));}),await c(),()=>{t=true,o();}}return ()=>{t=true,o();}}async onIncomingNativeMessage(e){if(!await this.canUseTauriIpc())return ()=>{};let t=await this.listenIpc("iroh://message",i=>{if(i?.payload?.data&&i.payload.streamId==="main")try{let a=new Uint8Array(i.payload.data);if(a.length<2||a[0]!==0)return;let s=a.slice(1),o=new TextDecoder().decode(s),c=JSON.parse(o);e(i.payload.connectionId,i.payload.remoteNodeId??null,c);}catch{}});return typeof t=="function"?t:()=>{}}async getTransferHistory(e=50){return await this.canUseTauriIpc()?this.invokeIpc("get_transfer_history",{limit:e}):[]}async deleteTransferJob(e){await this.canUseTauriIpc()&&await this.invokeIpc("delete_transfer_job",{jobId:e});}};h.AUTH_REQUIRED_WAIT_MS=o.nativeIpc.authRequiredWaitMs,h.DEFAULT_BOUNDED_IPC_TIMEOUT_MS=o.nativeIpc.defaultBoundedCommandTimeoutMs,h.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=o.nativeIpc.connectionEventSubscribeWindowMs,h.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=o.nativeIpc.connectionEventRetryMinDelayMs,h.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=o.nativeIpc.connectionEventRetryMaxDelayMs,h.CONNECTION_TERMINAL_CONFIRMATION_MS=1500,h.TAURI_IPC_NEGATIVE_CACHE_MS=o.nativeIpc.tauriIpcNegativeCacheMs,h.NATIVE_STATUS_IPC_TIMEOUT_MS=2500;var M=h;var J=class extends a$1{constructor(e){let t=c(e.bridge,"IpcRuntimeAdapter");super(new M({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
2
+ export{Y as a,k as b,j as c,ae as d,E as e,J as f};
@@ -0,0 +1,2 @@
1
+ import {d as d$2,c}from'./chunk-VK6KX433.js';import {a,d as d$1}from'./chunk-C7YN5MSV.js';import {x25519}from'@noble/curves/ed25519.js';import {hkdf}from'@noble/hashes/hkdf.js';import {sha256}from'@noble/hashes/sha2.js';var A=3e4,d=class d{constructor(){this.name="webrtc";this.pc=null;this.dc=null;this.state="disconnected";this.pendingCandidates=[];this.connectTimeoutId=null;this.iceDisconnectedGraceTimer=null;this.iceRestartAttempted=false;this.localNodeId="";this.remoteNodeId="";this.candidatesGathered=0;this.sdpOfferSent=false;this.sdpAnswerReceived=false;this._terminalFailure=false;this.activeAttemptId=0;this.negotiationId=null;this.disconnectedGraceExtensions=0;this.offerInFlight=false;this.messageListeners=[];this.stateListeners=[];this.internalSignalSender=null;}get isReady(){return this.state==="connected"}isTerminalFailure(){return this._terminalFailure}getNegotiationId(){return this.negotiationId}getDataChannelReadyState(){return this.dc?.readyState??null}getNativeTransport(){return this.pc}setSignalSender(e){this.internalSignalSender=e;}async init(e,n,t){this.closePeerResources();let i=++this.activeAttemptId;this.localNodeId=e,this.remoteNodeId=n,this.candidatesGathered=0,this.sdpOfferSent=false,this.sdpAnswerReceived=false,this._terminalFailure=false,this.offerInFlight=false,this.pendingCandidates=[],this.disconnectedGraceExtensions=0,this.negotiationId=typeof t?.negotiationId=="string"&&t.negotiationId.trim().length>0?t.negotiationId.trim():this.createNegotiationId(),this.setState("connecting"),this.startConnectTimeout(i);let a=t.rtcConfig||{},s=typeof t?.forceRole=="string"&&(t.forceRole==="initiator"||t.forceRole==="responder")?t.forceRole:null,c=s?s==="initiator":e>n;d$2(`[WebRTCTransport] init \u2014 role=${c?"initiator":"responder"}`,{local:e.slice(0,12),remote:n.slice(0,12),negotiationId:this.negotiationId,forcedRole:s});try{d$2("[WebRTCTransport] Creating RTCPeerConnection",{iceServers:a.iceServers?.length??0}),this.pc=new RTCPeerConnection(a);}catch(R){console.error("[WebRTCTransport] RTCPeerConnection constructor failed",R),this.setState("failed");return}let T=this.pc.createDataChannel("pluto-dc",{negotiated:true,id:0});this.setupDataChannel(T,i),this.setupPCHandlers(c,i),c&&queueMicrotask(()=>{this.createAndSendOffer(i,"initial-initiator");});}setupDataChannel(e,n){this.dc=e,e.onopen=()=>{this.isCurrentAttempt(n,e)&&(d$2("[WebRTCTransport] DataChannel opened \u2014 upgrade complete"),this.promoteConnectedIfReady("datachannel-open"));},e.onmessage=t=>{if(!this.isCurrentAttempt(n,e))return;let i=typeof t.data=="string"?new TextEncoder().encode(t.data):new Uint8Array(t.data);this.messageListeners.forEach(a=>a(i));},e.onclose=()=>{this.isCurrentAttempt(n,e)&&(d$2("[WebRTCTransport] DataChannel closed"),(this.state==="connected"||this.state==="connecting")&&this.setState("disconnected"));},e.onerror=t=>{if(!this.isCurrentAttempt(n,e))return;console.warn("[WebRTCTransport] DataChannel error",t);let i=t?.error?.message??"";if((i.includes("User-Initiated Abort")||i.includes("Close called"))&&this.state==="connected"&&e.readyState!=="open"){console.warn("[WebRTCTransport] DataChannel aborted post-connect; forcing disconnected state",{readyState:e.readyState,connectionState:this.pc?.connectionState,iceConnectionState:this.pc?.iceConnectionState}),this.setState("disconnected");return}this.state==="connecting"&&this.setState("failed");};}setupPCHandlers(e,n){let t=this.pc;t&&(t.onicecandidate=i=>{this.isCurrentAttempt(n,void 0,t)&&(i.candidate?(this.candidatesGathered++,d$2(`[WebRTCTransport] ICE candidate #${this.candidatesGathered}: ${i.candidate.type} ${i.candidate.protocol} ${i.candidate.address??"?"}:${i.candidate.port}`),this.internalSignalSender?this.internalSignalSender({transport:"webrtc",type:"candidate",candidate:i.candidate,negotiationId:this.negotiationId??void 0}).catch(a=>{console.warn("[WebRTCTransport] Failed sending local ICE candidate signal",{error:a,gatheringState:t?.iceGatheringState,iceConnectionState:t?.iceConnectionState});}):console.warn("[WebRTCTransport] ICE candidate dropped \u2014 no signal sender!")):this.candidatesGathered===0?(console.warn("[WebRTCTransport] ICE gathering complete with 0 candidates \u2014 failing immediately.","If both peers are on the same page, WebRTC requires separate tabs or devices.",{local:this.localNodeId.slice(0,12),remote:this.remoteNodeId.slice(0,12)}),this._terminalFailure=true,this.setState("failed")):d$2(`[WebRTCTransport] ICE gathering complete \u2014 ${this.candidatesGathered} candidate(s)`));},t.onnegotiationneeded=async()=>{e&&await this.createAndSendOffer(n,"negotiationneeded");},t.onconnectionstatechange=()=>{if(!this.isCurrentAttempt(n,void 0,t))return;let i=t.connectionState;if(d$2(`[WebRTCTransport] Connection state: ${i}`),i==="connected")this.promoteConnectedIfReady("pc-connected");else if(i==="failed"){if(this.iceDisconnectedGraceTimer){console.warn("[WebRTCTransport] pc.connectionState=failed during grace window \u2014 deferring to grace timer",{iceState:t.iceConnectionState,iceRestartAttempted:this.iceRestartAttempted});return}console.error("[WebRTCTransport] Connection failed",{iceState:t.iceConnectionState,gatheringState:t.iceGatheringState,signalingState:t.signalingState,candidatesGathered:this.candidatesGathered,sdpOfferSent:this.sdpOfferSent,sdpAnswerReceived:this.sdpAnswerReceived}),this.clearIceDisconnectedGrace("pc-failed"),this.setState("failed");}else i==="closed"?(this.clearIceDisconnectedGrace("pc-closed"),this.setState("disconnected")):i==="disconnected"&&(d$2("[WebRTCTransport] pc.connectionState=disconnected, deferring to ICE grace period"),this.startIceDisconnectedGrace(n,t,e,"pc-disconnected"));},t.oniceconnectionstatechange=()=>{if(!this.isCurrentAttempt(n,void 0,t))return;let i=t.iceConnectionState;if(d$2(`[WebRTCTransport] ICE connection state: ${i}`,{gatheringState:t.iceGatheringState,signalingState:t.signalingState,candidatesGathered:this.candidatesGathered,hasSdpOffer:this.sdpOfferSent,hasSdpAnswer:this.sdpAnswerReceived,hasRemoteDescription:!!t.remoteDescription,hasLocalDescription:!!t.localDescription}),i==="failed"){if(this.iceDisconnectedGraceTimer){console.warn("[WebRTCTransport] ice failed during grace window \u2014 deferring to grace timer");return}console.error("[WebRTCTransport] ICE failed \u2014 likely NAT traversal issue or no matching candidates",{gatheringState:t.iceGatheringState,signalingState:t.signalingState,candidatesGathered:this.candidatesGathered}),this.clearIceDisconnectedGrace("ice-failed"),this.setState("failed");}else i==="disconnected"?this.startIceDisconnectedGrace(n,t,e,"ice-disconnected"):(i==="connected"||i==="completed")&&(this.iceDisconnectedGraceTimer&&d$2("[WebRTCTransport] ice-recovered \u2014 cancelling grace timer"),this.clearIceDisconnectedGrace("ice-recovered"),this.iceRestartAttempted=false,this.promoteConnectedIfReady("ice-connected"));},t.onicegatheringstatechange=()=>{this.isCurrentAttempt(n,void 0,t)&&d$2(`[WebRTCTransport] ICE gathering state: ${t.iceGatheringState}`,{iceConnectionState:t.iceConnectionState,signalingState:t.signalingState,hasLocalDesc:!!t.localDescription,hasRemoteDesc:!!t.remoteDescription});});}async createAndSendOffer(e,n){let t=this.pc;if(!(!t||!this.isCurrentAttempt(e,void 0,t))&&t.signalingState==="stable"&&!(this.sdpOfferSent&&t.localDescription?.type==="offer")&&!this.offerInFlight){d$2(`[WebRTCTransport] Creating offer (${n})`),this.offerInFlight=true;try{let i=await t.createOffer();if(await t.setLocalDescription(i),!this.isCurrentAttempt(e,void 0,t))return;if(this.sdpOfferSent=!0,this.internalSignalSender)try{await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:i,negotiationId:this.negotiationId??void 0});}catch(a){console.warn("[WebRTCTransport] Offer signaling failed (non-fatal)",{error:a,negotiationId:this.negotiationId,signalingState:t.signalingState,iceConnectionState:t.iceConnectionState});}else console.warn("[WebRTCTransport] No signal sender \u2014 offer not transmitted");}catch(i){console.error("[WebRTCTransport] Offer creation failed",i),this.closePeerResources(),this.setState("failed");}finally{this.isCurrentAttempt(e,void 0,t)&&(this.offerInFlight=false);}}}handleSignalingMessage(e){if(!this.pc||e.transport!=="webrtc")return;let n=this.normalizeNegotiationId(e?.negotiationId);if(n&&this.negotiationId&&n!==this.negotiationId){c("[WebRTCTransport] Ignoring stale signaling message for a different negotiation",{signalType:e?.type??null,signalNegotiationId:n,activeNegotiationId:this.negotiationId});return}if(e.type==="candidate"){let t=e.candidate;d$2("[WebRTCTransport] Received remote ICE candidate",{hasRemoteDesc:!!this.pc.remoteDescription,type:t?.type,protocol:t?.protocol,address:t?.address}),this.pc.remoteDescription?this.pc.addIceCandidate(t).catch(i=>{console.warn("[WebRTCTransport] addIceCandidate failed",i);}):(this.pendingCandidates.push(t),d$2(`[WebRTCTransport] Buffered remote candidate \u2014 ${this.pendingCandidates.length} pending`));}else if(e.type==="sdp"){let t=e.sdp,i=t.type==="offer",a=t.type==="answer";if(a&&this.pc.signalingState!=="have-local-offer"){c("[WebRTCTransport] Ignoring SDP answer because no local offer is pending",{signalingState:this.pc.signalingState,iceConnectionState:this.pc.iceConnectionState,signalNegotiationId:n,activeNegotiationId:this.negotiationId,hasLocalDescription:!!this.pc.localDescription,hasRemoteDescription:!!this.pc.remoteDescription});return}d$2(`[WebRTCTransport] Received SDP ${t.type} \u2014 applying remote description`),a&&(this.sdpAnswerReceived=true),this.pc.setRemoteDescription(t).then(async()=>{if(a&&(d$2("[WebRTCTransport] Remote SDP answer applied",{signalingState:this.pc?.signalingState,iceConnectionState:this.pc?.iceConnectionState,hasLocalDescription:!!this.pc?.localDescription,hasRemoteDescription:!!this.pc?.remoteDescription}),this.promoteConnectedIfReady("sdp-answer-applied")),this.pendingCandidates.length&&(d$2(`[WebRTCTransport] Flushing ${this.pendingCandidates.length} buffered candidate(s)`),this.pendingCandidates.forEach(s=>this.pc?.addIceCandidate(s)),this.pendingCandidates=[]),i){d$2("[WebRTCTransport] Creating answer (responder)");let s=await this.pc.createAnswer();if(await this.pc.setLocalDescription(s),d$2("[WebRTCTransport] Answer sent"),this.internalSignalSender)try{await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:s,negotiationId:n??this.negotiationId??void 0});}catch(c){throw console.warn("[WebRTCTransport] Failed sending SDP answer signal",{error:c,signalingState:this.pc?.signalingState,hasLocalDescription:!!this.pc?.localDescription,hasRemoteDescription:!!this.pc?.remoteDescription}),c}else console.warn("[WebRTCTransport] No signal sender \u2014 answer not transmitted");}}).catch(s=>{console.error(`[WebRTCTransport] setRemoteDescription (${t.type}) failed`,s),this.setState("failed");});}}async send(e){if(this.dc&&this.dc.readyState==="open"){let n=new Uint8Array(e);this.dc.send(n);}else throw new Error("WebRTC DataChannel not open")}getBufferedAmount(){return this.dc?.bufferedAmount??0}async waitForDrain(e){!this.dc||this.dc.bufferedAmount<=e||await new Promise(n=>{let t=this.dc;if(!t){n();return}t.bufferedAmountLowThreshold=e,t.onbufferedamountlow=()=>{t.onbufferedamountlow=null,n();};});}close(){this.closePeerResources(),this.setState("disconnected");}onMessage(e){this.messageListeners.push(e);}onStateChange(e){this.stateListeners.push(e);}setState(e){this.state!==e&&(this.state=e,(e==="connected"||e==="failed"||e==="disconnected")&&this.clearConnectTimeout(),this.stateListeners.forEach(n=>n(e)));}startConnectTimeout(e){this.clearConnectTimeout(),this.connectTimeoutId=setTimeout(()=>{this.activeAttemptId===e&&this.state==="connecting"&&(console.warn(`[WebRTCTransport] Timed out after ${d.ICE_CONNECT_TIMEOUT_MS}ms`,{iceState:this.pc?.iceConnectionState,gatheringState:this.pc?.iceGatheringState,signalingState:this.pc?.signalingState,candidatesGathered:this.candidatesGathered,sdpOfferSent:this.sdpOfferSent,sdpAnswerReceived:this.sdpAnswerReceived,hasRemoteDescription:!!this.pc?.remoteDescription,hasLocalDescription:!!this.pc?.localDescription}),this.setState("failed"));},d.ICE_CONNECT_TIMEOUT_MS);}clearConnectTimeout(){this.connectTimeoutId&&(clearTimeout(this.connectTimeoutId),this.connectTimeoutId=null);}startIceDisconnectedGrace(e,n,t,i){if(!this.iceDisconnectedGraceTimer){if(this.iceRestartAttempted)d$2("[WebRTCTransport] ice-disconnected grace (restart already attempted)",{reason:i});else if(this.iceRestartAttempted=true,t){try{d$2("[WebRTCTransport] ice-restart-attempted",{reason:i,isInitiator:t}),n.restartIce();}catch(a){console.warn("[WebRTCTransport] restartIce threw",a);}this.sendIceRestartOffer(e,n);}else d$2("[WebRTCTransport] ice-restart deferred to initiator",{reason:i});this.iceDisconnectedGraceTimer=setTimeout(()=>{if(this.iceDisconnectedGraceTimer=null,this.activeAttemptId!==e||this.pc!==n)return;let a=n.iceConnectionState,s=n.connectionState,c=this.dc?.readyState??"missing";if(a==="connected"||a==="completed"||s==="connected"||c==="open"){d$2("[WebRTCTransport] ice-grace expired \u2014 recovered",{ice:a,conn:s,dcReadyState:c});return}if(this.disconnectedGraceExtensions<1){this.disconnectedGraceExtensions+=1,console.warn("[WebRTCTransport] ice-grace expired \u2014 extending once before fail",{ice:a,conn:s,dcReadyState:c,extension:this.disconnectedGraceExtensions}),this.startIceDisconnectedGrace(e,n,t,`${i}:extended`);return}console.warn("[WebRTCTransport] ice-grace expired \u2014 marking failed",{ice:a,conn:s}),this.setState("failed");},d.ICE_DISCONNECTED_GRACE_MS);}}async sendIceRestartOffer(e,n){try{let t=await n.createOffer({iceRestart:!0});if(!this.isCurrentAttempt(e,void 0,n)||(await n.setLocalDescription(t),!this.isCurrentAttempt(e,void 0,n)))return;this.internalSignalSender?(await this.internalSignalSender({transport:"webrtc",type:"sdp",sdp:t,negotiationId:this.negotiationId??void 0}),d$2("[WebRTCTransport] ice-restart re-offer sent",{negotiationId:this.negotiationId})):console.warn("[WebRTCTransport] ice-restart re-offer dropped \u2014 no signal sender");}catch(t){console.warn("[WebRTCTransport] ice-restart re-offer failed",t);}}clearIceDisconnectedGrace(e){this.iceDisconnectedGraceTimer&&(clearTimeout(this.iceDisconnectedGraceTimer),this.iceDisconnectedGraceTimer=null);}promoteConnectedIfReady(e){let n=this.dc?.readyState??"missing";if(n!=="open"){d$2("[WebRTCTransport] Deferring connected state until DataChannel is open",{reason:e,dcReadyState:n,iceConnectionState:this.pc?.iceConnectionState,connectionState:this.pc?.connectionState});return}this.clearIceDisconnectedGrace(`connected:${e}`),this.disconnectedGraceExtensions=0,this.setState("connected");}closePeerResources(){this.activeAttemptId+=1,this.clearConnectTimeout(),this.clearIceDisconnectedGrace("close"),this.iceRestartAttempted=false,this.pendingCandidates=[],this._terminalFailure=false,this.negotiationId=null,this.disconnectedGraceExtensions=0,this.offerInFlight=false,this.dc&&(this.dc.onopen=null,this.dc.onmessage=null,this.dc.onclose=null,this.dc.onerror=null,this.dc.readyState!=="closed"&&this.dc.close(),this.dc=null),this.pc&&(this.pc.onicecandidate=null,this.pc.onnegotiationneeded=null,this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.connectionState!=="closed"&&this.pc.close(),this.pc=null);}isCurrentAttempt(e,n,t){return !(this.activeAttemptId!==e||n&&this.dc!==n||t&&this.pc!==t)}createNegotiationId(){return `ts-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}normalizeNegotiationId(e){if(typeof e!="string")return null;let n=e.trim();return n.length>0?n:null}};d.ICE_CONNECT_TIMEOUT_MS=A,d.ICE_DISCONNECTED_GRACE_MS=3e4;var h=d;var v={iroh:{available:false,reason:"iroh is constructed by the OpenRTC runtime, not the legacy ITransport factory."},"iroh-quic":{available:false,reason:"iroh-quic is a path label, not a standalone transport."},"iroh-relay":{available:false,reason:"iroh-relay is a path label, not a standalone transport."},"iroh-lan":{available:false,reason:"iroh-lan is a path label, not a standalone transport."},ble:{available:false,reason:"ble requires a separately licensed native host companion and current physical-device evidence."},webrtc:{available:true},"webrtc-lan":{available:false,reason:"webrtc-lan is a path label, not a standalone transport."},"webrtc-turn":{available:false,reason:"webrtc-turn is a path label, not a standalone transport."},moq:{available:false,reason:"MoQ is constructed by the route lifecycle, not the legacy ITransport factory."}};function I(r){return r.implementation==="route-adapter"?"plugin":r.implementation==="core"?"native":"path-label"}function w(){return Object.fromEntries(a.map(r=>[r.id,{...r,routeImplementation:r.implementation,implementation:I(r),protocol:r.id,preferredRank:d$1[r.id],...v[r.id]}]))}var f=class{static createTransport(e){if(this.assertProtocolAvailable(e),e==="webrtc")return new h;throw new Error(`[TransportFactory] '${e}' is not implemented as an ITransport plugin.`)}static getProtocolCapability(e){return {...this.capabilityMap[e]}}static getProtocolCapabilities(){return Object.fromEntries(a.map(e=>[e.id,this.getProtocolCapability(e.id)]))}static getPreferredProtocolOrder(e={}){let n=e.runtime??"any",t=e.includePathLabels??true;return a.filter(i=>t||i.implementation!=="path-label").filter(i=>n==="browser"?i.browser:n==="native"?i.native:i.browser||i.native).sort((i,a)=>d$1[i.id]-d$1[a.id]).map(i=>i.id)}static assertProtocolAvailable(e){let n=this.capabilityMap[e];if(!n.available||n.maturity==="unsupported"){let t=n.reason?` ${n.reason}`:"";throw new Error(`[TransportFactory] Protocol '${e}' is unsupported.${t}`)}}};f.capabilityMap=w();function _(r){return f.getPreferredProtocolOrder(r)}var g=32,S="openrtc:x25519-hkdf:v1",C=new TextEncoder().encode("openrtc:application-crypto:v1");function u(r,e){if(!(e instanceof Uint8Array)||e.byteLength!==g)throw new Error(`[OpenRTC] ${r} must be ${g} bytes`)}function E(r,e){let[n,t]=r<=e?[r,e]:[e,r],i=new TextEncoder().encode(n),a=new TextEncoder().encode(t),s=new Uint8Array(C.byteLength+1+i.byteLength+1+a.byteLength),c=0;return s.set(C,c),c+=C.byteLength,s[c]=0,c+=1,s.set(i,c),c+=i.byteLength,s[c]=0,c+=1,s.set(a,c),s}function K(r=e=>{let n=new Uint8Array(e);return globalThis.crypto.getRandomValues(n),n}){let e=r(g);return u("key agreement secret",e),{publicKey:x25519.getPublicKey(e),secretKey:e}}function U(r,e,n,t){u("key agreement local secret",r),u("key agreement remote public key",e);let i=x25519.getSharedSecret(r,e);return hkdf(sha256,i,void 0,E(n,t),32)}function $(r){return Array.from(sha256(r).slice(0,6),e=>e.toString(16).padStart(2,"0")).join("")}function F(r){u("key agreement public key",r);let e="";for(let t=0;t<r.byteLength;t+=1)e+=String.fromCharCode(r[t]);let n=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return {algorithm:S,publicKey:n}}function k(r){if(!r||r.algorithm!==S)return null;let e=typeof r.publicKey=="string"?r.publicKey.trim():"";if(!e)return null;let n=e.replace(/-/g,"+").replace(/_/g,"/"),t=n.length%4===0?n:n+"=".repeat(4-n.length%4),i=Uint8Array.from(atob(t),a=>a.charCodeAt(0));return i.byteLength!==g?null:i}
2
+ export{A as a,f as b,_ as c,g as d,S as e,K as f,U as g,$ as h,F as i,k as j};
@@ -0,0 +1 @@
1
+ import {t}from'./chunk-YBXGNKM7.js';var a=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthScopedActivity(){typeof this.backend.stopAuthScopedActivity=="function"&&await this.backend.stopAuthScopedActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,n,t){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,n,t);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,n){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,n)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,n,t,i,r){return this.backend.updatePresence(e,n,t,i,r)}async refreshLivePresence(e,n,t){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,n,t)}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,n){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,n)}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,n){return this.backend.updateDevice(e,n)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,n){return this.backend.onDevicesChange(e,n)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,n,t,i){return this.backend.sendMessage(e,n,t,i)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,n){let t=this.backend;return t.watchFriendDevices?t.watchFriendDevices(e,n):()=>{}}async updateFriendTicket(e){let n=this.backend;n.updateFriendTicket&&await n.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,n){this.backend.startAutoConnect(e,n);}async submitDesiredPeerProjection(e,n){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,n);}startPresenceLoop(e,n,t,i,r){this.backend.startPresenceLoop(e,n,t,i,r);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,n){return this.backend.updateSession(e,n)}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 n=this.backend;if(typeof n.startManagedSessionNative!="function")throw new Error("Selected runtime adapter does not support startManagedSessionNative().");return n.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 n=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:n}),n}async startPresenceLoopOnce(e,n,t,i,r){let o=this.backend;if(typeof o.startPresenceLoopOnce!="function")throw new Error("Selected runtime adapter does not support startPresenceLoopOnce().");return o.startPresenceLoopOnce(e,n,t,i,r)}async startAutoConnectOnce(e,n){let t=this.backend;if(typeof t.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return t.startAutoConnectOnce(e,n)}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,n){let t=this.backend;return typeof t.getEndpointTicketWithToken!="function"?null:t.getEndpointTicketWithToken(e,n)}async registerSessionToken(e,n,t){let i=this.backend;typeof i.registerSessionToken=="function"&&await i.registerSessionToken(e,n,t);}async revokeSessionTokensByScope(e){let n=this.backend;return typeof n.revokeSessionTokensByScope!="function"?[]:n.revokeSessionTokensByScope(e)}async openPeerBi(e,n){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,n)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async is_current_transport_stable_id(e,n){let t=this.backend;return typeof t.is_current_transport_stable_id!="function"?false:t.is_current_transport_stable_id(e,n)}async openPeerNativeBi(e,n,t){let i=this.backend;if(typeof i.openPeerNativeBi!="function")throw new Error("Selected runtime adapter does not support openPeerNativeBi().");return i.openPeerNativeBi(e,n,t)}async openPeerBiTransportOnly(e,n){let t=this.backend;return typeof t.openPeerBiTransportOnly=="function"?t.openPeerBiTransportOnly(e,n):this.openPeerBi(e,n)}async openPeerUni(e,n){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,n)}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 setAutoConnectExcluded(e,n){if(typeof this.backend.setAutoConnectExcluded!="function")throw new Error("Selected runtime adapter does not support setAutoConnectExcluded().");return this.backend.setAutoConnectExcluded(e,n)}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,n,t){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,n,t)}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():t()}async onIncomingNativeMessage(e){let n=this.backend;return typeof n.onIncomingNativeMessage!="function"?()=>{}:n.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let n=this.backend;typeof n.setCoreClient=="function"&&n.setCoreClient(e);}};export{a};