openrtc 1.0.3 → 1.0.5

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 (39) hide show
  1. package/README.md +12 -4
  2. package/dist/{DelegatingRuntimeAdapter-D2_dgabz.d.ts → DelegatingRuntimeAdapter-DlC0TZB0.d.ts} +3 -102
  3. package/dist/OpenRTCShared-BvTf2gFH.d.ts +249 -0
  4. package/dist/{framing-rPdckqn5.d.ts → assembly-BH-ZekkH.d.ts} +4 -46
  5. package/dist/auth/index.js +1 -1
  6. package/dist/auth/internal.js +1 -1
  7. package/dist/capabilities-C4Dqs_pB.d.ts +101 -0
  8. package/dist/chunk-4AXAWVC6.js +2 -0
  9. package/dist/chunk-7352ZIXN.js +3 -0
  10. package/dist/chunk-DI5IPRPM.js +2 -0
  11. package/dist/{chunk-34LATQZZ.js → chunk-HVTYSEU7.js} +1 -1
  12. package/dist/chunk-MNI6JGR2.js +1 -0
  13. package/dist/{chunk-RRCARL4S.js → chunk-N6UBUNGC.js} +1 -1
  14. package/dist/chunk-WUREK3SW.js +1 -0
  15. package/dist/chunk-YTUWXCRO.js +1 -0
  16. package/dist/framing-zRvEKOld.d.ts +29 -0
  17. package/dist/index.d.ts +18 -260
  18. package/dist/index.js +2 -2
  19. package/dist/ipc-CflAVodw.d.ts +11 -0
  20. package/dist/native.d.ts +20 -0
  21. package/dist/native.js +1 -0
  22. package/dist/openrtc_bg.wasm +0 -0
  23. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -2
  24. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  25. package/dist/runtime/device-status.d.ts +37 -2
  26. package/dist/runtime/index.d.ts +28 -11
  27. package/dist/runtime/index.js +1 -1
  28. package/dist/runtime/tauri.d.ts +5 -19
  29. package/dist/runtime/tauri.js +1 -1
  30. package/dist/tauri-BVSxK0jq.d.ts +33 -0
  31. package/dist/transport/index.d.ts +2 -2
  32. package/dist/{types-ByZyADCn.d.ts → types-BCkKK8dy.d.ts} +1 -1
  33. package/dist/{device-status-CR27Ak7c.d.ts → types-QMj23Nvm.d.ts} +3 -36
  34. package/package.json +7 -2
  35. package/dist/IpcRuntimeAdapter-B8rkqNrq.d.ts +0 -28
  36. package/dist/chunk-BGQX25BO.js +0 -1
  37. package/dist/chunk-L6OUJ6YN.js +0 -2
  38. package/dist/chunk-MESPJTUA.js +0 -1
  39. package/dist/chunk-NCRP5ODV.js +0 -3
