import { y as ConnectionOptions, z as PayloadCrypto, F as ApplicationPayloadReadinessOptions, H as ApplicationPayloadRouteOptions, c as ProtocolName, J as ApplicationPayloadSendOptions, K as ITransport, O as LatencySnapshot, Q as PeerState, T as PeerScope, U as PeerHealth, V as ChannelDescriptor$1, W as ChannelMetadata, D as Device, w as BackendConnectionState, L as LocalDeviceInfo$1, o as DeviceStatusSnapshot, X as ManagedDeviceConnectOptions, h as ClientOptions, u as SignalingSession, m as RuntimeIdentity, Y as JoinRoomOptions$1, l as RoomMember, Z as DevicePresenceStatus, _ as PeerLifecycleStatus$1, d as PeerSessionSnapshot$1 } from './ITransport-yaruAmx3.js'; type ConnectionHealth = 'unknown' | 'healthy' | 'suspect' | 'stale'; type UpgradeState = 'none' | 'upgrading' | 'upgraded' | 'failed'; declare class Connection { private static readonly textDecoder; private static readonly textEncoder; private static readonly UPGRADE_RETRY_DELAY_MS; private static readonly MAX_UPGRADE_RETRIES; private static readonly UPGRADE_REDRIVE_DELAYS_MS; private static readonly WEBRTC_DISCONNECTED_GRACE_MS; private static readonly MAX_PENDING_MESSAGES; private static readonly DEFAULT_APPLICATION_CRYPTO_WAIT_MS; /** * Must exceed `WEBRTC_ICE_CONNECT_TIMEOUT_MS` in `WebRTCTransport`: the transport * waits that long for ICE + DataChannel before `failed`. A shorter watchdog here * tears the PC down early, burns `MAX_UPGRADE_RETRIES`, and stretches upgrades to ~60s+ under load. */ private static readonly WEBRTC_UPGRADE_ATTEMPT_TIMEOUT_MS; private static readonly MAX_PENDING_ENCRYPTED_APPLICATION_PAYLOADS; private static readonly WEBRTC_APPLICATION_ROUTE_PROOF_TIMEOUT_MS; private static readonly WEBRTC_APPLICATION_ROUTE_PROOF_DELAYS_MS; private static readonly WEBRTC_APPLICATION_ROUTE_PROOF_MAX_ID_LENGTH; private listeners; private pendingMessages; private pendingEncryptedApplicationPayloads; private lastApplicationPayloadTransport; private webrtcBinaryHandlers; private closeListeners; private upgradeStateListeners; private writer; private reader; private _isClosed; get isClosed(): boolean; private receiveBuffer; readonly id: string; readonly remoteNodeId: string; /** @deprecated Compatibility alias for legacy consumers. This is the remote node id, not a device id. */ readonly deviceId: string; readonly localNodeId: string; private options; private writeMutex; private applicationCryptoWaiters; private applicationKeyAgreementObservationEpoch; private nativeSignalSender; private webrtcTransport; private webRtcApplicationRouteReadyTransport; private webRtcApplicationRouteReadyNegotiationId; private upgradeState; private upgradeRequested; private negotiationSwitchCount; private nativeNegotiationSwitchCount; private upgradeAttemptActive; private upgradeRetryCount; private lastBaseTransportGeneration; private lastBaseTransportStableId; private lastNativeSessionAdmissionRecoveryGeneration; private upgradeReDriveCount; private upgradeReDriveTimer; private upgradeRetryTimer; private inboundSignalRetryBypassUsed; private upgradeAttemptTimeoutTimer; private lastReportedTransportStatus; private pendingTransportStatusReport; private transportStatusReportInFlight; private applicationRouteMissingNotified; private upgradeTerminalFailure; private pendingSignals; private activeNegotiationId; private pendingAvailabilityHint; private webrtcHeartbeat; private webRtcHeartbeatProbeInFlight; private webRtcApplicationRouteProbeInFlight; private pendingWebRtcApplicationRouteProof; private webRtcHeartbeatConsecutiveProbeFailures; private irohHealthListeners; private webrtcHealthListeners; private lastWebRtcHeartbeatOkAt; private lastWebRtcDataChannelOpenAt; private lastApplicationRouteReadyReportAt; private static readonly WEBRTC_RENEGOTIATE_LIVENESS_WINDOW_MS; private static readonly MAX_NEGOTIATION_SWITCHES; private static readonly MAX_NATIVE_NEGOTIATION_SWITCHES; private lastForegroundAt; private webRtcDisconnectedGraceTimer; private preferredWebRtcRole; constructor(id: string, localNodeId: string, remoteNodeId: string, writer: WritableStreamDefaultWriter, reader: ReadableStreamDefaultReader, options?: ConnectionOptions); setApplicationCrypto(applicationCrypto: PayloadCrypto | undefined): void; getKeyAgreementEpoch(): number; requireApplicationCrypto(): void; isApplicationCryptoRequired(): boolean; isPayloadReady(options?: ApplicationPayloadReadinessOptions): boolean; payloadTransports(options?: ApplicationPayloadRouteOptions): ProtocolName[]; private isTransportAvailableForApplicationPayload; private resolveApplicationCryptoWaiters; private rejectApplicationCryptoWaiters; private waitForRequiredApplicationCrypto; /** * Starts WebRTC upgrade only when peer capability negotiation allows it. * No-op when WebRTC is not configured or an upgrade already started. */ requestWebRTCUpgrade(reason?: string): void; /** * Whether the current WebRTC route is provably alive: an open data channel * plus either a recent heartbeat round trip or a freshly opened channel. An * `open` readyState alone is not proof — it lingers for many seconds after the * remote vanishes (e.g. a page reload), so a dead-but-`open` channel reports * not-live and can be replaced rather than trusted. */ private isWebRtcRouteHeartbeatLive; requestTransportRecovery(reason: string, options?: { forceRenegotiate?: boolean; replaceExisting?: boolean; }): void; private static readonly FOREGROUND_PROBE_TIMEOUT_MS; handleAppForeground(): void; /** * Accept authoritative Rust proof that a specific physical base generation * is connected. Generic outbound control writes are deliberately insufficient: * WebRTC recovery itself emits control frames, so treating their completion as * fresh availability recursively resets the retry budget during an outage. * This Connection remains the sole optional-route retry owner. */ handleBaseTransportAvailable(source: string, proof: { transportState?: string | null; transportGeneration?: number | null; transportStableId?: number | null; }): void; private beginWebRtcRecovery; getUpgradeState(): UpgradeState; updateRTCConfig(rtcConfig: ConnectionOptions['rtcConfig']): void; onUpgradeStateChange(callback: (state: UpgradeState) => void): void; /** * Best-effort transport diagnostics for developer tooling. * * - `usesRelay=true` means the selected WebRTC candidate pair includes a relay candidate. * - `usesRelay=false` means we found a selected pair and it is direct. * - `usesRelay=null` means there is not enough data yet. */ getTransportDiagnostics(): Promise<{ activeTransport: ProtocolName; parallelTransport: ProtocolName | null; usesRelay: boolean | null; relaySource: string | null; webrtc: { iceConnectionState: string | null; iceGatheringState: string | null; localCandidateType: string | null; remoteCandidateType: string | null; localProtocol: string | null; remoteProtocol: string | null; candidateTypeSummary: string | null; } | null; }>; private collectTransportDiagnostics; private refreshWebRtcCandidatePairObservation; private lastWebRtcLocalCandidateType; private lastWebRtcRemoteCandidateType; private clearWebRtcCandidatePairObservation; private webRtcTransportLabel; get transportType(): ProtocolName; private _peerMoQReady; get peerMoQReady(): boolean; set peerMoQReady(value: boolean); private _remoteSupportsWebRTC; get remoteSupportsWebRTC(): boolean; set remoteSupportsWebRTC(value: boolean); private mediaListeners; /** * Send a message to the other peer. * Messages can be strings or objects (JSON stringified). */ send(message: string | object | ArrayBuffer | Uint8Array, options?: ApplicationPayloadSendOptions): Promise; /** * Send media data (video/audio header + payload) * Internal use for now. */ sendMedia(type: 'audio' | 'video', data: Uint8Array): Promise; /** * Send a data message on a specific transport without fallback. * Throws when the requested transport is unavailable. */ sendOnTransport(transport: ProtocolName, message: string | object | ArrayBuffer | Uint8Array): Promise; /** Last transport that accepted an application payload from this connection. */ lastPayloadTransport(): ProtocolName | null; /** * Send plaintext control traffic that is required to bootstrap application * key agreement. This is intentionally separate from public app-data sends. */ sendControl(message: string | object | ArrayBuffer | Uint8Array): Promise; /** * Write an already-framed payload directly on the underlying iroh control stream. * Used by native-main signaling paths that must preserve protocol framing. */ sendRawIrohFrame(frame: Uint8Array): Promise; /** * Compatibility/diagnostic view of currently usable transports. * * Lifecycle projection and route selection must use getTransportStatus(). * This legacy list intentionally remains for older callers and tests that * need a human-readable inventory, but it is not an authority for active * versus fallback transport state. */ getAvailableTransports(): ProtocolName[]; onWebRTCBinaryMessage(handler: (data: Uint8Array) => boolean): void; private dispatchWebRtcBinaryHandlers; getWebRTCTransport(): ITransport | null; sendOnWebRTC(data: Uint8Array): Promise; private encodePayload; private protectApplicationPayload; private protectRequiredApplicationPayload; private openApplicationPayload; private openUntypedApplicationPayload; private isPlaintextBootstrapPayload; private queueEncryptedApplicationPayload; private flushPendingEncryptedApplicationPayloads; private buildFrame; private sendOverIroh; private sendUsingTransport; private sendTypedOnTransport; private sendTyped; private getSendTransportPriorities; /** * Disconnect the connection */ disconnect(): Promise; /** * Consume an authoritative managed-session denial for the current * capability epoch. This is terminal for the logical connection: optional * routes cannot keep a revoked or rejected session alive. */ handleSessionAdmissionRejected(reason: string): void; /** * Listen for incoming messages */ onMessage(callback: (message: any) => void): void; /** * Listen for incoming media */ onMedia(callback: (type: 'audio' | 'video', data: Uint8Array) => void): void; /** * Listen for disconnection */ onDisconnect(callback: () => void): void; private close; private preserveWebRtcConnectionAfterBaseTransportLoss; private readLoop; injectData(chunk: Uint8Array): void; private handleData; /** * Deliver one independently framed application body to this logical * connection. Fresh `system/peer-default` streams use this entrypoint so * their bytes never interleave with the bootstrap stream's receive buffer. */ receiveFrameBody(body: Uint8Array): void; private tryHandlePlaintextNativeSignal; private static isUntypedDataFrame; private processDataPayload; private isLikelyTextPayload; private emitMedia; private emitMessage; receiveMessage(msg: any): void; receiveDataPayload(messageData: Uint8Array): void; private trackListeners; private warnedSrtpApplicationCryptoBoundary; private warnSrtpApplicationCryptoBoundary; addTrack(track: MediaStreamTrack): RTCRtpSender | null; addTransceiver(trackOrKind: MediaStreamTrack | string, init?: RTCRtpTransceiverInit): RTCRtpTransceiver | null; onTrack(callback: (event: RTCTrackEvent) => void): void; private hasRecoverableBasePath; private hasBaseApplicationRoute; private isWebRtcDataChannelOpen; private clearWebRtcDisconnectedGraceTimer; private transportStillLikelyAlive; private handleUnhealthyWebRtcTransportStateWithGrace; private attemptUpgrade; private setUpgradeState; private handleUpgradeFailure; private scheduleUpgradeReDrive; private clearUpgradeReDriveTimer; private shouldRetryUpgrade; private scheduleUpgradeRetry; private clearUpgradeRetryTimer; private startUpgradeAttemptTimeout; private clearUpgradeAttemptTimeoutTimer; private teardownWebRTCTransport; private startWebRtcHeartbeat; private stopWebRtcHeartbeat; private notifyWebRtcApplicationRouteMissing; private currentWebRtcNegotiationId; private createWebRtcApplicationRouteProofId; private isCurrentWebRtcApplicationRouteProof; private cancelWebRtcApplicationRouteProofForTransport; private cancelWebRtcApplicationRouteProof; private completeWebRtcApplicationRouteProofAck; private sendWebRtcApplicationRouteProofFrame; private tryHandleWebRtcApplicationRouteProofBytes; private tryHandleWebRtcApplicationRouteProofPayload; private isWebRtcApplicationRouteProofFrame; private startWebRtcApplicationRouteProbe; private sendIrohHeartbeatPong; /** Register a listener for WebRTC heartbeat health changes. */ onWebRtcHeartbeatHealth(cb: (health: ConnectionHealth) => void): void; /** Register a listener for iroh heartbeat health changes (WASM path). */ onIrohHeartbeatHealth(cb: (health: ConnectionHealth) => void): void; reportTransportStatusIfChanged(): void; private drainTransportStatusReports; private reportApplicationRouteReady; /** * Single connection-owned transport snapshot for status reporting, * lifecycle projection, and diagnostics. The active route is application * ready; the parallel route is its usable fallback or candidate. */ getTransportStatus(): { activeTransport: ProtocolName; parallelTransport: ProtocolName | null; }; /** Passive RTT samples owned by the active transport heartbeats. */ getLatencySnapshot(): LatencySnapshot; private resolveParallelTransport; setNativeSignalSender(sender: (envelope: any) => Promise): void; /** * Structured connection-lifecycle log. One event per meaningful transition * (upgrade requested/started/failed, route promoted, app route ready, …) with * the connection's current lifecycle snapshot, so the whole connection flow * can be reconstructed from logs. Emits both a human line and a JSON line. */ private traceLifecycle; getControlFrameMode(): NonNullable; /** * Send a control envelope over the native-main signal route. Returns false * (without sending) unless this connection is in `native-main` control-frame * mode and has a native signal sender, so a typed connection never * accidentally routes control through the native sender. */ sendNativeControlEnvelope(envelope: any): Promise; private hasRequiredApplicationCrypto; private clearWebRtcApplicationRouteReady; private isCurrentWebRtcTransportApplicationRouteReady; private isWebRtcApplicationRouteReadyForTransport; /** * Mark the upgraded WebRTC data plane as carrying a proven application route * (data channel open + required crypto present). Idempotent. Promotes the * active transport projection to `webrtc` via reportTransportStatusIfChanged. */ private markWebRtcApplicationRouteReady; /** * True only when the WebRTC transport is upgraded AND its application route * is proven (crypto present). The active route must not advertise `webrtc` * until this holds, so a half-open data channel never looks routable. */ isWebRtcApplicationRouteReady(): boolean; /** * MoQ has a different data-plane shape than WebRTC: it is a shared relay * session on the Client plus a peer capability/subscription bit on this * Connection. Even so, it follows the same lifecycle invariant as every * custom transport: do not advertise it as the active application route until * the local transport is ready, the peer route is enabled, and the required * application crypto is available, and the current relay session has * completed a protected probe/ACK exchange with this peer. */ isMoQApplicationRouteReady(): boolean; private isMoQDataRouteReady; private sendInternalSignal; receiveInternalSignal(content: any): void; private handleInternalSignal; private createNegotiationId; private getDeterministicWebRtcRole; private normalizeNegotiationId; } type AuthContext = { userId: string; token?: string | null; refreshToken?: string | null; customToken?: string | null; tokenProvider?: (forceRefresh?: boolean) => Promise; /** * Supplies the platform attestation token required by the configured * control plane. Firebase-backed hosted deployments use App Check today; * keeping acquisition on the auth context prevents coordination code from * owning a second Firebase app or assuming one global project. */ appCheckTokenProvider?: (forceRefresh?: boolean) => Promise; expiresAtMs?: number | null; }; /** * App-facing options intentionally hide transport node identifiers from callbacks. */ type RuntimeClientOptions = Omit & { onDevices?: (devices: RuntimeDevice[]) => void; onAutoConnect?: (devices: RuntimeDevice[]) => void; onIncomingSession?: (session: RuntimeSession) => Promise; }; /** * App-facing device model. Runtime transport identifiers stay internal. */ type RuntimeDevice = Omit; /** * App-facing session model. Node identifiers are runtime-internal metadata. */ type RuntimeSession = Omit; type RuntimeAuthIdentity = RuntimeIdentity; type RuntimeAuthContext = AuthContext; /** * App-facing peer state model. Runtime transport identifiers stay internal. */ type RuntimePeerState = Omit; type RuntimePeerHealth = PeerHealth; type PeerLifecycleStatus = PeerLifecycleStatus$1; type RuntimePeerScope = PeerScope; /** * App-facing peer session snapshot model. Runtime transport identifiers stay internal. */ type PeerSessionSnapshot = Omit; type LocalDeviceInfo = LocalDeviceInfo$1; type RuntimeRoomMember = RoomMember; type DeviceConnectOptions = ManagedDeviceConnectOptions; type JoinRoomOptions = JoinRoomOptions$1; type ChannelDescriptor = ChannelDescriptor$1; interface ConnectionTarget { ticket: string; timeoutMs?: number; } /** * Durable browser storage used by the optional upstream Iroh docs, blobs, and * gossip protocols. Implementations normally map these atomic operations to * IndexedDB; OpenRTC deliberately does not own a second browser database. */ interface BrowserProtocolStore { loadIdentity(): Promise<{ defaultAuthor: Uint8Array; } | null>; exportSnapshot(): Promise<{ authors: unknown[]; namespaces: unknown[]; entries: unknown[]; }>; importAuthor(authorId: string, author: Uint8Array): Promise; importNamespace(capability: unknown): Promise; deleteNamespace(namespaceId: string): Promise; applyEntry(mutation: unknown): Promise; acknowledgeOutbox(operationId: string): Promise; listBlobManifests(): Promise; getBlobResumeState(contentHash: string): Promise; readBlobRange(contentHash: string, offset: number, length: number): Promise; writeBlobRange(contentHash: string, size: number, chunkBytes: number, offset: number, bytes: Uint8Array): Promise; finalizeBlob(contentHash: string): Promise; readBlobOutboardNode(contentHash: string, nodeId: string): Promise; writeOutboard(contentHash: string, nodeId: string, pair: Uint8Array): Promise; markBlobBaoReady(contentHash: string): Promise; writeStagingChunk(sessionId: string, chunkIndex: number, bytes: Uint8Array): Promise; finalizeBlobStaging(sessionId: string, contentHash: string, size: number, chunkBytes: number): Promise; abortBlobStaging(sessionId: string): Promise; deleteBlob(contentHash: string, force: boolean): Promise; beginBlobImport(contentHash: string, size: number, chunkBytes: number): Promise; writeBlobChunk(contentHash: string, size: number, chunkBytes: number, chunkIndex: number, bytes: Uint8Array): Promise; finalizeBlobImport(contentHash: string, size: number, chunkBytes: number): Promise; flush(): Promise; } interface NamespaceDescriptor { namespaceId: string; capabilityKind: 'read' | 'write'; capability: Uint8Array; } interface IrohMutationReceipt { contentHash: string; operationId: string; } interface IrohDocEntry { namespaceId: string; authorId: string; key: Uint8Array; timestamp: number; contentHash: string; contentLength: number; } interface PeerConnectOptions { deviceId?: string; ticket?: string; scope?: RuntimePeerScope; channelId?: string; /** Total wall-clock budget for dial, admission, and peer settlement. */ timeoutMs?: number; /** * When true, automatic/observer dials fail fast if the peer has a sticky * manual-disconnect projection for this app session. User-initiated manual * reconnects should leave this unset and clear the exclusion explicitly. */ keepManualDisconnect?: boolean; } interface PeerStreamOptions { ticket?: string; scope?: RuntimePeerScope; channelId?: string; timeoutMs?: number; } type ChannelFraming = 'raw' | 'u32be'; interface ScopedChannelOptions { peerId?: string; peerNodeId?: string; deviceId?: string | null; ticket?: string; scope: RuntimePeerScope; channelId: string; timeoutMs?: number; keepManualDisconnect?: boolean; /** * Reuse an application-ready route owned by an active capability and fail * if none exists. Protocol packages use this to open a named channel * without gaining authority to dial, repair, or add an admission avenue. */ existingRouteOnly?: boolean; /** * Native product protocols such as Plutonium drive-view expect a plaintext * stream label before payload frames. OpenRTC owns that handshake here so * apps do not need to choose raw transport APIs. */ nativeLabel?: boolean; framing?: ChannelFraming; } interface ScopedLogicalChannel { channelId: string; peerId: string; connection: Connection; send(payload: Uint8Array): Promise; onMessage(callback: (payload: Uint8Array) => void): () => void; close(): Promise; diagnostics(): { connectionId: string | null; remoteNodeId: string | null; transports: string[]; hasSendOnWebRTC?: boolean; hasWebRTCTransport?: boolean; lastSendTransport?: ProtocolName | 'stream' | null; framing: ChannelFraming; nativeLabel: boolean; delivery: 'reliable' | 'latest-state'; }; } /** * App-facing device status snapshot model. Runtime transport identifiers stay internal. */ type DeviceStatus = Omit; type DevicePresence = DevicePresenceStatus; type IncomingStream = { type: 'bi' | 'uni'; stream: any; remoteNodeId: string; protocolHint?: 'control' | 'explicit' | 'native-main' | 'unknown'; channel?: ChannelMetadata | null; }; type ConnectionEvent = { type: 'connected' | 'disconnected'; connectionId: string; localNodeId: string; remoteNodeId: string; transport: ProtocolName; }; type RawConnection = { connectionId: string; localNodeId: string; remoteNodeId: string; }; type PresenceLoopOptions = { deviceName?: string; ticket?: string; metadata?: string; }; type SessionPlatform = 'native' | 'web'; type SessionKind = 'app-user-device' | 'share-anonymous' | 'drive-grant-guest' | 'scoped-guest' | (string & {}); type AutoConnectPolicy = 'enabled' | 'disabled' | 'scoped-only'; type PresencePolicy = 'online' | 'disabled'; type ConnectionState = BackendConnectionState; type ReadinessOptions = ApplicationPayloadReadinessOptions; type PayloadRouteOptions = ApplicationPayloadRouteOptions; type ConnectionStatus = 'connecting' | 'connected' | 'disconnected' | 'failed'; interface PeerReadiness { requestedId: string; connected: boolean; settledReady: boolean; status: ConnectionStatus; health: RuntimePeerHealth | 'unknown'; deviceId?: string | null; deviceIdHint?: string | null; activeConnectionId?: string | null; readinessState?: string; readinessReason?: string; scopes: string[]; } interface DeviceProfile { deviceId: string | null; deviceName: string; platformType: string; userId: string | null; capabilities: NonNullable; lastSeenAt: string; localNodeId?: string | null; } interface ManagedOptions { platform: SessionPlatform; sessionKind?: SessionKind; scope?: string | null; autoConnectPolicy?: AutoConnectPolicy; presencePolicy?: PresencePolicy; userId?: string | null; deviceName?: string; localDeviceId?: string | null; metadata?: string; autoConnect?: boolean; presence?: boolean; } interface ManagedSession { mode: SessionPlatform; device: DeviceProfile; stop: () => Promise; } export { type AuthContext as A, type BrowserProtocolStore as B, type ChannelDescriptor as C, type DeviceStatus as D, type PeerLifecycleStatus as E, type PeerSessionSnapshot as F, type PresencePolicy as G, type RuntimeAuthContext as H, type IncomingStream as I, type JoinRoomOptions as J, type RuntimePeerScope as K, type LocalDeviceInfo as L, type ManagedOptions as M, type NamespaceDescriptor as N, type SessionKind as O, type PeerConnectOptions as P, type SessionPlatform as Q, type RuntimePeerState as R, type ScopedChannelOptions as S, Connection as a, type PeerReadiness as b, type RuntimePeerHealth as c, type PeerStreamOptions as d, type RuntimeDevice as e, type ScopedLogicalChannel as f, type ConnectionState as g, type ReadinessOptions as h, type ConnectionEvent as i, type ManagedSession as j, type DeviceConnectOptions as k, type DeviceProfile as l, type RawConnection as m, type RuntimeRoomMember as n, type RuntimeClientOptions as o, type IrohMutationReceipt as p, type IrohDocEntry as q, type RuntimeAuthIdentity as r, type RuntimeSession as s, type ConnectionTarget as t, type PresenceLoopOptions as u, type AutoConnectPolicy as v, type ChannelFraming as w, type ConnectionStatus as x, type DevicePresence as y, type PayloadRouteOptions as z };