@@ -0,0 +1,33 @@
1
+ import { n as ClientOptions } from './types-BCkKK8dy.js';
2
+ import { W as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-DlC0TZB0.js';
3
+ import { P as PlutoIpcBridge } from './ipc-CflAVodw.js';
4
+
5
+ interface NativeIpcBridgeOptions extends WasmBridgeOptions {
6
+ allowWasmFallback?: boolean;
7
+ ipcBridge?: PlutoIpcBridge;
8
+ transports?: ClientOptions['transports'];
9
+ strictMode?: boolean;
10
+ }
11
+
12
+ interface IpcRuntimeAdapterOptions extends NativeIpcBridgeOptions {
13
+ bridge: PlutoIpcBridge;
14
+ }
15
+ declare class IpcRuntimeAdapter extends DelegatingRuntimeAdapter {
16
+ constructor(options: IpcRuntimeAdapterOptions);
17
+ }
18
+
19
+ /**
20
+ * @deprecated Native Tauri support now lives in the first-party `openrtc-tauri` package.
21
+ * Removal target: OpenRTC 0.2.0. This shim remains for one compatibility cycle.
22
+ */
23
+ declare function createTauriIpcBridge(): PlutoIpcBridge;
24
+ /**
25
+ * @deprecated Native Tauri support now lives in the first-party `openrtc-tauri` package.
26
+ * Removal target: OpenRTC 0.2.0. This shim remains for one compatibility cycle.
27
+ */
28
+ declare class TauriRuntimeAdapter extends IpcRuntimeAdapter {
29
+ constructor(options: NativeIpcBridgeOptions);
30
+ }
31
+ type TauriRuntimeAdapterOptions = NativeIpcBridgeOptions;
32
+
33
+ export { IpcRuntimeAdapter as I, TauriRuntimeAdapter as T, type IpcRuntimeAdapterOptions as a, type TauriRuntimeAdapterOptions as b, createTauriIpcBridge as c };
@@ -1,5 +1,5 @@
1
- import { K as RouteDescriptor, o as ProtocolName } from '../types-ByZyADCn.js';
2
- export { O as RouteFamily, Q as RouteImplementationKind } from '../types-ByZyADCn.js';
1
+ import { $ as RouteDescriptor, s as ProtocolName } from '../types-BCkKK8dy.js';
2
+ export { a0 as RouteFamily, a1 as RouteImplementationKind } from '../types-BCkKK8dy.js';
3
3
 
4
4
  declare const ROUTE_DESCRIPTORS: readonly RouteDescriptor[];
5
5
  declare function getRouteDescriptor(id: ProtocolName): RouteDescriptor;
@@ -934,4 +934,4 @@ interface JoinRequest {
934
934
  state: 'pending' | 'accepted' | 'rejected';
935
935
  }
936
936
 
937
- export type { RuntimeBootstrapOptions as $, AuthMode as A, BackendPeerBiStream as B, ClientOptions as C, DiscoveryMode as D, ExplicitFileDataSendParams as E, ProtocolBaseName as F, GrantScope as G, ProtocolImplementationKind as H, ISignalingBackend as I, ProtocolLocality as J, RouteDescriptor as K, LocalDeviceInfo as L, ManagedConnectionRecord as M, NativeManagedSessionStartResult as N, RouteFamily as O, PeerSessionSnapshot as P, RouteImplementationKind as Q, RuntimeIdentity as R, SignalingMode as S, SpaceAuthMode as T, SignalingOptions as U, JoinRoomOptions as V, RoomMember as W, IncomingStreamChannelMetadata as X, RoomCreationMode as Y, ScanningLoopOptions as Z, ScanningLoopHandle as _, Device as a, RuntimeBootstrapResult as a0, ManagedApplicationRouteOptions as a1, PeerState as a2, PeerScope as a3, PeerHealth as a4, ChannelDescriptor as a5, JoinRequest as a6, ConnectionOptions as a7, TransportLatencySnapshot as a8, ManagedDeviceConnectOptions as a9, PeerLifecycleStatus as aa, DeviceStatusSnapshot as b, ResolvedPeerIdentity as c, SignalingEnvelope as d, DeviceEvent as e, SignalingSession as f, SessionEvent as g, BackendPeerUniStream as h, NativeConnectParams as i, NativeConnectResult as j, BackendConnectionState as k, ConnectDeviceResult as l, ConnectDeviceHooks as m, ConnectDeviceOptions as n, ProtocolName as o, ProtocolCapability as p, ProtocolCapabilityMap as q, ApplicationPayloadCrypto as r, ApplicationCryptoStreamTools as s, SpaceTokenProvider as t, AppLimits as u, ApplicationCryptoBiStream as v, ApplicationPayloadReadinessOptions as w, ApplicationPayloadRouteOptions as x, ApplicationPayloadSendOptions as y, DevicePresenceStatus as z };
937
+ export type { RouteDescriptor as $, AuthMode as A, BackendPeerBiStream as B, ConnectDeviceResult as C, DiscoveryMode as D, ExplicitFileDataSendParams as E, PeerScope as F, GrantScope as G, DevicePresenceStatus as H, ISignalingBackend as I, JoinRoomOptions as J, PeerLifecycleStatus as K, LocalDeviceInfo as L, ManagedConnectionRecord as M, NativeManagedSessionStartResult as N, ProtocolCapability as O, PeerSessionSnapshot as P, ProtocolCapabilityMap as Q, ResolvedPeerIdentity as R, SignalingMode as S, TransportLatencySnapshot as T, ApplicationCryptoStreamTools as U, SpaceTokenProvider as V, AppLimits as W, ApplicationCryptoBiStream as X, ProtocolBaseName as Y, ProtocolImplementationKind as Z, ProtocolLocality as _, ConnectDeviceHooks as a, RouteFamily as a0, RouteImplementationKind as a1, SpaceAuthMode as a2, SignalingOptions as a3, RoomCreationMode as a4, ScanningLoopOptions as a5, ScanningLoopHandle as a6, RuntimeBootstrapOptions as a7, RuntimeBootstrapResult as a8, ManagedApplicationRouteOptions as a9, JoinRequest as aa, ConnectDeviceOptions as b, RuntimeIdentity as c, Device as d, DeviceStatusSnapshot as e, SignalingEnvelope as f, DeviceEvent as g, SignalingSession as h, SessionEvent as i, BackendPeerUniStream as j, NativeConnectParams as k, NativeConnectResult as l, BackendConnectionState as m, ClientOptions as n, ConnectionOptions as o, ApplicationPayloadCrypto as p, ApplicationPayloadReadinessOptions as q, ApplicationPayloadRouteOptions as r, ProtocolName as s, ApplicationPayloadSendOptions as t, ChannelDescriptor as u, IncomingStreamChannelMetadata as v, ManagedDeviceConnectOptions as w, PeerState as x, PeerHealth as y, RoomMember as z };
@@ -1,5 +1,5 @@
1
1
  import { A as AuthContext } from './IEngineBridge-C7OT2CRv.js';
2
- import { a7 as ConnectionOptions, r as ApplicationPayloadCrypto, w as ApplicationPayloadReadinessOptions, x as ApplicationPayloadRouteOptions, o as ProtocolName, y as ApplicationPayloadSendOptions, a8 as TransportLatencySnapshot, a5 as ChannelDescriptor$1, L as LocalDeviceInfo, X as IncomingStreamChannelMetadata, C as ClientOptions, a as Device, f as SignalingSession, R as RuntimeIdentity, b as DeviceStatusSnapshot, a9 as ManagedDeviceConnectOptions, a2 as PeerState, a4 as PeerHealth, V as JoinRoomOptions, W as RoomMember, a3 as PeerScope, k as BackendConnectionState, z as DevicePresenceStatus, aa as PeerLifecycleStatus, P as PeerSessionSnapshot } from './types-ByZyADCn.js';
2
+ import { o as ConnectionOptions, p as ApplicationPayloadCrypto, q as ApplicationPayloadReadinessOptions, r as ApplicationPayloadRouteOptions, s as ProtocolName, t as ApplicationPayloadSendOptions, T as TransportLatencySnapshot, u as ChannelDescriptor$1, L as LocalDeviceInfo, v as IncomingStreamChannelMetadata, n as ClientOptions, d as Device, h as SignalingSession, c as RuntimeIdentity, e as DeviceStatusSnapshot, w as ManagedDeviceConnectOptions, x as PeerState, y as PeerHealth, J as JoinRoomOptions, z as RoomMember, F as PeerScope, m as BackendConnectionState, H as DevicePresenceStatus, K as PeerLifecycleStatus, P as PeerSessionSnapshot } from './types-BCkKK8dy.js';
3
3
 
4
4
  interface ITransport {
5
5
  readonly name: string;
@@ -483,7 +483,7 @@ interface RuntimeScopedLogicalChannel {
483
483
  */
484
484
  type RuntimeDeviceStatusSnapshot = Omit<DeviceStatusSnapshot, 'nodeId'>;
485
485
  type RuntimeDeviceStatus = RuntimeDeviceStatusSnapshot;
486
- type RuntimeDevicePresenceStatus$1 = DevicePresenceStatus;
486
+ type RuntimeDevicePresenceStatus = DevicePresenceStatus;
487
487
  type RuntimeIncomingStream = {
488
488
  type: 'bi' | 'uni';
489
489
  stream: any;
@@ -570,37 +570,4 @@ type SessionOptions = RuntimeManagedSessionOptions;
570
570
  type Session = RuntimeManagedSession;
571
571
  type ChannelDescriptor = RuntimeChannelDescriptor;
572
572
 
573
- interface RuntimeDeviceActiveOptions {
574
- now?: number;
575
- /**
576
- * Optional local freshness window for durable roster rows. Leave undefined
577
- * when the caller only wants to honor explicit online/expiresAt state.
578
- */
579
- staleAfterMs?: number;
580
- }
581
- type RuntimeDeviceActivityStatus = Pick<Partial<RuntimeDevice>, 'online' | 'lastSeenAt' | 'updatedAt' | 'createdAt' | 'expiresAt'>;
582
- type RuntimeDeviceRouteStatus = Pick<Partial<RuntimeDeviceStatusSnapshot>, 'settledReady' | 'readinessState' | 'connectionStatus'>;
583
- type RuntimeDevicePresenceStatus = Pick<RuntimeDevice, 'online' | 'ticket'> & Pick<Partial<RuntimeDeviceStatusSnapshot>, 'connectable' | 'presenceStatus' | 'online' | 'ticket'>;
584
- /**
585
- * True when a runtime device row is currently live enough to display or
586
- * consider for app-level routing. This is deliberately separate from
587
- * `isRuntimeDeviceConnectable`: a peer can be active/present before it has a
588
- * usable ticket, and a stale durable row should not keep app UIs alive.
589
- */
590
- declare function isRuntimeDeviceActive(device: RuntimeDeviceActivityStatus, options?: RuntimeDeviceActiveOptions): boolean;
591
- /**
592
- * True once OpenRTC has a routable peer projection for normal app payloads.
593
- *
594
- * This intentionally does not inspect discovery metadata or device
595
- * capabilities. Those fields describe the remote endpoint roster entry; they
596
- * are not proof that an application-level protocol has exchanged its own
597
- * ready/capability message over the mesh.
598
- */
599
- declare function isRuntimeDeviceRoutable(device: RuntimeDeviceRouteStatus): boolean;
600
- /**
601
- * True when the discovery row currently has enough fresh presence to attempt
602
- * a dial. This is a discovery gate, not a connected/readiness gate.
603
- */
604
- declare function isRuntimeDeviceConnectable(device: RuntimeDevicePresenceStatus): boolean;
605
-
606
- export { isRuntimeDeviceActive as $, type PeerReadiness as A, type PeerStreamOptions as B, Connection as C, type DeviceProfile as D, type PresenceLoopOptions as E, type RawConnection as F, type RuntimeAuthContext as G, type RuntimeAuthIdentity as H, type ITransport as I, type RuntimeAutoConnectPolicy as J, type RuntimeConnectionTarget as K, type RuntimeDevicePresenceStatus$1 as L, type RuntimeDeviceStatus as M, type RuntimeLogicalChannelFraming as N, type RuntimeManagedSessionKind as O, type PeerConnectOptions as P, type RuntimeManagedSessionPlatform as Q, type RuntimeClientOptions as R, type RuntimePeerLifecycleStatus as S, type RuntimePeerScope as T, type RuntimePeerSessionSnapshot as U, type RuntimePresenceLoopOptions as V, type RuntimePresencePolicy as W, type RuntimeSession as X, type RuntimeUiConnectionStatus as Y, type ScopedChannelOptions as Z, type ScopedLogicalChannel as _, type RuntimeManagedSessionOptions as a, isRuntimeDeviceConnectable as a0, isRuntimeDeviceRoutable as a1, type RuntimeDeviceActiveOptions as a2, type Session as a3, type SessionOptions as a4, type RuntimeManagedSession as b, type RuntimeDevice as c, type RuntimeDeviceStatusSnapshot as d, type RuntimeDeviceConnectOptions as e, type RuntimeLocalDeviceInfo as f, type RuntimeLocalDeviceProfile as g, type RuntimePeerState as h, type RuntimePeerConnectOptions as i, type RuntimePeerReadinessSnapshot as j, type RuntimePeerHealth as k, type RuntimeChannelDescriptor as l, type RuntimePeerStreamOptions as m, type RuntimeIncomingStream as n, type RuntimeScopedChannelOptions as o, type RuntimeScopedLogicalChannel as p, type RuntimeJoinRoomOptions as q, type RuntimeRoomMember as r, type RuntimeConnectionStateSnapshot as s, type RuntimeApplicationPayloadReadinessOptions as t, type RuntimeConnectionEvent as u, type RuntimeRawConnection as v, type ChannelDescriptor as w, type ConnectionEvent as x, type ConnectionTarget as y, type IncomingStream as z };
573
+ export { type Session as $, type PeerReadiness as A, type PeerStreamOptions as B, Connection as C, type DeviceProfile as D, type PresenceLoopOptions as E, type RawConnection as F, type RuntimeAuthContext as G, type RuntimeAuthIdentity as H, type ITransport as I, type RuntimeAutoConnectPolicy as J, type RuntimeConnectionTarget as K, type RuntimeDevicePresenceStatus as L, type RuntimeDeviceStatus as M, type RuntimeLogicalChannelFraming as N, type RuntimeManagedSessionKind as O, type PeerConnectOptions as P, type RuntimeManagedSessionPlatform as Q, type RuntimeClientOptions as R, type RuntimePeerLifecycleStatus as S, type RuntimePeerScope as T, type RuntimePeerSessionSnapshot as U, type RuntimePresenceLoopOptions as V, type RuntimePresencePolicy as W, type RuntimeSession as X, type RuntimeUiConnectionStatus as Y, type ScopedChannelOptions as Z, type ScopedLogicalChannel as _, type RuntimeManagedSessionOptions as a, type SessionOptions as a0, type RuntimeManagedSession as b, type RuntimeDevice as c, type RuntimeDeviceStatusSnapshot as d, type RuntimeDeviceConnectOptions as e, type RuntimeLocalDeviceInfo as f, type RuntimeLocalDeviceProfile as g, type RuntimePeerState as h, type RuntimePeerConnectOptions as i, type RuntimePeerReadinessSnapshot as j, type RuntimePeerHealth as k, type RuntimeChannelDescriptor as l, type RuntimePeerStreamOptions as m, type RuntimeIncomingStream as n, type RuntimeScopedChannelOptions as o, type RuntimeScopedLogicalChannel as p, type RuntimeJoinRoomOptions as q, type RuntimeRoomMember as r, type RuntimeConnectionStateSnapshot as s, type RuntimeApplicationPayloadReadinessOptions as t, type RuntimeConnectionEvent as u, type RuntimeRawConnection as v, type ChannelDescriptor as w, type ConnectionEvent as x, type ConnectionTarget as y, type IncomingStream as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openrtc",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -35,6 +35,10 @@
35
35
  "types": "./dist/index.d.ts",
36
36
  "import": "./dist/index.js"
37
37
  },
38
+ "./native": {
39
+ "types": "./dist/native.d.ts",
40
+ "import": "./dist/native.js"
41
+ },
38
42
  "./auth": {
39
43
  "types": "./dist/auth/index.d.ts",
40
44
  "import": "./dist/auth/index.js"
@@ -67,8 +71,9 @@
67
71
  },
68
72
  "scripts": {
69
73
  "build": "tsup",
74
+ "check:native-bundle": "node scripts/check-native-entry-bundle.mjs",
70
75
  "build:clean": "rm -rf dist && pnpm run build",
71
- "release:prepare": "pnpm run build:wasm && pnpm run build:clean",
76
+ "release:prepare": "pnpm run build:wasm && pnpm run build:clean && pnpm run check:native-bundle",
72
77
  "build:types": "tsc --noEmit",
73
78
  "build:wasm": "cd ../../crates/openrtc && OPENRTC_REPO_ROOT=$(cd ../.. && pwd) && CARGO_REGISTRY_ROOT=${CARGO_HOME:-$HOME/.cargo} && RUSTUP_TOOLCHAIN=nightly RUSTFLAGS=\"-Zlocation-detail=none --remap-path-prefix=$HOME=/home --remap-path-prefix=$CARGO_REGISTRY_ROOT=/cargo --remap-path-prefix=$OPENRTC_REPO_ROOT=/openrtc\" wasm-pack build --target web --out-dir ../../packages/openrtc/wasm && rm -rf ../../packages/openrtc/wasm/.gitignore",
74
79
  "test": "pnpm run test:deterministic && pnpm run test:emulator",
@@ -1,28 +0,0 @@
1
- import { C as ClientOptions } from './types-ByZyADCn.js';
2
- import { W as WasmBridgeOptions, D as DelegatingRuntimeAdapter } from './DelegatingRuntimeAdapter-D2_dgabz.js';
3
-
4
- type PlutoIpcUnlisten = () => void | Promise<void>;
5
- interface PlutoIpcBridge {
6
- invoke<T = unknown>(command: string, args?: Record<string, unknown>): Promise<T>;
7
- listen<T = unknown>(event: string, handler: (payload: T) => void): Promise<PlutoIpcUnlisten>;
8
- isAvailable?(): boolean | Promise<boolean>;
9
- }
10
- type NativeIpcFailureKind = 'command-unavailable' | 'runtime-unavailable' | 'timeout' | 'unknown';
11
- declare function classifyNativeIpcFailure(error: unknown): NativeIpcFailureKind;
12
- declare function isNativeIpcCommandUnavailable(error: unknown): boolean;
13
-
14
- interface NativeIpcBridgeOptions extends WasmBridgeOptions {
15
- allowWasmFallback?: boolean;
16
- ipcBridge?: PlutoIpcBridge;
17
- transports?: ClientOptions['transports'];
18
- strictMode?: boolean;
19
- }
20
-
21
- interface IpcRuntimeAdapterOptions extends NativeIpcBridgeOptions {
22
- bridge: PlutoIpcBridge;
23
- }
24
- declare class IpcRuntimeAdapter extends DelegatingRuntimeAdapter {
25
- constructor(options: IpcRuntimeAdapterOptions);
26
- }
27
-
28
- export { IpcRuntimeAdapter as I, type NativeIpcBridgeOptions as N, type PlutoIpcBridge as P, type IpcRuntimeAdapterOptions as a, type NativeIpcFailureKind as b, type PlutoIpcUnlisten as c, classifyNativeIpcFailure as d, isNativeIpcCommandUnavailable as i };
@@ -1 +0,0 @@
1
- import {F,E}from'./chunk-MESPJTUA.js';var n=class extends F{constructor(e){super(new E(e));}setWasmClient(e){this.unwrap().setWasmClient(e);}};export{n as a};
@@ -1,2 +0,0 @@
1
- import {w,F,C,E,A,c,p,b as b$1,o,r,s,t,u as u$1,v as v$1}from'./chunk-MESPJTUA.js';import {x,u,b,h,a,E as E$1,G}from'./chunk-34LATQZZ.js';function ie(d){let e=String(d?.message??d??"").toLowerCase();return e?e.includes("__tauri_internals__")||e.includes("window is not defined")||e.includes("cannot read properties of undefined")?"runtime-unavailable":e.includes("timeout after")?"timeout":e.includes("not found")||e.includes("not allowed")||e.includes("unknown command")||e.includes("plugin not found")||e.includes("plugin:openrtc-tauri-plugin")||e.includes("plugin:openrtc")?"command-unavailable":"unknown":"unknown"}function O(d){return ie(d)==="command-unavailable"}function T(d,e="native runtime"){if(!d||typeof d!="object")throw new Error(`[openrtc] ${e} requires a valid IPC bridge object.`);if(typeof d.invoke!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing invoke(command, args).`);if(typeof d.listen!="function")throw new Error(`[openrtc] ${e} IPC bridge is missing listen(event, handler).`);return d}var B=null;async function ne(){return B||(B=(async()=>{let d="openrtc-tauri",e="../../../tauri/src/runtime/ipc";try{return await import(d)}catch(t){try{return await import(e)}catch(i){let n=new Error("[openrtc] Native support now lives in the first-party `openrtc-tauri` package. Install `openrtc-tauri` (and `@tauri-apps/api`) or pass an explicit IPC bridge to OpenRTC.native(...).");throw n.cause={packageError:t,workspaceError:i},n}}})()),B}function Q(){let d=null,e=async()=>(d||(d=ne().then(t=>T(t.createTauriIpcBridge(),"openrtc-tauri"))),d);return {async invoke(t,i){return (await e()).invoke(t,i)},async listen(t,i){return (await e()).listen(t,i)},async isAvailable(){try{let t=await e();return typeof t.isAvailable=="function"?!!await t.isAvailable():!0}catch{return false}}}}var ae="relay-only endpoint ticket unavailable",re=12e3,se=250,oe=1500;function ce(d){return String(d?.message??d??"").toLowerCase().includes(ae)}async function q(d,e={}){let t=e.windowMs??re,i=e.minDelayMs??se,n=e.maxDelayMs??oe,r=Date.now(),s=0,a=null;for(;e.isActive?.()??true;){s+=1;try{return await d()}catch(u$1){if(a=u$1,!ce(u$1))throw u$1;let o=Date.now()-r;if(o>=t)throw u$1;let c=Math.min(x(s,i,n),Math.max(0,t-o));c>0&&await u(c);}}throw a||new Error("endpoint ticket minting stopped before a ticket was available")}function Z(d){let e=d?.split(".")[1];if(!e)return null;try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),i=(4-t.length%4)%4,n=atob(t+"=".repeat(i)),r=JSON.parse(n);return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function X(d,e){let t=d?.[e];return typeof t=="string"&&t.trim()?t.trim():null}function ee(d,e){return X(d,"namespaceId")===e||X(d,"appTag")===`space::${e}`}var v=class v{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.nativeRuntimeCapabilitiesSyncInFlight=null;this.lastNativeAuthSyncAtMs=0;this.hasLoggedMissingAuthForDevices=false;this.runtimeCapabilities=C(null,false);this.fallback=new E(e),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=T(e.ipcBridge??Q(),"NativeIpcBridge"),this.runtimeCapabilities=C(null,this.allowWasmFallback),this.syncNativeRuntimeCapabilities("constructor");}get currentUser(){return this.fallback.currentUser}get tag(){return this.fallback.tag}getRuntimeCapabilities(){let e=A(this.runtimeCapabilities);return e.fallback.wasm=this.allowWasmFallback,e}setWasmClient(e){if(!this.allowWasmFallback){let t="[NativeIpcBridge][NATIVE-GUARD] Refusing WasmClient attachment because native IPC is authoritative and WASM fallback is disabled.";throw console.error(t,{capabilities:this.getRuntimeCapabilities()}),new Error(t)}this.fallback.setWasmClient(e);}onAuthChange(e){return this.fallback.onAuthChange(e)}checkForSSOToken(){return this.fallback.checkForSSOToken()}waitForAuth(){return this.fallback.waitForAuth()}signInAnonymously(){return this.fallback.signInAnonymously()}getTurnCredentials(){return this.fallback.getTurnCredentials()}cleanupStaleDevices(){return this.fallback.cleanupStaleDevices()}sendMessage(e,t,i,n){return this.fallback.sendMessage(e,t,i,n)}pollMessages(e){return this.fallback.pollMessages(e)}createSession(e){return this.fallback.createSession(e)}updateSession(e,t){return this.fallback.updateSession(e,t)}async openPeerBi(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_stream",{peerId:e,timeoutMs:t??null}):this.fallback.openPeerBi(e,t)}async openPeerBiTransportOnly(e,t){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_bi_transport_only_stream",{peerId:e,timeoutMs:t??null},{fallbackCommand:"open_peer_bi_stream"}):this.fallback.openPeerBiTransportOnly(e,t)}async openPeerNativeBi(e,t,i){return await this.canUseTauriIpc()?this.openPeerBiViaIpc("open_peer_native_bi_stream",{peerId:e,label:t,timeoutMs:i??null},{fallbackCommand:"open_peer_bi_stream",fallbackArgs:{peerId:e,timeoutMs:i??null}}):this.fallback.openPeerNativeBi(e,t,i)}async incoming_streams(){if(!await this.canUseTauriIpc()){let r=this.fallback;if(typeof r.incoming_streams=="function")return r.incoming_streams();throw new Error("Native incoming stream bridge is unavailable")}let e=`native-incoming-${Date.now()}-${++this.subscriptionNonce}`,t=null,i=false,n=async()=>{i=true;let r=t;t=null,await Promise.allSettled([r?Promise.resolve(r()):Promise.resolve(),this.invokeIpc("stop_rtc_subscription",{requestId:e},{timeoutMs:null}).catch(()=>{})]);};return new ReadableStream({start:async r=>{try{t=await this.listenIpc("openrtc://peer-bi-stream/incoming",s=>{if(i)return;let a=s.payload,u=typeof a?.requestId=="string"?a.requestId:typeof a?.request_id=="string"?a.request_id:"";if(u!==e){c("[NativeIpcBridge][incoming-application-stream] ignored request id",{expectedRequestId:e,eventRequestId:u});return}let o=typeof a?.streamId=="string"?a.streamId.trim():typeof a?.stream_id=="string"?a.stream_id.trim():"";if(!o)return;let c$1=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():typeof a?.remote_node_id=="string"?a.remote_node_id.trim():"",l=Number.isSafeInteger(a?.transportStableId)?Number(a.transportStableId):Number.isSafeInteger(a?.transport_stable_id)?Number(a.transport_stable_id):0;if(!c$1||l<=0){c("[NativeIpcBridge][incoming-application-stream] ignored invalid generation",{requestId:e,remoteNodeId:c$1,transportStableId:l});return}c("[NativeIpcBridge][incoming-application-stream] accepted event",{requestId:e,remoteNodeId:c$1,transportStableId:l});let g=this.peerBiStreamFromId(o,{startReadAfterListeners:!0});r.enqueue({type:"bi",stream:{send:g.writable,recv:g.readable,endpoint_id:c$1},endpointId:c$1,transportStableId:l,protocolHint:"unknown",channel:null});}),await this.invokeIpc("start_incoming_peer_bi_streams",{requestId:e},{timeoutMs:null});}catch(s){i=true,r.error(s),await n();}},cancel:async()=>{await n();}})}async is_current_transport_stable_id(e,t){if(!await this.canUseTauriIpc()){let i=this.fallback;return typeof i.is_current_transport_stable_id=="function"?i.is_current_transport_stable_id(e,t):false}return !e.trim()||t<=0n||t>BigInt(Number.MAX_SAFE_INTEGER)?false:this.invokeIpc("is_current_transport_stable_id",{endpointId:e.trim(),transportStableId:Number(t)})}openPeerUni(e,t){return this.fallback.openPeerUni(e,t)}isConnected(e){return this.fallback.isConnected(e)}getAuthContext(){return this.fallback.getAuthContext()}resolveNativeAuthScopedUserId(e){return this.currentUser?.id??this.getAuthContext()?.userId??e??null}resolveConfiguredSpaceKey(){let e=this.options.spaceKey??this.options.space;return typeof e=="string"?e.trim():""}usesAnonymousSpaceMode(){return this.options.authMode==="anonymous"&&this.resolveConfiguredSpaceKey().length>0}requiresNativeAuthToken(){return !this.usesAnonymousSpaceMode()||typeof this.options.spaceTokenProvider=="function"}async nativeAuthTokenMatchesExpectedScope(e){if(!this.usesAnonymousSpaceMode())return true;let t=typeof this.options.apiKey=="string"?this.options.apiKey.trim():"",i=this.resolveConfiguredSpaceKey();if(!t||!i)return true;let n=await b(t,i).catch(()=>null);return n?ee(Z(e),n):true}resolveNativeSignalingUserId(e){return this.usesAnonymousSpaceMode()?(typeof e=="string"?e.trim():"")||this.resolveConfiguredSpaceKey()||null:this.resolveNativeAuthScopedUserId(e)}getCurrentUserId(){return this.resolveNativeSignalingUserId(this.fallback.getCurrentUserIdForScope())}nativeAuthWaitMs(){return this.requiresNativeAuthToken()?v.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=p(e);if(this.matchesTag(t))return {keep:true,classification:"match"};let i=typeof t.appTag=="string"&&t.appTag.trim().length>0?t.appTag.trim():typeof t.tag=="string"&&t.tag.trim().length>0?t.tag.trim():void 0;return i===void 0?{keep:true,classification:"untagged"}:{keep:false,classification:"foreign",foreignTag:i}}filterNativeRosterByTag(e,t){let i=new Set,n=e.filter(r=>{let s=this.nativeRosterTagDisposition(r);return !s.keep&&s.foreignTag&&i.add(s.foreignTag),s.keep});return e.length>0&&n.length===0&&i.size>0?console.warn(`[NativeIpcBridge] ${t}: dropped ALL ${e.length} native device(s) as foreign-app \u2014 this is the app-tag drift signature (empty native device list). The native Rust OpenRTC app tag does not match the SDK app tag; check that the desktop binary and the web bundle use the same VITE_PLUTO_OPENRTC_API_KEY / VITE_PLUTO_OPENRTC_APP_TAG for this environment lane.`,{sdkAppTag:this.appTag,foreignTags:Array.from(i),droppedCount:e.length}):i.size>0&&c(`[NativeIpcBridge] ${t}: filtered ${e.length-n.length} foreign-app device(s) from the native roster`,{sdkAppTag:this.appTag,foreignTags:Array.from(i)}),n}normalizeNativeIceServer(e){let t=e.urls,i=Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.trim().length>0):typeof t=="string"&&t.trim().length>0?[t]:[];return i.length===0?null:{urls:i,username:typeof e.username=="string"&&e.username.trim().length>0?e.username:void 0,credential:typeof e.credential=="string"&&e.credential.trim().length>0?e.credential:void 0}}filterNativeStunServers(e){return e.map(t=>({...t,urls:t.urls.filter(i=>!i.startsWith("stun:"))})).filter(t=>t.urls.length>0)}nativeIceServerHasTurnUrl(e){return e.urls.some(t=>t.startsWith("turn:")||t.startsWith("turns:"))}async loadNativeTurnIceServers(){if(typeof this.turnCredentialsProvider!="function")return [];let e=await this.turnCredentialsProvider().catch(t=>(console.warn("[NativeIpcBridge] TURN credential provider failed:",t),null));return !e||!Array.isArray(e.iceServers)?[]:e.iceServers.map(t=>this.normalizeNativeIceServer(t)).filter(t=>!!t)}async buildNativeTransportConfigPayload(){let e=this.transportOptions;if(!e&&!this.strictMode)return null;let t=null;if(!this.strictMode&&e?.iroh&&typeof e.iroh=="object"){let o=e.iroh;o.localDiscovery===true&&(t={enabled:true,advertise:o.localDiscoveryMode!=="passive"});}let i=null;if(e?.webrtc===true||e?.webrtc&&typeof e.webrtc=="object"){let o=e.webrtc===true?null:e.webrtc,c=o?.useDefaultIceServers!==false,l=Array.isArray(o?.iceServers)&&o.iceServers.length>0?o.iceServers.map(m=>this.normalizeNativeIceServer(m)).filter(m=>!!m):c?h.map(m=>this.normalizeNativeIceServer(m)).filter(m=>!!m):[],g=this.strictMode||o?.privacyMode===true;(this.strictMode||o?.privacyMode===true||o?.useTurn===true)&&(l=[...l,...await this.loadNativeTurnIceServers()]),g&&(l=this.filterNativeStunServers(l));let h$1=l.some(m=>this.nativeIceServerHasTurnUrl(m)),f=g&&h$1;g&&!h$1&&console.warn("[NativeIpcBridge] Relay-only WebRTC requested, but no TURN servers are configured; native WebRTC override disabled");let k=o?.lanMode===true;(l.length>0||f||k||!c)&&(i={iceServers:l.length>0||!c?l:void 0,privacyMode:f,lanMode:k||void 0});}let n=null;if(e?.moq&&typeof e.moq=="object"){let o=typeof e.moq.relayUrl=="string"&&e.moq.relayUrl.trim().length>0?e.moq.relayUrl:void 0;if(o){let c=typeof e.moq.accessToken=="string"&&e.moq.accessToken.trim().length>0?e.moq.accessToken.trim():void 0;n={relayUrl:o,accessToken:c};}}let r=null;if(!this.strictMode&&(e?.ble===true||e?.ble&&typeof e.ble=="object")){let o=e.ble===true?null:e.ble,c=Number(o?.connectTimeoutMs);r={enabled:o?.enabled!==false,connectTimeoutMs:Number.isFinite(c)&&c>0?Math.round(c):void 0};}let s=this.strictMode||e?.iroh&&typeof e.iroh=="object"&&e.iroh.relayOnly===true,a=e?.iroh&&typeof e.iroh=="object"?e.iroh.relayTransportPolicy:void 0,u=this.strictMode?a??"auto":a;return !s&&!u&&!i&&!n&&!t&&!r?null:{irohRelayOnly:s||void 0,irohRelayTransportPolicy:u,irohLan:t,webrtc:i,moq:n,ble:r}}isTauriEnv(){return a()}nextConnectionEventRetryDelayMs(e){return x(e,v.CONNECTION_EVENT_RETRY_MIN_DELAY_MS,v.CONNECTION_EVENT_RETRY_MAX_DELAY_MS)}async clearNativeAuthRelay(e){if(await this.canUseTauriIpc())try{await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:null,refreshToken:null}),this.lastSyncedAuthToken=null,this.lastNativeAuthSyncAtMs=0,c(`[NativeIpcBridge] cleared native auth relay (${e})`);}catch(t){console.warn(`[NativeIpcBridge] failed clearing native auth relay (${e}):`,t);}}async relayNativeAuthToken(e,t,i,n){if(!await this.canUseTauriIpc())return true;if(!await this.nativeAuthTokenMatchesExpectedScope(e))return c(`[NativeIpcBridge] auth sync deferred (${i}): token claims do not match configured space`),false;if(e===this.lastSyncedAuthToken)return true;try{await this.invokeIpc("desktop_set_pluto_auth_token",{authToken:e,refreshToken:t??null});}catch(r){return O(r)?console.warn(`[NativeIpcBridge] desktop auth relay unavailable (${i}); install/register openrtc-tauri-plugin and include its default permission set.`,r):console.warn(`[NativeIpcBridge] desktop auth relay failed (${i}):`,r),false}return this.lastSyncedAuthToken=e,this.lastNativeAuthSyncAtMs=Date.now(),c(`[NativeIpcBridge] auth token relayed to native runtime (${i}) user_id=${n??this.currentUser?.id??"unknown"}`),true}async relayExplicitNativeAuthContext(e){let t=this.authSyncInFlight,i=(async()=>(await t?.catch(()=>{}),this.relayNativeAuthToken(e.token,e.refreshToken,"setAuthContext",e.userId)))();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}applyNativeRuntimeStatus(e){this.runtimeCapabilities=C(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:v.NATIVE_STATUS_IPC_TIMEOUT_MS});this.applyNativeRuntimeStatus(t),c(`[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<v.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("[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("[NativeIpcBridge] Tauri IPC probe reached native layer (command-level error acceptable)"),this.tauriCoreAvailabilityValue=!0,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),!0)}}catch{return this.tauriCoreAvailabilityValue=false,this.tauriCoreAvailabilityCheckedAtMs=Date.now(),false}})().finally(()=>{this.tauriCoreAvailability=null;})),this.tauriCoreAvailability)}async invokeIpc(e,t,i){let n=this.ipcBridge.invoke(e,t),r=i&&Object.prototype.hasOwnProperty.call(i,"timeoutMs")?i.timeoutMs:v.DEFAULT_BOUNDED_IPC_TIMEOUT_MS;return r==null||r<=0?n:E$1(n,r,()=>new Error(`${e} timeout after ${r}ms`))}async listenIpc(e,t){return this.ipcBridge.listen(e,i=>{t({payload:i});})}async openPeerBiViaIpc(e,t,i){let n=await this.invokePeerBiOpen(e,t,i),r=typeof n?.streamId=="string"?n.streamId.trim():typeof n?.stream_id=="string"?n.stream_id.trim():"";if(!r)throw new Error(`${e} returned no streamId`);return this.peerBiStreamFromId(r)}peerBiStreamFromId(e,t={}){let i=this,n=null,r=null,s=false,a=null,u=null,o=async()=>{let h=[n,r];n=null,r=null,await Promise.allSettled(h.filter(f=>typeof f=="function").map(f=>Promise.resolve(f())));},c=(async()=>{n=await this.listenIpc("openrtc://peer-bi-stream/chunk",h=>{let f=h.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||s||!a)return;let w=f?.bytes;w instanceof Uint8Array?a.enqueue(w):Array.isArray(w)&&a.enqueue(new Uint8Array(w));}),r=await this.listenIpc("openrtc://peer-bi-stream/closed",h=>{let f=h.payload;if((typeof f?.streamId=="string"?f.streamId:typeof f?.stream_id=="string"?f.stream_id:"")!==e||s||!a)return;s=true;let w=typeof f?.error=="string"?f.error.trim():"";w?a.error(new Error(w)):a.close(),o();}),t.startReadAfterListeners&&await this.invokeIpc("start_peer_bi_stream_read",{streamId:e},{timeoutMs:null});})().catch(h=>{u=h,a&&!s&&(s=true,a.error(h));}),l=async()=>{await this.invokeIpc("close_peer_bi_stream",{streamId:e},{timeoutMs:null}).catch(()=>{}),await o();},g=new ReadableStream({async start(h){a=h,await c,u&&!s&&(s=true,h.error(u));},async cancel(){s=true,await l();}}),y=new WritableStream({write:async h=>{await i.invokeIpc("write_peer_bi_stream",{streamId:e,bytes:Array.from(h)},{timeoutMs:null});},close:l,abort:l});return {readable:g,writable:y}}async invokePeerBiOpen(e,t,i){try{return await this.invokeIpc(e,t)}catch(n){if(!i?.fallbackCommand||!this.isMissingNativeCommandError(n))throw n;return this.invokeIpc(i.fallbackCommand,i.fallbackArgs??t)}}isMissingNativeCommandError(e){let t=e instanceof Error?e.message:String(e??"");return t.includes("Command")&&t.includes("not found")}async shouldUseTauriSignaling(){if(await this.canUseTauriIpc())return true;if(this.allowWasmFallback)return false;throw new Error("[pluto-rtc] Tauri runtime adapter requires native IPC, but it is unavailable.")}async signInWithPluto(){if(!await this.canUseTauriIpc()){await this.fallback.signInWithPluto();return}let e=await this.invokeIpc("rtc_sign_in_with_pluto"),t=typeof e?.customToken=="string"?e.customToken.trim():"";if(!t)throw new Error("[pluto-rtc] Native Pluto SSO did not return a custom token.");await G().signInWithCustomTokenValue(t),await this.ensureNativeAuth("pluto-sso",{requireToken:true,maxWaitMs:1e4});}async setAuthContext(e){let t=this.getAuthContext()?.userId??null,i=typeof e?.userId=="string"&&e.userId.trim()||null,n=this.fallback.setAuthContext(e);if(t&&i&&t!==i&&await this.stopNativeAuthScopedActivity(t),await n,!e?.token)await this.clearNativeAuthRelay("setAuthContext");else if(!await this.relayExplicitNativeAuthContext(e))throw new Error("Native auth token unavailable for setAuthContext")}async signOut(){await this.fallback.signOut(),await this.clearNativeAuthRelay("signOut");}async stopAuthScopedActivity(e){let t=this.resolveNativeSignalingUserId(e?.userId??null);await this.stopNativeAuthScopedActivity(t);}async stopNativeAuthScopedActivity(e){let t=await this.shouldUseTauriSignaling();if(o("NativeIpcBridge.stopAuthScopedActivity",{userId:e,useTauri:t}),t)try{await Promise.allSettled([this.revokeSessionTokensByScope("user-device"),this.invokeIpc("stop_rtc_presence_loop"),this.invokeIpc("stop_rtc_auto_connect"),e?this.invokeIpc("set_rtc_offline",{userId:e}):Promise.resolve()]);}catch(i){console.warn("[NativeIpcBridge] Failed to stop native auth-scoped RTC activity:",i);}await this.fallback.stopAuthScopedActivity({userId:e});}async ensureNativeAuthOnce(e,t){if(!await this.canUseTauriIpc())return true;if(this.authSyncInFlight)return this.authSyncInFlight;let i=(async()=>{try{if(!this.currentUser)return c(`[NativeIpcBridge] auth sync deferred (${e}): no current user`),!t;let n=Date.now()-this.lastNativeAuthSyncAtMs>=480*1e3,r=this.currentUser?.getToken?await this.currentUser.getToken(n):null,a=this.getAuthContext()?.refreshToken??this.auth?.currentUser?.refreshToken??null;return r?this.relayNativeAuthToken(r,a,e,this.currentUser?.id):(c(`[NativeIpcBridge] auth sync deferred (${e}): missing token for user ${this.currentUser?.id}`),!t)}catch(n){return console.error("[NativeIpcBridge] auth sync failed:",n),false}})();this.authSyncInFlight=i;try{return await i}finally{this.authSyncInFlight===i&&(this.authSyncInFlight=null);}}async ensureNativeAuth(e="runtime",t){if(!await this.canUseTauriIpc())return true;let i=t?.requireToken??false,n=t?.maxWaitMs??(i?v.AUTH_REQUIRED_WAIT_MS:0),r=t?.pollMs??250,s=Date.now()+Math.max(0,n);for(;;){if(await this.ensureNativeAuthOnce(e,i))return true;if(!i||Date.now()>=s)return false;await u(r);}}decodeNativeDeviceIdentity(e){let t=e?.systemInfo??e?.system_info??null,i=typeof e?.deviceId=="string"?e.deviceId.trim():typeof e?.device_id=="string"?e.device_id.trim():"",n=typeof e?.deviceName=="string"?e.deviceName.trim():typeof e?.device_name=="string"?e.device_name.trim():"",r=typeof e?.platformType=="string"?e.platformType.trim():typeof e?.platform_type=="string"?e.platform_type.trim():typeof t?.platformType=="string"?t.platformType.trim():typeof t?.platform_type=="string"?t.platform_type.trim():"";return {deviceId:i,deviceName:n,platformType:r}}async resolveLocalDeviceId(){if(this.cachedLocalDeviceId)return this.cachedLocalDeviceId;if(await this.canUseTauriIpc())try{let t=await this.invokeIpc("get_rtc_local_device_info"),{deviceId:i,deviceName:n}=this.decodeNativeDeviceIdentity(t);if(i)return this.cachedLocalDeviceId=i,n&&(this.cachedLocalDeviceName=n),i}catch(t){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",t);}let e=this.resolveWebLogicalDeviceId();return this.cachedLocalDeviceId=e,e}async resolveLocalDeviceName(){if(this.cachedLocalDeviceName)return this.cachedLocalDeviceName;if(await this.canUseTauriIpc())try{let e=await this.invokeIpc("get_rtc_local_device_info"),{deviceName:t}=this.decodeNativeDeviceIdentity(e);if(t){let i=this.normalizeNativeDeviceName(t);return this.cachedLocalDeviceName=i,i}}catch(e){console.warn("[NativeIpcBridge] get_rtc_local_device_info failed:",e);}return this.defaultDeviceNameFallback()}normalizeNativeDeviceName(e){let t=e.trim();if(!t)return this.defaultDeviceNameFallback();if(t==="Desktop Device"){let i=this.defaultDeviceNameFallback();if(i!=="Desktop Device")return i}return t}defaultDeviceNameFallback(){if(typeof window>"u"||typeof navigator>"u")return "Desktop Device";let e=navigator.userAgent||"";return /iPhone|iPad|iPod/i.test(e)?"iPhone":/Android/i.test(e)?"Android":"Desktop Device"}inferNativePlatformTypeFallback(){if(typeof window>"u"||typeof navigator>"u")return "desktop";if(!this.isTauriEnv())return "web";let e=navigator.userAgent||"";return /iPhone|iPad|iPod|Android|Mobile/i.test(e)?"mobile":"desktop"}withPresenceMetadata(e,t){try{let i=e?JSON.parse(e):{};return JSON.stringify({...i,deviceId:t,plutoVersion:"0.1.0-desktop"})}catch{return JSON.stringify({deviceId:t,plutoVersion:"0.1.0-desktop",rawMetadata:e})}}async searchDevices(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("searchDevices",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for searchDevices");let i=await this.invokeIpc("search_rtc_devices",{userId:this.getCurrentUserId()});if(Array.isArray(i?.devices)){let n=i.devices.map(r=>this.normalizeDevice(r));return e&&(n=n.filter(r=>r.ticket!==e&&r.deviceId!==e&&r.nodeId!==e)),n}throw typeof i?.message=="string"?new Error(String(i.message)):new Error("Unexpected response for search_rtc_devices")}return this.fallback.searchDevices(e)}async listDevicesWithStatus(){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("listDevicesWithStatus",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for listDevicesWithStatus");let t=await this.invokeIpc("search_rtc_devices_with_status",{userId:this.getCurrentUserId()});if(Array.isArray(t?.devices)){let i=t.devices,n=this.filterNativeRosterByTag(i,"listDevicesWithStatus").map(a=>r(a)),r$1=await this.resolveLocalDeviceId().catch(()=>null),s=!!r$1&&n.some(a=>a.deviceId===r$1);return b$1("[NativeIpcBridge] listDevicesWithStatus result",{rawCount:i.length,count:n.length,localDeviceId:r$1,selfIncluded:s,devices:n.map(a=>({deviceId:a.deviceId,deviceName:a.deviceName,online:!!a.online,presenceStatus:a.presenceStatus,connectable:a.connectable,connectionStatus:a.connectionStatus,settledReady:!!a.settledReady,peerHealth:a.peerHealth,scopes:a.scopes,connectionId:a.connectionId??null,deviceIdHint:a.deviceIdHint??null,nodeId:a.nodeId??null,activeTransport:a.activeTransport??null,parallelTransport:a.parallelTransport??null}))}),r$1&&!s&&b$1("[NativeIpcBridge] native status snapshot excludes local device by design",{localDeviceId:r$1,count:n.length}),n}throw typeof t?.message=="string"?new Error(String(t.message)):new Error("Unexpected response for search_rtc_devices_with_status")}return this.fallback.listDevicesWithStatus()}async getPeerSession(e){if(await this.shouldUseTauriSignaling()){let t=await this.invokeIpc("get_rtc_peer_session",{id:e});return !t||typeof t!="object"?null:s(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=>s(t))}return this.fallback.listPeerSessions()}async waitForSettledPeer(e,t){if(await this.shouldUseTauriSignaling()){let i=typeof t=="number"?Math.max(v.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,t+1e3):v.DEFAULT_BOUNDED_IPC_TIMEOUT_MS,n=await this.invokeIpc("wait_for_rtc_settled_peer",{id:e,timeoutMs:t},{timeoutMs:i});return !n||typeof n!="object"?null:s(n)}return this.fallback.waitForSettledPeer(e,t)}async resolvePeerConnectionRecords(e){if(await this.shouldUseTauriSignaling()){let t$1=await this.invokeIpc("resolve_rtc_peer_connection_records",{id:e});return (Array.isArray(t$1)?t$1:[]).map(i=>t(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 u$1(t)}return this.fallback.resolvePeerIdentity(e)}async setOffline(e){if(await this.shouldUseTauriSignaling())try{if(!await this.ensureNativeAuth("setOffline",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for setOffline");let i=this.getCurrentUserId();await this.invokeIpc("set_rtc_offline",{userId:i});return}catch(t){console.warn("[NativeIpcBridge] set_rtc_offline failed:",t);}return this.fallback.setOffline(e)}async updateDevice(e,t){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("updateDevice",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for updateDevice");let r=this.getCurrentUserId();if(!r)throw new Error("updateDevice requires authenticated user scope");try{await this.invokeIpc("update_rtc_device",{userId:r,deviceId:e,deviceName:t.deviceName??null,capabilities:t.capabilities??null,metadata:t.metadata??null});return}catch(s){throw console.warn("[NativeIpcBridge] update_rtc_device failed:",s),s instanceof Error?s:new Error(String(s))}}return this.fallback.updateDevice(e,t)}async deleteDevice(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("deleteDevice",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for deleteDevice");let n=this.getCurrentUserId();if(!n)throw new Error("deleteDevice requires authenticated user scope");try{await this.invokeIpc("delete_rtc_device",{userId:n,deviceId:e});return}catch(r){throw console.warn("[NativeIpcBridge] delete_rtc_device failed:",r),r instanceof Error?r:new Error(String(r))}}return this.fallback.deleteDevice(e)}async getLocalDeviceInfo(){if(!await this.canUseTauriIpc()){let e=await this.getLocalDeviceId?.();return e?{deviceId:e,deviceName:this.defaultDeviceNameFallback(),platformType:this.inferNativePlatformTypeFallback()}:null}try{let e=await this.invokeIpc("get_rtc_local_device_info"),t=this.decodeNativeDeviceIdentity(e),{deviceId:i}=t;return i?{deviceId:i,deviceName:this.normalizeNativeDeviceName(t.deviceName),platformType:t.platformType||this.inferNativePlatformTypeFallback(),capabilities:e?.capabilities??void 0,lastSeenAt:typeof e?.last_seen_at=="string"?e.last_seen_at:void 0}:null}catch(e){return console.warn("[NativeIpcBridge] getLocalDeviceInfo failed:",e),null}}async updateLocalDeviceName(e){if(!await this.canUseTauriIpc())return null;try{let t=await this.invokeIpc("update_rtc_local_device_name",{deviceName:e}),i=this.decodeNativeDeviceIdentity(t),{deviceId:n}=i;return n?(this.cachedLocalDeviceName=this.normalizeNativeDeviceName(e),{deviceId:n,deviceName:this.cachedLocalDeviceName,platformType:i.platformType||this.inferNativePlatformTypeFallback(),capabilities:t?.capabilities??void 0,lastSeenAt:typeof t?.last_seen_at=="string"?t.last_seen_at:void 0}):null}catch(t){return console.warn("[NativeIpcBridge] updateLocalDeviceName failed:",t),null}}async startManagedSessionNative(e){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startManagedSessionNative().");if(!await this.ensureNativeAuth("startManagedSessionNative",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startManagedSessionNative");let i=this.resolveNativeSignalingUserId(e.userId);if(!i)throw new Error("Native managed session startup requires a runtime auth-scoped user id.");i!==e.userId&&console.info("[NativeIpcBridge][managed-session][user-id-remap]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i});let n=this.resolveConfiguredSpaceKey();console.info("[NativeIpcBridge][managed-session][start-request]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,spaceKey:n?"[configured]":null,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,presence:e.presence!==false,autoConnect:e.autoConnect!==false,hasMetadata:typeof e.metadata=="string"&&e.metadata.trim().length>0});let r=await this.buildNativeTransportConfigPayload(),s={userId:i,deviceName:e.deviceName??null,localDeviceId:e.localDeviceId??null,metadata:e.metadata??null,...r?{transports:r}:{},autoConnect:e.autoConnect!==false,presence:e.presence!==false,apiKey:this.options.apiKey??null,spaceKey:n||null},a=await this.invokeIpc("start_rtc_managed_session",s,{timeoutMs:null});this.syncNativeRuntimeCapabilities("managed-session-started");let u=typeof a?.ticket=="string"&&a.ticket.trim().length>0?a.ticket.trim():null,o=a?.localDevice&&typeof a.localDevice=="object"?a.localDevice:a?.local_device&&typeof a.local_device=="object"?a.local_device:null,c=o?{deviceId:typeof o.deviceId=="string"?o.deviceId:typeof o.device_id=="string"?o.device_id:"",deviceName:this.normalizeNativeDeviceName(typeof o.deviceName=="string"?o.deviceName:typeof o.device_name=="string"?o.device_name:""),platformType:typeof o.platformType=="string"?o.platformType:typeof o.platform_type=="string"?o.platform_type:"desktop",capabilities:o.capabilities??void 0,lastSeenAt:typeof o.lastSeenAt=="string"?o.lastSeenAt:typeof o.last_seen_at=="string"?o.last_seen_at:void 0}:null,l={localNodeId:typeof a?.localNodeId=="string"?a.localNodeId:typeof a?.local_node_id=="string"?a.local_node_id:null,ticket:u,ticketScope:typeof a?.ticketScope=="string"?a.ticketScope:typeof a?.ticket_scope=="string"?a.ticket_scope:null,presenceStarted:typeof a?.presenceStarted=="boolean"?a.presenceStarted:!!a?.presence_started,autoConnectStarted:typeof a?.autoConnectStarted=="boolean"?a.autoConnectStarted:!!a?.auto_connect_started,localDevice:c?.deviceId?c:null};return console.info("[NativeIpcBridge][managed-session][ipc-started]",{requestedUserId:e.userId,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:i,localNodeId:l.localNodeId,ticketScope:l.ticketScope,presenceStarted:l.presenceStarted,autoConnectStarted:l.autoConnectStarted,localDeviceId:l.localDevice?.deviceId??null}),l}async reconcileNativeManagedSession(e){if(!await this.shouldUseTauriSignaling())return null;if(!await this.ensureNativeAuth("reconcileNativeManagedSession",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for reconcileNativeManagedSession");return this.invokeIpc("reconcile_mobile_rtc_after_resume",{reason:e?.reason??"frontend"})}async notifyNetworkChange(e){return await this.canUseTauriIpc()?(c("[NativeIpcBridge] forwarding host network-change hint",{reason:e?.reason??"host"}),this.invokeIpc("notify_rtc_network_change")):null}async getManagedNodeId(e){let t=e?.initializeIfMissing??true;console.info("[NativeIpcBridge][getManagedNodeId] enter",{initializeIfMissing:t});let i=await this.canUseTauriIpc();if(console.info("[NativeIpcBridge][getManagedNodeId] canUseTauriIpc",{canUse:i}),!i)return null;try{console.info("[NativeIpcBridge][getManagedNodeId] invoking get_iroh_node_id");let n=await this.invokeIpc("get_iroh_node_id");if(console.info("[NativeIpcBridge][getManagedNodeId] get_iroh_node_id returned",{existing:n}),n||!t)return n;console.info("[NativeIpcBridge][getManagedNodeId] invoking start_iroh_node");let r=await this.invokeIpc("start_iroh_node");return console.info("[NativeIpcBridge][getManagedNodeId] start_iroh_node returned",{started:r}),r}catch(n){if(console.warn("[NativeIpcBridge] getManagedNodeId failed:",n),!t)return null;throw n}}async getEndpointTicket(){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] getEndpointTicket requires native IPC in Tauri runtime.");return q(()=>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:v.AUTH_REQUIRED_WAIT_MS}):c("[NativeIpcBridge] connectToDevice using anonymous native ticket path");let t=Math.max(1,Math.floor(e.timeoutMs??v.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 q(()=>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(o("NativeIpcBridge.revokeSessionTokensByScope",{grantScope:e}),!await this.canUseTauriIpc())return [];try{return await this.invokeIpc("revoke_session_tokens_by_scope",{scope:e})}catch{return []}}async disconnectDevice(e){if(!await this.canUseTauriIpc())throw new Error("[pluto-rtc] disconnectDevice requires native IPC in Tauri runtime.");await this.invokeIpc("disconnect_device",{deviceId:e});}async setAutoConnectExcluded(e,t){await this.canUseTauriIpc()&&await this.invokeIpc("set_auto_connect_excluded",{deviceId:e,excluded:t});}onDevicesChange(e,t){let i=false,n=new Map,r=null,s=false,a=false,u$1=()=>{if(a=false,i)return;let g=Array.from(n.values());t&&(g=g.filter(y=>y.ticket!==t&&y.deviceId!==t&&y.nodeId!==t)),e(g);},o=()=>{if(!a){if(a=true,typeof queueMicrotask=="function"){queueMicrotask(u$1);return}Promise.resolve().then(u$1);}},c$1=async()=>{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] onDevicesChange falling back to wasm signaling (Tauri IPC unavailable)"),l=this.fallback.onDevicesChange(e,t);return}for(;!i;)try{let g=this.requiresNativeAuthToken()?15e3:0,y=Date.now()+g,h=this.getCurrentUserId();for(;!i&&!h&&Date.now()<y&&(this.hasLoggedMissingAuthForDevices||(this.hasLoggedMissingAuthForDevices=!0,c("[NativeIpcBridge] onDevicesChange waiting for authenticated user before subscription")),h=this.getCurrentUserId(),!h);)await u(250);if(!h){!i&&!s&&(console.warn("[NativeIpcBridge] onDevicesChange could not resolve authenticated user; keeping subscription in retry mode"),e([]),s=!0),await u(1e3);continue}if(!await this.ensureNativeAuth("onDevicesChange",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:Math.max(0,y-Date.now())})){!i&&!s&&(console.warn("[NativeIpcBridge] onDevicesChange timed out waiting for auth token; keeping subscription in retry mode"),e([]),s=!0),await u(1e3);continue}this.hasLoggedMissingAuthForDevices=!1,s=!1,c(`[NativeIpcBridge] onDevicesChange starting subscription user_id=${h}`);let k=await this.listDevicesWithStatus().catch(async m=>(c(`[NativeIpcBridge] onDevicesChange full-roster seed failed; falling back to online-only search: ${m}`),this.searchDevices(t)));n.clear();for(let m of k)m?.deviceId&&n.set(m.deviceId,m);for(o(),r=(await this.subscribeDevices(h)).getReader();!i;){let{done:m,value:L}=await r.read();if(m||!L)break;for(let N of L){if(N.type==="removed"){n.delete(N.deviceId);continue}let M=N.device?.deviceId,R=this.nativeRosterTagDisposition(N.device??{});if(!R.keep){R.foreignTag&&c("[NativeIpcBridge] onDevicesChange dropped foreign-app device event",{sdkAppTag:this.appTag,foreignTag:R.foreignTag,deviceId:M??null}),M&&n.delete(M);continue}let E=this.normalizeDevice(N.device);E.deviceId&&n.set(E.deviceId,E);}o();}}catch(g){i||(console.error("[NativeIpcBridge] onDevicesChange stream failed; retrying subscription:",g),await u(1e3));}finally{if(r){try{await r.cancel();}catch{}r=null;}}},l=()=>{i=true,r&&(r.cancel(),r=null);};return c$1(),()=>l()}async subscribeDevices(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("subscribeDevices",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for subscribeDevices");let i=`sub-${Math.random().toString(36).substring(2,11)}`,n=null,r=null,s=false,a=async()=>{if(!s&&(s=true,n&&(await Promise.resolve(n()),n=null),r)){try{await r();}catch{}r=null;}};return new ReadableStream({start:async u=>{c(`[NativeIpcBridge] subscribeDevices request start user_id=${e} request_id=${i}`),n=await this.listenIpc("rtc-device-events",o=>{if(s)return;let c=o.payload;if(c.requestId===i){if(c.type==="deviceEvents"){let l=Array.isArray(c.events)?c.events.length:0;b$1(`[NativeIpcBridge] subscribeDevices event batch request_id=${i} count=${l}`);try{u.enqueue(c.events);}catch{a();}}else if(c.type==="error"&&(console.warn(`[NativeIpcBridge] subscribeDevices stream error request_id=${i}: ${c.message}`),!s)){try{u.error(c.message);}catch{}a();}}}),r=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_device_subscription",{requestId:i,userId:e});}catch(o){try{u.error(o);}catch{}await a();}},cancel:async()=>{c(`[NativeIpcBridge] subscribeDevices request stop request_id=${i}`),await a();}})}return this.fallback.subscribeDevices(e)}async subscribeSessions(e){if(await this.shouldUseTauriSignaling()){if(!await this.ensureNativeAuth("subscribeSessions",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for subscribeSessions");let i=`sub-${Math.random().toString(36).substring(2,11)}`,n=await this.resolveLocalDeviceId()||e,r=null,s=null,a=false,u=async()=>{if(!a&&(a=true,r&&(await Promise.resolve(r()),r=null),s)){try{await s();}catch{}s=null;}};return new ReadableStream({start:async o=>{r=await this.listenIpc("rtc-session-events",c=>{if(a)return;let l=c.payload;if(l.requestId===i){if(l.type==="sessionEvents")try{o.enqueue(l.events);}catch{u();}else if(l.type==="error"&&!a){try{o.error(l.message);}catch{}u();}}}),s=async()=>{await this.invokeIpc("stop_rtc_subscription",{requestId:i});};try{await this.invokeIpc("start_rtc_session_subscription",{requestId:i,localDeviceId:n});}catch(c){try{o.error(c);}catch{}await u();}},cancel:async()=>{await u();}})}return this.fallback.subscribeSessions(e)}async getLocalDeviceId(){return this.resolveLocalDeviceId()}async updatePresence(e,t,i=true,n=3e5,r){if(await this.shouldUseTauriSignaling())try{if(!await this.ensureNativeAuth("updatePresence",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for updatePresence");let a=this.resolveNativeSignalingUserId(),u=await this.resolveLocalDeviceId(),o=await this.resolveLocalDeviceName();await this.invokeIpc("update_rtc_presence",{userId:a,deviceName:o,ticket:t,metadata:this.withPresenceMetadata(r,u)});return}catch(s){console.warn("[NativeIpcBridge] update_rtc_presence failed:",s);}return this.fallback.updatePresence(e,t,i,n,r)}startAutoConnect(e,t){(async()=>{try{if(!await this.shouldUseTauriSignaling()){console.error("[NativeIpcBridge] startAutoConnect requires native Rust signaling; IPC unavailable");return}let i=await this.resolveLocalDeviceId()||t;await this.startAutoConnectOnce(e,i);}catch(i){console.warn("[NativeIpcBridge] startAutoConnect failed:",i);}})();}forceReconnectSnapshot(){(async()=>{if(!await this.shouldUseTauriSignaling()){console.error("[NativeIpcBridge] forceReconnectSnapshot requires native Rust signaling; IPC unavailable");return}try{await this.invokeIpc("force_rtc_reconnect_snapshot");}catch(e){console.warn("[NativeIpcBridge] force_rtc_reconnect_snapshot failed:",e);}})();}startPresenceLoop(e,t,i,n,r){(async()=>{try{if(!await this.shouldUseTauriSignaling()){console.warn("[NativeIpcBridge] startPresenceLoop falling back to wasm signaling (Tauri IPC unavailable)"),this.fallback.startPresenceLoop(e,t,i,n,r);return}let s=await this.resolveLocalDeviceId(),a=this.shouldUseResolvedDeviceName(i)?await this.resolveLocalDeviceName():i.trim(),u=this.withPresenceMetadata(r,s);await this.startPresenceLoopOnce(e,t,a,n,u);}catch(s){console.warn("[NativeIpcBridge] startPresenceLoop failed:",s);}})();}async startAutoConnectOnce(e,t){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startAutoConnectOnce().");if(!await this.ensureNativeAuth("startAutoConnect",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startAutoConnect");let n=this.resolveNativeSignalingUserId(e);if(!n)throw new Error("Native auto-connect requires a runtime auth-scoped user id.");await this.invokeIpc("start_rtc_auto_connect",{userId:n,localDeviceId:t});}async startPresenceLoopOnce(e,t,i,n,r){if(!await this.shouldUseTauriSignaling())throw new Error("[pluto-rtc] Native IPC unavailable for startPresenceLoopOnce().");if(console.info("[NativeIpcBridge][presence][start-request]",{userId:e,localNodeId:t,deviceName:i,hasMetadata:typeof r=="string"&&r.trim().length>0,hasCompoundTicket:typeof n=="string"&&n.includes(".")}),!await this.ensureNativeAuth("startPresenceLoop",{requireToken:this.requiresNativeAuthToken(),maxWaitMs:this.nativeAuthWaitMs()}))throw new Error("Native auth token unavailable for startPresenceLoop");let a=this.resolveNativeSignalingUserId(e);if(!a)throw new Error("Native presence loop requires a runtime auth-scoped user id.");console.info("[NativeIpcBridge][presence][auth-ready]",{requestedUserId:e,runtimeUserId:this.currentUser?.id??this.getAuthContext()?.userId??null,effectiveUserId:a,localNodeId:t}),await this.invokeIpc("start_rtc_presence_loop",{userId:a,localNodeId:t,deviceName:i,ticket:n,metadata:r,apiKey:this.options.apiKey??null,spaceKey:this.resolveConfiguredSpaceKey()||null}),console.info("[NativeIpcBridge][presence][ipc-started]",{requestedUserId:e,effectiveUserId:a,localNodeId:t,deviceName:i});}shouldUseResolvedDeviceName(e){let t=e.trim();return t.length===0||t==="Unknown Device"||t==="Desktop Device"}async sendExplicitFilePath(e,t,i=""){if(c("[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("[NativeIpcBridge] sendExplicitFilePath using anonymous native path");let n=await this.invokeIpc("send_file",{connectionId:e,filePath:t,transferId:i});return c("[NativeIpcBridge] sendExplicitFilePath completed",{connectionId:e,transferId:i||null,result:n}),n}return this.fallback.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){c("[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("[NativeIpcBridge] sendExplicitFileData using anonymous native path");let i=e.connectionId||e.connection?.deviceId||e.connection?.remoteNodeId||e.remoteNodeId||"";if(!i)throw new Error("sendExplicitFileData requires a settled peer identifier in native runtime");let n=new Uint8Array(await e.file.arrayBuffer());await this.invokeIpc("send_file_data",{connectionId:i,filename:e.file.name,data:Array.from(n),transferId:e.transferId}),c("[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=>v$1(t)).filter(t=>!!t)}catch(e){return O(e)?c("[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"),v$1(await this.invokeIpc("get_rtc_connection_state",{connectionId:t}))}catch(i){return console.warn("[NativeIpcBridge] Failed to fetch native connection state:",{connectionId:t,error:i}),null}}async onConnectionStateChange(e){let t=false,i=null,n=new Map,r=Date.now(),s=0,a=()=>{let c=i;c&&Promise.resolve(c());},u$1=async()=>{try{let c=await this.getConnectionStates();c.length>0&&(b$1("[NativeIpcBridge] replaying current native connection states",c.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}))),c.forEach(l=>e(l)));}catch(c){console.warn("[NativeIpcBridge] Failed to replay native connection states after event subscription:",c);}},o=async c=>{let l=(n.get(c)??0)+1;n.set(c,l);let g=await this.getConnectionState(c);if(!g||t||n.get(c)!==l)return;if(["closed","failed","disconnected"].includes(String(g.state??"").trim().toLowerCase())){if(await u(v.CONNECTION_TERMINAL_CONFIRMATION_MS),t||n.get(c)!==l)return;g=await this.getConnectionState(c)??g;}!t&&n.get(c)===l&&e(g);};for(;!t&&Date.now()-r<=v.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS;){if(s+=1,!await this.canUseTauriIpc()){await u(this.nextConnectionEventRetryDelayMs(s));continue}return i=await this.listenIpc("connection-state-changed",c=>{let l=v$1(c?.payload);l&&(b$1("[NativeIpcBridge] connection-state-changed trigger",{connectionId:l.connectionId}),o(l.connectionId));}),await u$1(),()=>{t=true,a();}}return ()=>{t=true,a();}}async onIncomingNativeMessage(e){if(!await this.canUseTauriIpc())return ()=>{};let t=await this.listenIpc("iroh://message",i=>{if(i?.payload?.data&&i.payload.streamId==="main")try{let n=new Uint8Array(i.payload.data);if(n.length<2||n[0]!==0)return;let s=n.slice(1),a=new TextDecoder().decode(s),u=JSON.parse(a);e(i.payload.connectionId,i.payload.remoteNodeId??null,u);}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});}};v.AUTH_REQUIRED_WAIT_MS=w.nativeIpc.authRequiredWaitMs,v.DEFAULT_BOUNDED_IPC_TIMEOUT_MS=w.nativeIpc.defaultBoundedCommandTimeoutMs,v.CONNECTION_EVENT_SUBSCRIBE_WINDOW_MS=w.nativeIpc.connectionEventSubscribeWindowMs,v.CONNECTION_EVENT_RETRY_MIN_DELAY_MS=w.nativeIpc.connectionEventRetryMinDelayMs,v.CONNECTION_EVENT_RETRY_MAX_DELAY_MS=w.nativeIpc.connectionEventRetryMaxDelayMs,v.CONNECTION_TERMINAL_CONFIRMATION_MS=1500,v.TAURI_IPC_NEGATIVE_CACHE_MS=w.nativeIpc.tauriIpcNegativeCacheMs,v.NATIVE_STATUS_IPC_TIMEOUT_MS=2500;var D=v;var te=class extends F{constructor(e){let t=T(e.bridge,"IpcRuntimeAdapter");super(new D({...e,ipcBridge:t,allowWasmFallback:e.allowWasmFallback??false}));}};
2
- export{Z as a,X as b,ee as c,q as d,ie as e,O as f,Q as g,te as h};