@signalwire/js 4.0.0-rc.1 → 4.0.0-rc.2

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operators-B8ipd4Xl.cjs","names":["DEFAULT_VIDEO_CONSTRAINTS: MediaTrackConstraints","at?: string","requestId: string","timeoutMs: number","error: unknown","storageType: string","key: string","originalError: Error","description: string","message: string","direction: 'inbound' | 'outbound'","code: number | string","data?: unknown","requestId?: string","originalError: unknown","operation: string","kind: string","media: string","fatal: boolean","action: string","attempt: number","originalError?: unknown","deviceKind: string","phase: string","log","userLogger: SDKLogger | null","logger","debugOptions: DebugOptions","wsTraffic: InternalSDKLogger['wsTraffic']","payload: unknown","value: unknown"],"sources":["../src/core/constants.ts","../src/core/errors.ts","../src/utils/logger.ts","../src/operators/filterNull.ts","../src/utils/getValueFrom.ts","../src/operators/filterEventAs.ts","../src/operators/throwOnRPCError.ts"],"sourcesContent":["export const INVITE_VERSION = 1000;\nexport const DEFAULT_ICE_CANDIDATE_TIMEOUT_MS = 600;\nexport const DEFAULT_ICE_GATHERING_TIMEOUT_MS = 6_000;\nexport const DEFAULT_RECONNECT_CALLS_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes\nexport const DEFAULT_REATTACH_WAIT_TIMEOUT_MS = 10_000; // 10 seconds to wait for server verto.attach\nexport const DEFAULT_CONNECTION_TIMEOUT_MS = 10_000;\nexport const DEFAULT_RECONNECT_DELAY_MIN_MS = 100;\nexport const DEFAULT_RECONNECT_DELAY_MAX_MS = 3000;\nexport const DEFAULT_DEVICE_DEBOUNCE_TIME_MS = 1500;\nexport const DEFAULT_DEVICE_POLLING_INTERVAL_MS = 0; // Disabled by default\nexport const PREFERENCES_STORAGE_KEY = 'sw:preferences';\n\n/** Scope value that enables automatic token refresh. */\nexport const SAT_REFRESH_SCOPE = 'sat:refresh';\n\n/** API endpoints for device token operations. */\nexport const DEVICE_TOKEN_ENDPOINT = '/api/fabric/subscriber/devices/token';\nexport const DEVICE_REFRESH_ENDPOINT = '/api/fabric/subscriber/devices/refresh';\n\n/** Default device token TTL in seconds (15 minutes). */\nexport const DEVICE_TOKEN_DEFAULT_EXPIRE_IN = 900;\n\n/** Buffer time in milliseconds before expiry to trigger refresh. */\nexport const DEVICE_TOKEN_REFRESH_BUFFER_MS = 30_000;\n\n/** Maximum retry attempts for device token refresh on transient failure. */\nexport const DEVICE_TOKEN_REFRESH_MAX_RETRIES = 3;\n\n/** Base delay in milliseconds for exponential backoff on refresh retry. */\nexport const DEVICE_TOKEN_REFRESH_RETRY_BASE_MS = 1000;\n\n/** Maximum retry attempts for developer credential refresh on transient failure. */\nexport const CREDENTIAL_REFRESH_MAX_RETRIES = 5;\n\n/** Base delay in milliseconds for exponential backoff on credential refresh retry. */\nexport const CREDENTIAL_REFRESH_RETRY_BASE_MS = 1000;\n\n/** Maximum delay in milliseconds for credential refresh backoff. */\nexport const CREDENTIAL_REFRESH_MAX_DELAY_MS = 30_000;\n\n/** Buffer in milliseconds before token expiry to trigger refresh. */\nexport const CREDENTIAL_REFRESH_BUFFER_MS = 5000;\n\n/**\n * Maximum time the coordinator will wait for `DeviceTokenManager.activate()`\n * to resolve before treating the activation as failed and falling back to\n * the developer-provided refresh path. Prevents a wedged HTTP layer from\n * leaving the session with no active refresh mechanism.\n */\nexport const CREDENTIAL_ACTIVATE_TIMEOUT_MS = 30_000;\n\n/** JSON-RPC error code for requester validation failure (corrupted auth state). */\nexport const RPC_ERROR_REQUESTER_VALIDATION_FAILED = -32003;\n\n/** JSON-RPC error code for invalid params (e.g., missing authentication block). */\nexport const RPC_ERROR_INVALID_PARAMS = -32602;\n\n/** JSON-RPC error code for authentication failure (invalid token, missing DPoP, etc.). */\nexport const RPC_ERROR_AUTHENTICATION_FAILED = -32002;\n\n/** Error names browsers use for a media permission denial (user or policy). */\nexport const MEDIA_ACCESS_DENIAL_NAMES = [\n 'NotAllowedError',\n 'SecurityError',\n 'PermissionDeniedError'\n];\n\n// =============================================================================\n// STATS MONITORING DEFAULTS (Section 1)\n// =============================================================================\n\n/** Default polling interval for RTCPeerConnection.getStats() in milliseconds. */\nexport const DEFAULT_STATS_POLLING_INTERVAL_MS = 1000;\n\n/** Number of initial samples used to build a baseline for spike detection. */\nexport const DEFAULT_STATS_BASELINE_SAMPLES = 10;\n\n/** Duration in ms with no inbound audio packets before emitting a critical issue. */\nexport const DEFAULT_STATS_NO_PACKET_THRESHOLD_MS = 2000;\n\n/** Multiplier applied to baseline RTT to detect a warning-level RTT spike. */\nexport const DEFAULT_STATS_RTT_SPIKE_MULTIPLIER = 3;\n\n/** Packet loss fraction (0-1) above which a warning is emitted. */\nexport const DEFAULT_STATS_PACKET_LOSS_THRESHOLD = 0.05;\n\n/** Multiplier applied to baseline jitter to detect a jitter spike. */\nexport const DEFAULT_STATS_JITTER_SPIKE_MULTIPLIER = 4;\n\n/** Number of seconds of metrics history to retain. */\nexport const DEFAULT_STATS_HISTORY_SIZE = 30;\n\n// =============================================================================\n// KEYFRAME THROTTLING DEFAULTS (Section 2)\n// =============================================================================\n\n/** Maximum keyframe requests allowed within a single burst window. */\nexport const DEFAULT_KEYFRAME_MAX_BURST = 3;\n\n/** Duration of the keyframe burst window in milliseconds. */\nexport const DEFAULT_KEYFRAME_BURST_WINDOW_MS = 3000;\n\n/** Cooldown period in ms after burst limit is reached before allowing more keyframes. */\nexport const DEFAULT_KEYFRAME_COOLDOWN_MS = 10_000;\n\n// =============================================================================\n// RE-INVITE / ICE RESTART DEFAULTS (Section 2 & 19)\n// =============================================================================\n\n/** Minimum time between re-INVITE attempts in milliseconds. */\nexport const DEFAULT_REINVITE_DEBOUNCE_TIME_MS = 10_000;\n\n/** Maximum number of re-INVITE attempts per call. */\nexport const DEFAULT_REINVITE_MAX_ATTEMPTS = 3;\n\n/** Timeout for a single re-INVITE attempt in milliseconds. */\nexport const DEFAULT_REINVITE_TIMEOUT_MS = 5000;\n\n// =============================================================================\n// RECOVERY PIPELINE DEFAULTS (Section 19)\n// =============================================================================\n\n/** Debounce window in ms to collapse multiple detection signals into one trigger. */\nexport const DEFAULT_RECOVERY_DEBOUNCE_TIME_MS = 2000;\n\n/** Cooldown period in ms between recovery attempts. */\nexport const DEFAULT_RECOVERY_COOLDOWN_MS = 10_000;\n\n/** Grace period in ms before treating ICE 'disconnected' as a failure. */\nexport const DEFAULT_ICE_DISCONNECTED_GRACE_PERIOD_MS = 3000;\n\n/** Timeout for a single ICE restart attempt in milliseconds. */\nexport const DEFAULT_ICE_RESTART_TIMEOUT_MS = 5000;\n\n/** Maximum recovery attempts before emitting 'max_attempts_reached'. */\nexport const DEFAULT_MAX_RECOVERY_ATTEMPTS = 3;\n\n/** Upper bound in ms for waiting on iceGatheringState === 'complete' after an ICE restart. */\nexport const ICE_GATHERING_COMPLETE_TIMEOUT_MS = 10_000;\n\n/** Upper bound in ms for waiting on RTCPeerConnection.connectionState === 'connected' after a recovery ICE restart. */\nexport const PEER_CONNECTION_RECOVERY_WAIT_MS = 5000;\n\n/** Polling interval in ms while waiting for RTCPeerConnection.connectionState to transition. */\nexport const PEER_CONNECTION_RECOVERY_POLL_MS = 100;\n\n// =============================================================================\n// AUDIO PIPELINE (local mic metering / gain / VAD)\n// =============================================================================\n\n/** Polling interval for LocalAudioPipeline.level$ (ms). ~30fps is smooth for meters. */\nexport const AUDIO_LEVEL_POLL_INTERVAL_MS = 33;\n\n/** RMS level threshold (0..1) above which the local participant is considered speaking. */\nexport const VAD_THRESHOLD = 0.03;\n\n/** Hold window in ms below the threshold before speaking$ flips back to false. */\nexport const VAD_HOLD_MS = 250;\n\n// =============================================================================\n// DEVICE MANAGEMENT DEFAULTS (Section 5)\n// =============================================================================\n\n/** Whether to persist device selections to storage by default. */\nexport const DEFAULT_PERSIST_DEVICE_SELECTION = true;\n\n/** Whether to auto-apply device changes to active calls by default. */\nexport const DEFAULT_SYNC_DEVICES_TO_ACTIVE_CALLS = true;\n\n/** Storage keys for persisted device selections. */\nexport const DEVICE_STORAGE_KEY_AUDIO_INPUT = 'sw:device:audioinput';\nexport const DEVICE_STORAGE_KEY_AUDIO_OUTPUT = 'sw:device:audiooutput';\nexport const DEVICE_STORAGE_KEY_VIDEO_INPUT = 'sw:device:videoinput';\n\n/** SDK storage key prefix used for targeted cleanup (factory reset). */\nexport const SDK_STORAGE_KEY_PREFIX = 'sw:';\n\n// =============================================================================\n// VISIBILITY DEFAULTS (Section 4)\n// =============================================================================\n\n/** Whether to auto-mute video when the tab becomes hidden. */\nexport const DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN = false;\n\n/** Whether to re-enumerate devices when the page becomes visible. */\nexport const DEFAULT_REFRESH_DEVICES_ON_VISIBLE = true;\n\n/** Whether to check peer connection health when the page becomes visible. */\nexport const DEFAULT_CHECK_CONNECTION_ON_VISIBLE = true;\n\n// =============================================================================\n// DEGRADATION THRESHOLDS (Section 22)\n// =============================================================================\n\n/** Whether automatic video degradation on low bandwidth is enabled. */\nexport const DEFAULT_ENABLE_AUTO_DEGRADATION = true;\n\n/** Bitrate in kbps below which video is automatically disabled. */\nexport const DEFAULT_DEGRADATION_BITRATE_THRESHOLD_KBPS = 150;\n\n/** Bitrate in kbps above which video is automatically re-enabled (hysteresis). */\nexport const DEFAULT_DEGRADATION_RECOVERY_THRESHOLD_KBPS = 300;\n\n// =============================================================================\n// NETWORK RECOVERY FEATURE FLAGS (Section 19)\n// =============================================================================\n\n/** Whether relay-only escalation is enabled as a last-resort recovery tier. */\nexport const DEFAULT_ENABLE_RELAY_FALLBACK = true;\n\n/** Whether to listen for browser online/offline/connection events. */\nexport const DEFAULT_ENABLE_NETWORK_CHANGE_DETECTION = true;\n\n/** Whether to intercept server-sent media-timeout hangups and attempt recovery. */\nexport const DEFAULT_ENABLE_SERVER_HANGUP_INTERCEPTION = true;\n\n// =============================================================================\n// DEFAULT AUDIO/VIDEO CONSTRAINTS (Section 16.5 & 16.6)\n// =============================================================================\n\n/** Default audio track constraints applied when no explicit constraints are provided. */\nexport const DEFAULT_AUDIO_CONSTRAINTS: MediaTrackConstraints = {\n echoCancellation: true,\n noiseSuppression: true,\n autoGainControl: true\n};\n\n/** Default video track constraints applied when video is enabled without explicit constraints. */\nexport const DEFAULT_VIDEO_CONSTRAINTS: MediaTrackConstraints = {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n aspectRatio: 16 / 9\n};\n\n/** Whether stereo Opus is enabled by default. */\nexport const DEFAULT_STEREO_AUDIO = false;\n\n/** Max average bitrate for stereo Opus in bits per second. */\nexport const DEFAULT_STEREO_MAX_AVERAGE_BITRATE = 510_000;\n\n// =============================================================================\n// QUALITY LEVEL THRESHOLDS (Section 21)\n// =============================================================================\n\n/** MOS score threshold: at or above this is 'excellent'. */\nexport const QUALITY_THRESHOLD_EXCELLENT = 4.0;\n\n/** MOS score threshold: at or above this is 'good'. */\nexport const QUALITY_THRESHOLD_GOOD = 3.5;\n\n/** MOS score threshold: at or above this is 'fair'. */\nexport const QUALITY_THRESHOLD_FAIR = 3.0;\n\n/** MOS score threshold: at or above this is 'poor'. */\nexport const QUALITY_THRESHOLD_POOR = 2.0;\n\n/** MOS score at or below QUALITY_THRESHOLD_POOR is 'critical'. */\n\n// =============================================================================\n// PREFLIGHT DEFAULTS (Section 20)\n// =============================================================================\n\n/** Default duration for the preflight media/bandwidth test in seconds. */\nexport const DEFAULT_PREFLIGHT_DURATION_SEC = 10;\n","import { MEDIA_ACCESS_DENIAL_NAMES } from './constants';\n\nexport class UnexpectedError extends Error {\n constructor(\n public at?: string,\n options?: ErrorOptions\n ) {\n super(`Unexpected Error${at ? ` at ${at}` : ''}`, options);\n this.name = 'UnexpectedError';\n }\n}\n\nexport class UnimplementedError extends Error {\n constructor(\n public reason = 'Not Implemented',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'UnimplementedError';\n }\n}\n\nexport class NotConnectedError extends Error {\n constructor(\n public reason = 'Not Connected',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'NotConnectedError';\n }\n}\n\nexport class InvalidCredentialsError extends Error {\n constructor(\n public reason = 'Invalid Credentials',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'InvalidCredentialsError';\n }\n}\n\nexport class WebSocketConnectionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WebSocketConnectionError';\n }\n}\n\nexport class TransportConnectionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'TransportConnectionError';\n }\n}\n\nexport class WebSocketTimeoutError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WebSocketTimeoutError';\n }\n}\n\nexport class RequestTimeoutError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'RequestTimeoutError';\n }\n}\n\nexport class RequestError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'RequestError';\n }\n}\n\nexport class InvalidListenerError extends Error {\n constructor(options?: ErrorOptions) {\n super('listener is not a function', options);\n this.name = 'InvalidListenerError';\n }\n}\n\nexport class RPCTimeoutError extends Error {\n constructor(\n public requestId: string,\n public timeoutMs: number,\n options?: ErrorOptions\n ) {\n super(`RPC request ${requestId} timed out after ${timeoutMs}ms`, options);\n this.name = 'RPCTimeoutError';\n }\n}\n\nexport class AuthStateHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling authorization state update', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'AuthStateHandlerError';\n }\n}\n\nexport class InvalidStateTransitionError extends Error {\n constructor(\n public currentState: string,\n public targetState: string,\n options?: ErrorOptions\n ) {\n super(\n `Invalid transition: cannot transition from \"${currentState}\" to \"${targetState}\"`,\n options\n );\n this.name = 'InvalidStateTransitionError';\n }\n}\n\nexport class InvalidOptionError extends Error {\n constructor(\n public value: string,\n public availableOptions: string[],\n options?: ErrorOptions\n ) {\n super(\n `Invalid option: \"${value}\" must be one of the available options: ${availableOptions.join(', ')}`,\n options\n );\n this.name = 'InvalidOptionError';\n }\n}\n\nexport class StorageNotAvailableError extends Error {\n constructor(\n public storageType: string = 'localStorage',\n options?: ErrorOptions\n ) {\n super(`${storageType} is not available in this environment`, options);\n this.name = 'StorageNotAvailableError';\n }\n}\n\nexport class SerializationError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to serialize value for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'SerializationError';\n }\n}\n\nexport class DeserializationError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to deserialize value for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'DeserializationError';\n }\n}\n\nexport class StorageWriteError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to write to storage for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'StorageWriteError';\n }\n}\n\nexport class StorageReadError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to read from storage \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'StorageReadError';\n }\n}\n\nexport class InvalidStorageValueError extends Error {\n constructor(\n public key: string,\n public valueType: string,\n options?: ErrorOptions\n ) {\n super(\n `Cannot serialize value of type \"${valueType}\" for key \"${key}\": This type cannot be serialized to JSON`,\n options\n );\n this.name = 'InvalidStorageValueError';\n }\n}\n\nexport class DependencyError extends Error {\n constructor(\n public description: string,\n options?: ErrorOptions\n ) {\n super(`Dependency ${description} is not set or available.`, options);\n this.name = 'DependencyError';\n }\n}\n\nexport class DeviceNotFoundError extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'DeviceNotFoundError';\n }\n}\n\n// =============================================================================\n// CALL ERROR TYPES\n// =============================================================================\n\n/**\n * Semantic category of a call-lifecycle error.\n *\n * - `'media'` – RTCPeerConnection / media device failure\n * - `'signaling'` – Verto / JSON-RPC protocol error\n * - `'timeout'` – Call setup timed out waiting for a response\n * - `'rejected'` – Remote side rejected the call\n * - `'network'` – Transport lost during an active call\n * - `'internal'` – Unexpected / unknown error\n */\nexport type CallErrorKind = 'media' | 'signaling' | 'timeout' | 'rejected' | 'network' | 'internal';\n\n/**\n * Structured error emitted on `call.errors$`.\n *\n * Provides actionable metadata so consumers can react without\n * resorting to `instanceof` checks on raw `Error` objects.\n */\nexport interface CallError {\n /** Semantic category of the error. */\n readonly kind: CallErrorKind;\n /**\n * Whether the error terminates the call.\n * When `true`, the call will automatically transition to `'failed'`\n * and be destroyed — no further action is needed from the consumer.\n */\n readonly fatal: boolean;\n /** The underlying error. */\n readonly error: Error;\n /** ID of the call that produced this error. */\n readonly callId: string;\n}\n\nexport class CallCreateError extends Error {\n constructor(\n public message: string,\n public error: unknown = null,\n public direction: 'inbound' | 'outbound' = 'outbound',\n options?: ErrorOptions\n ) {\n super(message, {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'CallCreateError';\n }\n}\n\nexport class JSONRPCError extends Error {\n constructor(\n public code: number | string,\n message: string,\n public data?: unknown,\n options?: ErrorOptions,\n public requestId?: string\n ) {\n super(message, options);\n this.name = 'JSONRPCError';\n }\n}\n\nexport class InvalidParams extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'InvalidParams';\n }\n}\n\nexport class ConversationError extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'ConversationError';\n }\n}\n\nexport class VertoInviteHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling Verto invite', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'VertoInviteHandlerError';\n }\n}\n\nexport class VertoAttachHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling Verto attach', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'VertoAttachHandlerError';\n }\n}\n\nexport class HttpRequestError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'HttpRequestError';\n }\n}\n\nexport class ValidationError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ValidationError';\n }\n}\n\nexport class VertoPongError extends Error {\n constructor(public originalError: unknown) {\n super('Failed to send Verto pong - call may disconnect', {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'VertoPongError';\n }\n}\n\nexport class MessageParseError extends Error {\n constructor(public originalError: unknown) {\n super('Failed to parse incoming WebSocket message', {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'MessageParseError';\n }\n}\n\nexport class CollectionFetchError extends Error {\n constructor(\n public operation: string,\n public originalError: unknown\n ) {\n super(`Collection fetch failed during ${operation}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'CollectionFetchError';\n }\n}\n\nexport class MediaTrackError extends Error {\n constructor(\n public operation: string,\n public kind: string,\n public originalError: unknown\n ) {\n super(`Media track ${operation} failed for ${kind}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'MediaTrackError';\n }\n}\n\n/** True when a `getUserMedia`/`getDisplayMedia` rejection is a permission denial. */\nfunction isMediaAccessDenial(originalError: unknown): boolean {\n return originalError instanceof Error && MEDIA_ACCESS_DENIAL_NAMES.includes(originalError.name);\n}\n\n/**\n * Failure to acquire local media (camera, microphone, or screen capture)\n * via `getUserMedia`/`getDisplayMedia`.\n *\n * Non-fatal by default: screenshare and additional-device failures never\n * end the call, and main-connection failures degrade to receive-only when\n * possible. The wrapping site sets `fatal` to `true` only when the call\n * cannot continue (receive-only fallback disabled or no receive intent).\n */\nexport class MediaAccessError extends Error {\n constructor(\n /** The SDK operation that failed, e.g. `'acquireLocalMedia'`, `'startScreenShare'`, `'addInputDevice'`. */\n public operation: string,\n /** The media being acquired: `'audio' | 'video' | 'audiovideo' | 'screen'`. */\n public media: string,\n /** The raw `getUserMedia`/`getDisplayMedia` error (typically a `DOMException`). */\n public originalError: unknown,\n /** Whether this failure terminates the call. */\n public readonly fatal: boolean = false\n ) {\n super(\n `Media access ${isMediaAccessDenial(originalError) ? 'denied' : 'failed'} for ${operation} (${media})`,\n {\n cause: originalError instanceof Error ? originalError : undefined\n }\n );\n this.name = 'MediaAccessError';\n }\n\n /** True when the underlying failure is a permission denial (user or policy). */\n get denied(): boolean {\n return isMediaAccessDenial(this.originalError);\n }\n}\n\n// =============================================================================\n// DPOP / CLIENT BOUND SAT ERROR TYPES\n// =============================================================================\n\nexport class DPoPInitError extends Error {\n constructor(\n public originalError: unknown,\n message = 'Failed to initialize DPoP key pair'\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'DPoPInitError';\n }\n}\n\n// =============================================================================\n// RESILIENCE ERROR TYPES\n// =============================================================================\n\n/**\n * Error thrown when a recovery attempt fails.\n *\n * Carries the recovery action and attempt number for diagnostic purposes.\n */\nexport class RecoveryError extends Error {\n constructor(\n public action: string,\n public attempt: number,\n public originalError?: unknown\n ) {\n super(`Recovery failed: ${action} (attempt ${attempt})`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'RecoveryError';\n }\n}\n\n/**\n * Error thrown when getUserMedia fails with OverconstrainedError\n * and all fallback levels have been exhausted.\n */\nexport class OverconstrainedFallbackError extends Error {\n constructor(\n public deviceKind: string,\n public originalError?: unknown\n ) {\n super(`All constraint fallback levels exhausted for ${deviceKind}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'OverconstrainedFallbackError';\n }\n}\n\n/**\n * Error thrown when the preflight connectivity test fails.\n */\nexport class PreflightError extends Error {\n constructor(\n public phase: string,\n public originalError?: unknown\n ) {\n super(`Preflight test failed during ${phase}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'PreflightError';\n }\n}\n\n// =============================================================================\n// DPOP / CLIENT BOUND SAT ERROR TYPES\n// =============================================================================\n\nexport class DeviceTokenError extends Error {\n constructor(\n message: string,\n public originalError?: unknown\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'DeviceTokenError';\n }\n}\n\nexport class TokenRefreshError extends Error {\n constructor(\n message: string,\n public originalError?: unknown\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'TokenRefreshError';\n }\n}\n","import log from 'loglevel';\n\n// =============================================================================\n// Public Interfaces\n// =============================================================================\n\n/** Log level names supported by the SDK. */\nexport type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent';\n\n/**\n * Logger interface that consumers can implement to replace the built-in logger.\n * All methods accept variadic arguments matching the browser console API.\n */\nexport interface SDKLogger {\n error(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n info(...args: unknown[]): void;\n debug(...args: unknown[]): void;\n trace(...args: unknown[]): void;\n}\n\n/** Options for WebSocket traffic logging. */\nexport interface WsTrafficOptions {\n type: 'send' | 'recv' | 'http';\n /** Parsed object or raw string — will be JSON.stringify'd for display if an object. */\n payload: unknown;\n}\n\n/**\n * Options for WebSocket traffic logging using raw strings.\n * The string is only parsed when logging is enabled, avoiding\n * unnecessary JSON.parse on every message.\n */\nexport interface WsTrafficRawOptions {\n type: 'send' | 'recv';\n raw: string;\n}\n\n/** Debug options that control verbose SDK logging. */\nexport interface DebugOptions {\n /** Log all WebSocket send/recv traffic to the console. */\n logWsTraffic?: boolean;\n}\n\n/** Extended logger with SDK-internal helpers (wsTraffic). */\nexport interface InternalSDKLogger extends SDKLogger {\n wsTraffic: (options: WsTrafficOptions | WsTrafficRawOptions) => void;\n}\n\n// =============================================================================\n// Default Logger (loglevel)\n// =============================================================================\n\nconst datetime = () => new Date().toISOString();\nconst defaultLogger = log.getLogger('signalwire');\n\nconst originalFactory = defaultLogger.methodFactory;\ndefaultLogger.methodFactory = (methodName, logLevel, loggerName) => {\n const rawMethod = originalFactory(methodName, logLevel, loggerName);\n\n return function (...args: unknown[]) {\n const prefixed = [datetime(), '-', ...args];\n // eslint-disable-next-line prefer-spread\n rawMethod.apply(undefined, prefixed);\n };\n};\n\n// Default to WARN in production; consumers opt in to verbose logging\nconst defaultLoggerLevel = defaultLogger.levels.WARN;\ndefaultLogger.setLevel(defaultLoggerLevel);\n\n// =============================================================================\n// Logger State\n// =============================================================================\n\nlet userLogger: SDKLogger | null = null;\n\n/** Replace the built-in logger with a custom implementation. Pass `null` to restore defaults. */\nconst setLogger = (logger: SDKLogger | null): void => {\n userLogger = logger;\n};\n\nlet debugOptions: DebugOptions = {};\n\n/** Configure debug options (e.g., `{ logWsTraffic: true }`). */\nconst setDebugOptions = (options: DebugOptions | null): void => {\n if (options == null) {\n debugOptions = {};\n return;\n }\n debugOptions = { ...debugOptions, ...options };\n};\n\n/**\n * Set the log level for the built-in logger.\n * Has no effect when a custom logger is set via `setLogger()`.\n */\nconst setLogLevel = (level: LogLevel): void => {\n defaultLogger.setLevel(level);\n};\n\n// =============================================================================\n// Logger Instance\n// =============================================================================\n\nconst getLoggerInstance = (): SDKLogger => {\n // loglevel's Logger matches SDKLogger (error, warn, info, debug, trace)\n return userLogger ?? (defaultLogger as SDKLogger);\n};\n\nconst shouldStringify = (payload: unknown): boolean => {\n if (payload != null && typeof payload === 'object' && 'method' in payload) {\n return (payload as Record<string, unknown>).method !== 'signalwire.ping';\n }\n return true;\n};\n\nconst wsTraffic: InternalSDKLogger['wsTraffic'] = (options) => {\n const { logWsTraffic } = debugOptions;\n\n if (!logWsTraffic) {\n return;\n }\n\n const loggerInstance = getLoggerInstance();\n\n // Support raw string payloads — parse only when logging is enabled\n let payload: unknown;\n if ('raw' in options) {\n try {\n payload = JSON.parse(options.raw);\n } catch {\n loggerInstance.debug(`[WebSocket] ${options.type.toUpperCase()}: non-JSON message`);\n return;\n }\n } else {\n ({ payload } = options);\n }\n\n const msg = shouldStringify(payload) ? JSON.stringify(payload, null, 2) : payload;\n loggerInstance.debug(`${options.type.toUpperCase()}: \\n`, msg, '\\n');\n};\n\nconst getLogger = (): InternalSDKLogger => {\n const logger = getLoggerInstance();\n\n return new Proxy(logger, {\n get(_target, prop: string | symbol, _receiver) {\n if (prop === 'wsTraffic') {\n return wsTraffic;\n }\n // Always resolve from the current logger instance so that\n // setLogger() takes effect for all existing references.\n const instance = getLoggerInstance();\n const value: unknown = Reflect.get(instance, prop);\n if (typeof value === 'function') {\n return (value as (...args: unknown[]) => unknown).bind(instance);\n }\n return value;\n }\n }) as InternalSDKLogger;\n};\n\nexport { setLogger, getLogger, setDebugOptions, setLogLevel };\n","import { filter } from 'rxjs';\n\nimport type { OperatorFunction } from 'rxjs';\n\n/**\n * RxJS operator that filters out `null` and `undefined` values with type narrowing.\n *\n * @example\n * ```ts\n * source$.pipe(filterNull()).subscribe(value => {\n * // value is guaranteed non-null\n * });\n * ```\n */\nexport function filterNull<T>(): OperatorFunction<T | null | undefined, T> {\n return filter((value): value is T => value != null);\n}\n","export const getValueFrom = <T = unknown>(\n obj: unknown,\n path: string,\n defaultValue?: T\n): T | undefined => {\n const keys = path.split('.');\n let result = obj;\n for (const key of keys) {\n if (result && typeof result === 'object' && key in result) {\n result = (result as Record<string, unknown>)[key];\n } else {\n return defaultValue;\n }\n }\n return (result === undefined ? defaultValue : result) as T;\n};\n","import { pipe } from 'rxjs';\nimport { filter, map } from 'rxjs/operators';\n\nimport { getValueFrom } from '../utils/getValueFrom';\n\nimport type { OperatorFunction } from 'rxjs';\n\n/**\n * Type helper to extract nested property types using dot notation.\n * Supports up to 4 levels of nesting.\n *\n * @example\n * type Example = { a: { b: { c: string } } }\n * type Result = PathValue<Example, 'a.b.c'> // string\n */\ntype PathValue<T, P extends string> = P extends `${infer Key}.${infer Rest}`\n ? Key extends keyof T\n ? PathValue<T[Key], Rest>\n : never\n : P extends keyof T\n ? T[P]\n : never;\n\n// Usage:\n// source$.pipe(\n// isEvent(\n// (event) => event.type === 'call.started',\n// (event) => ({ id: event.id, timestamp: event.timestamp })\n// )\n// );\n\n/**\n * RxJS operator that filters events based on a predicate and maps matching events.\n *\n * This operator combines filter and map operations:\n * 1. Only events that match the predicate are emitted\n * 2. Matching events are transformed using the map function\n *\n * @template TInput - The type of input events\n * @template TOutput - The type of output after mapping\n * @param predicate - Function to test each event. Returns true to include the event.\n * @param mapFn - Function to transform matching events\n * @returns An operator function that filters and maps events\n *\n * @example\n * ```typescript\n * interface CallEvent {\n * type: 'call.started' | 'call.ended';\n * id: string;\n * timestamp: number;\n * }\n *\n * events$.pipe(\n * isEvent(\n * (event: CallEvent) => event.type === 'call.started',\n * (event: CallEvent) => ({ id: event.id, timestamp: event.timestamp })\n * )\n * ).subscribe(startEvent => {\n * console.log('Call started:', startEvent);\n * });\n * ```\n */\nexport function ifIsMap<TInput, TOutput>(\n predicate: (event: unknown) => event is TInput,\n mapFn: (event: TInput) => TOutput\n): OperatorFunction<unknown, TOutput> {\n return pipe(filter(predicate), map(mapFn));\n}\n\n/**\n * Generic RxJS operator that filters events using a type guard and extracts a property.\n *\n * This is the generic version that works with any type, not just JSONRPCRequest.\n * Use this when you need to filter and extract properties from already-narrowed types.\n *\n * **Type inference**: The output type is automatically inferred from the input type and path!\n *\n * @template TInput - The type to narrow to (via type guard)\n * @template TPath - The dot-notation path to extract (inferred from parameter)\n * @param predicate - Type guard function to filter events\n * @param resultPath - Dot-notation path to extract (e.g., 'params', 'params.data')\n * @returns An operator function that filters and extracts\n *\n * @example\n * ```typescript\n * interface EventParams {\n * event_type: string;\n * data: { value: number };\n * }\n *\n * const isAuthEvent = (e: unknown): e is EventParams =>\n * typeof e === 'object' && e !== null && 'event_type' in e;\n *\n * // Type of 'data' is automatically inferred as { value: number }\n * params$.pipe(\n * filterAs(isAuthEvent, 'data')\n * ).subscribe(data => {\n * console.log('Event data:', data.value); // TypeScript knows about .value!\n * });\n *\n * // Deeply nested properties are also inferred\n * params$.pipe(\n * filterAs(isAuthEvent, 'data.value')\n * ).subscribe(value => {\n * console.log(value); // Type is 'number'\n * });\n * ```\n */\nexport function filterAs<TInput, TPath extends string>(\n predicate: (event: unknown) => event is TInput,\n resultPath: TPath\n): OperatorFunction<unknown, PathValue<TInput, TPath>> {\n return pipe(\n ifIsMap(predicate, (event) => {\n const result = getValueFrom<PathValue<TInput, TPath>>(event, resultPath);\n return result;\n }),\n filter((value): value is PathValue<TInput, TPath> => value !== undefined)\n );\n}\n","import { map, type OperatorFunction } from 'rxjs';\n\nimport { JSONRPCError } from '../core/errors';\nimport { getLogger } from '../utils/logger';\n\nimport type { JSONRPCResponse } from '../core/RPCMessages/types/base';\n\nconst logger = getLogger();\n\n/**\n * RxJS operator that throws a {@link JSONRPCError} when the RPC response contains an error.\n * Passes successful responses through unchanged.\n */\nexport function throwOnRPCError<T extends JSONRPCResponse>(): OperatorFunction<T, T> {\n return map((response: T) => {\n if (response.error) {\n logger.error('[throwOnRPCError] RPC error response:', {\n code: response.error.code,\n message: response.error.message,\n data: response.error.data\n });\n\n throw new JSONRPCError(response.error.code, response.error.message, response.error.data);\n }\n logger.debug('[throwOnRPCError] RPC successful response:', response);\n return response;\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAa,iBAAiB;AAC9B,MAAa,mCAAmC;AAChD,MAAa,mCAAmC;AAChD,MAAa,qCAAqC,MAAS;AAE3D,MAAa,gCAAgC;AAC7C,MAAa,iCAAiC;AAC9C,MAAa,iCAAiC;AAC9C,MAAa,kCAAkC;AAC/C,MAAa,qCAAqC;AAClD,MAAa,0BAA0B;;AAGvC,MAAa,oBAAoB;;AAGjC,MAAa,wBAAwB;AACrC,MAAa,0BAA0B;;AAGvC,MAAa,iCAAiC;;AAG9C,MAAa,iCAAiC;;AAG9C,MAAa,mCAAmC;;AAGhD,MAAa,qCAAqC;;AAGlD,MAAa,iCAAiC;;AAG9C,MAAa,mCAAmC;;AAGhD,MAAa,kCAAkC;;AAG/C,MAAa,+BAA+B;;;;;;;AAQ5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AY,UAAU;AAE5B,SADe,aAAuC,OAAO,WAAW;GAExE,8BACM,UAA6C,UAAU,OAAU,CAC1E;;;;;AC/GH,MAAM,SAAS,WAAW;;;;;AAM1B,SAAgB,kBAAqE;AACnF,uBAAY,aAAgB;AAC1B,MAAI,SAAS,OAAO;AAClB,UAAO,MAAM,yCAAyC;IACpD,MAAM,SAAS,MAAM;IACrB,SAAS,SAAS,MAAM;IACxB,MAAM,SAAS,MAAM;IACtB,CAAC;AAEF,SAAM,IAAI,aAAa,SAAS,MAAM,MAAM,SAAS,MAAM,SAAS,SAAS,MAAM,KAAK;;AAE1F,SAAO,MAAM,8CAA8C,SAAS;AACpE,SAAO;GACP"}
@@ -2,6 +2,143 @@ import { filter, map, pipe } from "rxjs";
2
2
  import log from "loglevel";
3
3
  import { filter as filter$1, map as map$1 } from "rxjs/operators";
4
4
 
5
+ //#region src/core/constants.ts
6
+ const INVITE_VERSION = 1e3;
7
+ const DEFAULT_ICE_CANDIDATE_TIMEOUT_MS = 600;
8
+ const DEFAULT_ICE_GATHERING_TIMEOUT_MS = 6e3;
9
+ const DEFAULT_RECONNECT_CALLS_TIMEOUT_MS = 300 * 1e3;
10
+ const DEFAULT_CONNECTION_TIMEOUT_MS = 1e4;
11
+ const DEFAULT_RECONNECT_DELAY_MIN_MS = 100;
12
+ const DEFAULT_RECONNECT_DELAY_MAX_MS = 3e3;
13
+ const DEFAULT_DEVICE_DEBOUNCE_TIME_MS = 1500;
14
+ const DEFAULT_DEVICE_POLLING_INTERVAL_MS = 0;
15
+ const PREFERENCES_STORAGE_KEY = "sw:preferences";
16
+ /** Scope value that enables automatic token refresh. */
17
+ const SAT_REFRESH_SCOPE = "sat:refresh";
18
+ /** API endpoints for device token operations. */
19
+ const DEVICE_TOKEN_ENDPOINT = "/api/fabric/subscriber/devices/token";
20
+ const DEVICE_REFRESH_ENDPOINT = "/api/fabric/subscriber/devices/refresh";
21
+ /** Default device token TTL in seconds (15 minutes). */
22
+ const DEVICE_TOKEN_DEFAULT_EXPIRE_IN = 900;
23
+ /** Buffer time in milliseconds before expiry to trigger refresh. */
24
+ const DEVICE_TOKEN_REFRESH_BUFFER_MS = 3e4;
25
+ /** Maximum retry attempts for device token refresh on transient failure. */
26
+ const DEVICE_TOKEN_REFRESH_MAX_RETRIES = 3;
27
+ /** Base delay in milliseconds for exponential backoff on refresh retry. */
28
+ const DEVICE_TOKEN_REFRESH_RETRY_BASE_MS = 1e3;
29
+ /** Maximum retry attempts for developer credential refresh on transient failure. */
30
+ const CREDENTIAL_REFRESH_MAX_RETRIES = 5;
31
+ /** Base delay in milliseconds for exponential backoff on credential refresh retry. */
32
+ const CREDENTIAL_REFRESH_RETRY_BASE_MS = 1e3;
33
+ /** Maximum delay in milliseconds for credential refresh backoff. */
34
+ const CREDENTIAL_REFRESH_MAX_DELAY_MS = 3e4;
35
+ /** Buffer in milliseconds before token expiry to trigger refresh. */
36
+ const CREDENTIAL_REFRESH_BUFFER_MS = 5e3;
37
+ /**
38
+ * Maximum time the coordinator will wait for `DeviceTokenManager.activate()`
39
+ * to resolve before treating the activation as failed and falling back to
40
+ * the developer-provided refresh path. Prevents a wedged HTTP layer from
41
+ * leaving the session with no active refresh mechanism.
42
+ */
43
+ const CREDENTIAL_ACTIVATE_TIMEOUT_MS = 3e4;
44
+ /** JSON-RPC error code for requester validation failure (corrupted auth state). */
45
+ const RPC_ERROR_REQUESTER_VALIDATION_FAILED = -32003;
46
+ /** JSON-RPC error code for invalid params (e.g., missing authentication block). */
47
+ const RPC_ERROR_INVALID_PARAMS = -32602;
48
+ /** JSON-RPC error code for authentication failure (invalid token, missing DPoP, etc.). */
49
+ const RPC_ERROR_AUTHENTICATION_FAILED = -32002;
50
+ /** Error names browsers use for a media permission denial (user or policy). */
51
+ const MEDIA_ACCESS_DENIAL_NAMES = [
52
+ "NotAllowedError",
53
+ "SecurityError",
54
+ "PermissionDeniedError"
55
+ ];
56
+ /** Default polling interval for RTCPeerConnection.getStats() in milliseconds. */
57
+ const DEFAULT_STATS_POLLING_INTERVAL_MS = 1e3;
58
+ /** Number of initial samples used to build a baseline for spike detection. */
59
+ const DEFAULT_STATS_BASELINE_SAMPLES = 10;
60
+ /** Duration in ms with no inbound audio packets before emitting a critical issue. */
61
+ const DEFAULT_STATS_NO_PACKET_THRESHOLD_MS = 2e3;
62
+ /** Multiplier applied to baseline RTT to detect a warning-level RTT spike. */
63
+ const DEFAULT_STATS_RTT_SPIKE_MULTIPLIER = 3;
64
+ /** Packet loss fraction (0-1) above which a warning is emitted. */
65
+ const DEFAULT_STATS_PACKET_LOSS_THRESHOLD = .05;
66
+ /** Multiplier applied to baseline jitter to detect a jitter spike. */
67
+ const DEFAULT_STATS_JITTER_SPIKE_MULTIPLIER = 4;
68
+ /** Number of seconds of metrics history to retain. */
69
+ const DEFAULT_STATS_HISTORY_SIZE = 30;
70
+ /** Maximum keyframe requests allowed within a single burst window. */
71
+ const DEFAULT_KEYFRAME_MAX_BURST = 3;
72
+ /** Duration of the keyframe burst window in milliseconds. */
73
+ const DEFAULT_KEYFRAME_BURST_WINDOW_MS = 3e3;
74
+ /** Cooldown period in ms after burst limit is reached before allowing more keyframes. */
75
+ const DEFAULT_KEYFRAME_COOLDOWN_MS = 1e4;
76
+ /** Minimum time between re-INVITE attempts in milliseconds. */
77
+ const DEFAULT_REINVITE_DEBOUNCE_TIME_MS = 1e4;
78
+ /** Maximum number of re-INVITE attempts per call. */
79
+ const DEFAULT_REINVITE_MAX_ATTEMPTS = 3;
80
+ /** Timeout for a single re-INVITE attempt in milliseconds. */
81
+ const DEFAULT_REINVITE_TIMEOUT_MS = 5e3;
82
+ /** Debounce window in ms to collapse multiple detection signals into one trigger. */
83
+ const DEFAULT_RECOVERY_DEBOUNCE_TIME_MS = 2e3;
84
+ /** Cooldown period in ms between recovery attempts. */
85
+ const DEFAULT_RECOVERY_COOLDOWN_MS = 1e4;
86
+ /** Grace period in ms before treating ICE 'disconnected' as a failure. */
87
+ const DEFAULT_ICE_DISCONNECTED_GRACE_PERIOD_MS = 3e3;
88
+ /** Timeout for a single ICE restart attempt in milliseconds. */
89
+ const DEFAULT_ICE_RESTART_TIMEOUT_MS = 5e3;
90
+ /** Maximum recovery attempts before emitting 'max_attempts_reached'. */
91
+ const DEFAULT_MAX_RECOVERY_ATTEMPTS = 3;
92
+ /** Upper bound in ms for waiting on iceGatheringState === 'complete' after an ICE restart. */
93
+ const ICE_GATHERING_COMPLETE_TIMEOUT_MS = 1e4;
94
+ /** Upper bound in ms for waiting on RTCPeerConnection.connectionState === 'connected' after a recovery ICE restart. */
95
+ const PEER_CONNECTION_RECOVERY_WAIT_MS = 5e3;
96
+ /** Polling interval in ms while waiting for RTCPeerConnection.connectionState to transition. */
97
+ const PEER_CONNECTION_RECOVERY_POLL_MS = 100;
98
+ /** Polling interval for LocalAudioPipeline.level$ (ms). ~30fps is smooth for meters. */
99
+ const AUDIO_LEVEL_POLL_INTERVAL_MS = 33;
100
+ /** RMS level threshold (0..1) above which the local participant is considered speaking. */
101
+ const VAD_THRESHOLD = .03;
102
+ /** Hold window in ms below the threshold before speaking$ flips back to false. */
103
+ const VAD_HOLD_MS = 250;
104
+ /** Whether to persist device selections to storage by default. */
105
+ const DEFAULT_PERSIST_DEVICE_SELECTION = true;
106
+ /** Whether to auto-apply device changes to active calls by default. */
107
+ const DEFAULT_SYNC_DEVICES_TO_ACTIVE_CALLS = true;
108
+ /** Storage keys for persisted device selections. */
109
+ const DEVICE_STORAGE_KEY_AUDIO_INPUT = "sw:device:audioinput";
110
+ const DEVICE_STORAGE_KEY_AUDIO_OUTPUT = "sw:device:audiooutput";
111
+ const DEVICE_STORAGE_KEY_VIDEO_INPUT = "sw:device:videoinput";
112
+ /** Whether to auto-mute video when the tab becomes hidden. */
113
+ const DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN = false;
114
+ /** Whether to re-enumerate devices when the page becomes visible. */
115
+ const DEFAULT_REFRESH_DEVICES_ON_VISIBLE = true;
116
+ /** Whether to check peer connection health when the page becomes visible. */
117
+ const DEFAULT_CHECK_CONNECTION_ON_VISIBLE = true;
118
+ /** Whether automatic video degradation on low bandwidth is enabled. */
119
+ const DEFAULT_ENABLE_AUTO_DEGRADATION = true;
120
+ /** Bitrate in kbps below which video is automatically disabled. */
121
+ const DEFAULT_DEGRADATION_BITRATE_THRESHOLD_KBPS = 150;
122
+ /** Bitrate in kbps above which video is automatically re-enabled (hysteresis). */
123
+ const DEFAULT_DEGRADATION_RECOVERY_THRESHOLD_KBPS = 300;
124
+ /** Whether relay-only escalation is enabled as a last-resort recovery tier. */
125
+ const DEFAULT_ENABLE_RELAY_FALLBACK = true;
126
+ /** Whether to listen for browser online/offline/connection events. */
127
+ const DEFAULT_ENABLE_NETWORK_CHANGE_DETECTION = true;
128
+ /** Whether to intercept server-sent media-timeout hangups and attempt recovery. */
129
+ const DEFAULT_ENABLE_SERVER_HANGUP_INTERCEPTION = true;
130
+ /** Default video track constraints applied when video is enabled without explicit constraints. */
131
+ const DEFAULT_VIDEO_CONSTRAINTS = {
132
+ width: { ideal: 1280 },
133
+ height: { ideal: 720 },
134
+ aspectRatio: 16 / 9
135
+ };
136
+ /** Whether stereo Opus is enabled by default. */
137
+ const DEFAULT_STEREO_AUDIO = false;
138
+ /** Max average bitrate for stereo Opus in bits per second. */
139
+ const DEFAULT_STEREO_MAX_AVERAGE_BITRATE = 51e4;
140
+
141
+ //#endregion
5
142
  //#region src/core/errors.ts
6
143
  var UnexpectedError = class extends Error {
7
144
  constructor(at, options) {
@@ -210,6 +347,33 @@ var MediaTrackError = class extends Error {
210
347
  this.name = "MediaTrackError";
211
348
  }
212
349
  };
350
+ /** True when a `getUserMedia`/`getDisplayMedia` rejection is a permission denial. */
351
+ function isMediaAccessDenial(originalError) {
352
+ return originalError instanceof Error && MEDIA_ACCESS_DENIAL_NAMES.includes(originalError.name);
353
+ }
354
+ /**
355
+ * Failure to acquire local media (camera, microphone, or screen capture)
356
+ * via `getUserMedia`/`getDisplayMedia`.
357
+ *
358
+ * Non-fatal by default: screenshare and additional-device failures never
359
+ * end the call, and main-connection failures degrade to receive-only when
360
+ * possible. The wrapping site sets `fatal` to `true` only when the call
361
+ * cannot continue (receive-only fallback disabled or no receive intent).
362
+ */
363
+ var MediaAccessError = class extends Error {
364
+ constructor(operation, media, originalError, fatal = false) {
365
+ super(`Media access ${isMediaAccessDenial(originalError) ? "denied" : "failed"} for ${operation} (${media})`, { cause: originalError instanceof Error ? originalError : void 0 });
366
+ this.operation = operation;
367
+ this.media = media;
368
+ this.originalError = originalError;
369
+ this.fatal = fatal;
370
+ this.name = "MediaAccessError";
371
+ }
372
+ /** True when the underlying failure is a permission denial (user or policy). */
373
+ get denied() {
374
+ return isMediaAccessDenial(this.originalError);
375
+ }
376
+ };
213
377
  var DPoPInitError = class extends Error {
214
378
  constructor(originalError, message = "Failed to initialize DPoP key pair") {
215
379
  super(message, { cause: originalError instanceof Error ? originalError : void 0 });
@@ -474,5 +638,5 @@ function throwOnRPCError() {
474
638
  }
475
639
 
476
640
  //#endregion
477
- export { StorageNotAvailableError as A, VertoPongError as B, OverconstrainedFallbackError as C, RequestError as D, RecoveryError as E, UnexpectedError as F, WebSocketTimeoutError as H, UnimplementedError as I, ValidationError as L, StorageWriteError as M, TokenRefreshError as N, RequestTimeoutError as O, TransportConnectionError as P, VertoAttachHandlerError as R, MessageParseError as S, RPCTimeoutError as T, WebSocketConnectionError as V, DeviceTokenError as _, filterNull as a, JSONRPCError as b, setLogLevel as c, CallCreateError as d, CollectionFetchError as f, DeserializationError as g, DependencyError as h, getValueFrom as i, StorageReadError as j, SerializationError as k, setLogger as l, DPoPInitError as m, filterAs as n, getLogger as o, ConversationError as p, ifIsMap as r, setDebugOptions as s, throwOnRPCError as t, AuthStateHandlerError as u, InvalidCredentialsError as v, PreflightError as w, MediaTrackError as x, InvalidParams as y, VertoInviteHandlerError as z };
478
- //# sourceMappingURL=operators-CX_lCCJm.mjs.map
641
+ export { DEFAULT_DEGRADATION_BITRATE_THRESHOLD_KBPS as $, VAD_HOLD_MS as $t, SerializationError as A, DEFAULT_STATS_POLLING_INTERVAL_MS as At, VertoInviteHandlerError as B, DEVICE_TOKEN_ENDPOINT as Bt, MessageParseError as C, DEFAULT_REINVITE_MAX_ATTEMPTS as Ct, RecoveryError as D, DEFAULT_STATS_JITTER_SPIKE_MULTIPLIER as Dt, RPCTimeoutError as E, DEFAULT_STATS_HISTORY_SIZE as Et, TransportConnectionError as F, DEVICE_REFRESH_ENDPOINT as Ft, CREDENTIAL_ACTIVATE_TIMEOUT_MS as G, INVITE_VERSION as Gt, WebSocketConnectionError as H, DEVICE_TOKEN_REFRESH_MAX_RETRIES as Ht, UnexpectedError as I, DEVICE_STORAGE_KEY_AUDIO_INPUT as It, CREDENTIAL_REFRESH_MAX_RETRIES as J, PREFERENCES_STORAGE_KEY as Jt, CREDENTIAL_REFRESH_BUFFER_MS as K, PEER_CONNECTION_RECOVERY_POLL_MS as Kt, UnimplementedError as L, DEVICE_STORAGE_KEY_AUDIO_OUTPUT as Lt, StorageReadError as M, DEFAULT_STEREO_AUDIO as Mt, StorageWriteError as N, DEFAULT_STEREO_MAX_AVERAGE_BITRATE as Nt, RequestError as O, DEFAULT_STATS_NO_PACKET_THRESHOLD_MS as Ot, TokenRefreshError as P, DEFAULT_SYNC_DEVICES_TO_ACTIVE_CALLS as Pt, DEFAULT_CONNECTION_TIMEOUT_MS as Q, SAT_REFRESH_SCOPE as Qt, ValidationError as R, DEVICE_STORAGE_KEY_VIDEO_INPUT as Rt, MediaTrackError as S, DEFAULT_REINVITE_DEBOUNCE_TIME_MS as St, PreflightError as T, DEFAULT_STATS_BASELINE_SAMPLES as Tt, WebSocketTimeoutError as U, DEVICE_TOKEN_REFRESH_RETRY_BASE_MS as Ut, VertoPongError as V, DEVICE_TOKEN_REFRESH_BUFFER_MS as Vt, AUDIO_LEVEL_POLL_INTERVAL_MS as W, ICE_GATHERING_COMPLETE_TIMEOUT_MS as Wt, DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN as X, RPC_ERROR_INVALID_PARAMS as Xt, CREDENTIAL_REFRESH_RETRY_BASE_MS as Y, RPC_ERROR_AUTHENTICATION_FAILED as Yt, DEFAULT_CHECK_CONNECTION_ON_VISIBLE as Z, RPC_ERROR_REQUESTER_VALIDATION_FAILED as Zt, DeviceTokenError as _, DEFAULT_RECONNECT_DELAY_MAX_MS as _t, filterNull as a, DEFAULT_ENABLE_RELAY_FALLBACK as at, JSONRPCError as b, DEFAULT_RECOVERY_DEBOUNCE_TIME_MS as bt, setLogLevel as c, DEFAULT_ICE_DISCONNECTED_GRACE_PERIOD_MS as ct, CallCreateError as d, DEFAULT_KEYFRAME_BURST_WINDOW_MS as dt, VAD_THRESHOLD as en, DEFAULT_DEGRADATION_RECOVERY_THRESHOLD_KBPS as et, CollectionFetchError as f, DEFAULT_KEYFRAME_COOLDOWN_MS as ft, DeserializationError as g, DEFAULT_RECONNECT_CALLS_TIMEOUT_MS as gt, DependencyError as h, DEFAULT_PERSIST_DEVICE_SELECTION as ht, getValueFrom as i, DEFAULT_ENABLE_NETWORK_CHANGE_DETECTION as it, StorageNotAvailableError as j, DEFAULT_STATS_RTT_SPIKE_MULTIPLIER as jt, RequestTimeoutError as k, DEFAULT_STATS_PACKET_LOSS_THRESHOLD as kt, setLogger as l, DEFAULT_ICE_GATHERING_TIMEOUT_MS as lt, DPoPInitError as m, DEFAULT_MAX_RECOVERY_ATTEMPTS as mt, filterAs as n, DEFAULT_DEVICE_POLLING_INTERVAL_MS as nt, getLogger as o, DEFAULT_ENABLE_SERVER_HANGUP_INTERCEPTION as ot, ConversationError as p, DEFAULT_KEYFRAME_MAX_BURST as pt, CREDENTIAL_REFRESH_MAX_DELAY_MS as q, PEER_CONNECTION_RECOVERY_WAIT_MS as qt, ifIsMap as r, DEFAULT_ENABLE_AUTO_DEGRADATION as rt, setDebugOptions as s, DEFAULT_ICE_CANDIDATE_TIMEOUT_MS as st, throwOnRPCError as t, DEFAULT_DEVICE_DEBOUNCE_TIME_MS as tt, AuthStateHandlerError as u, DEFAULT_ICE_RESTART_TIMEOUT_MS as ut, InvalidCredentialsError as v, DEFAULT_RECONNECT_DELAY_MIN_MS as vt, OverconstrainedFallbackError as w, DEFAULT_REINVITE_TIMEOUT_MS as wt, MediaAccessError as x, DEFAULT_REFRESH_DEVICES_ON_VISIBLE as xt, InvalidParams as y, DEFAULT_RECOVERY_COOLDOWN_MS as yt, VertoAttachHandlerError as z, DEVICE_TOKEN_DEFAULT_EXPIRE_IN as zt };
642
+ //# sourceMappingURL=operators-BlUtq-t0.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"operators-BlUtq-t0.mjs","names":["DEFAULT_VIDEO_CONSTRAINTS: MediaTrackConstraints","at?: string","requestId: string","timeoutMs: number","error: unknown","storageType: string","key: string","originalError: Error","description: string","message: string","direction: 'inbound' | 'outbound'","code: number | string","data?: unknown","requestId?: string","originalError: unknown","operation: string","kind: string","media: string","fatal: boolean","action: string","attempt: number","originalError?: unknown","deviceKind: string","phase: string","userLogger: SDKLogger | null","logger","debugOptions: DebugOptions","wsTraffic: InternalSDKLogger['wsTraffic']","payload: unknown","value: unknown","filter","map"],"sources":["../src/core/constants.ts","../src/core/errors.ts","../src/utils/logger.ts","../src/operators/filterNull.ts","../src/utils/getValueFrom.ts","../src/operators/filterEventAs.ts","../src/operators/throwOnRPCError.ts"],"sourcesContent":["export const INVITE_VERSION = 1000;\nexport const DEFAULT_ICE_CANDIDATE_TIMEOUT_MS = 600;\nexport const DEFAULT_ICE_GATHERING_TIMEOUT_MS = 6_000;\nexport const DEFAULT_RECONNECT_CALLS_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes\nexport const DEFAULT_REATTACH_WAIT_TIMEOUT_MS = 10_000; // 10 seconds to wait for server verto.attach\nexport const DEFAULT_CONNECTION_TIMEOUT_MS = 10_000;\nexport const DEFAULT_RECONNECT_DELAY_MIN_MS = 100;\nexport const DEFAULT_RECONNECT_DELAY_MAX_MS = 3000;\nexport const DEFAULT_DEVICE_DEBOUNCE_TIME_MS = 1500;\nexport const DEFAULT_DEVICE_POLLING_INTERVAL_MS = 0; // Disabled by default\nexport const PREFERENCES_STORAGE_KEY = 'sw:preferences';\n\n/** Scope value that enables automatic token refresh. */\nexport const SAT_REFRESH_SCOPE = 'sat:refresh';\n\n/** API endpoints for device token operations. */\nexport const DEVICE_TOKEN_ENDPOINT = '/api/fabric/subscriber/devices/token';\nexport const DEVICE_REFRESH_ENDPOINT = '/api/fabric/subscriber/devices/refresh';\n\n/** Default device token TTL in seconds (15 minutes). */\nexport const DEVICE_TOKEN_DEFAULT_EXPIRE_IN = 900;\n\n/** Buffer time in milliseconds before expiry to trigger refresh. */\nexport const DEVICE_TOKEN_REFRESH_BUFFER_MS = 30_000;\n\n/** Maximum retry attempts for device token refresh on transient failure. */\nexport const DEVICE_TOKEN_REFRESH_MAX_RETRIES = 3;\n\n/** Base delay in milliseconds for exponential backoff on refresh retry. */\nexport const DEVICE_TOKEN_REFRESH_RETRY_BASE_MS = 1000;\n\n/** Maximum retry attempts for developer credential refresh on transient failure. */\nexport const CREDENTIAL_REFRESH_MAX_RETRIES = 5;\n\n/** Base delay in milliseconds for exponential backoff on credential refresh retry. */\nexport const CREDENTIAL_REFRESH_RETRY_BASE_MS = 1000;\n\n/** Maximum delay in milliseconds for credential refresh backoff. */\nexport const CREDENTIAL_REFRESH_MAX_DELAY_MS = 30_000;\n\n/** Buffer in milliseconds before token expiry to trigger refresh. */\nexport const CREDENTIAL_REFRESH_BUFFER_MS = 5000;\n\n/**\n * Maximum time the coordinator will wait for `DeviceTokenManager.activate()`\n * to resolve before treating the activation as failed and falling back to\n * the developer-provided refresh path. Prevents a wedged HTTP layer from\n * leaving the session with no active refresh mechanism.\n */\nexport const CREDENTIAL_ACTIVATE_TIMEOUT_MS = 30_000;\n\n/** JSON-RPC error code for requester validation failure (corrupted auth state). */\nexport const RPC_ERROR_REQUESTER_VALIDATION_FAILED = -32003;\n\n/** JSON-RPC error code for invalid params (e.g., missing authentication block). */\nexport const RPC_ERROR_INVALID_PARAMS = -32602;\n\n/** JSON-RPC error code for authentication failure (invalid token, missing DPoP, etc.). */\nexport const RPC_ERROR_AUTHENTICATION_FAILED = -32002;\n\n/** Error names browsers use for a media permission denial (user or policy). */\nexport const MEDIA_ACCESS_DENIAL_NAMES = [\n 'NotAllowedError',\n 'SecurityError',\n 'PermissionDeniedError'\n];\n\n// =============================================================================\n// STATS MONITORING DEFAULTS (Section 1)\n// =============================================================================\n\n/** Default polling interval for RTCPeerConnection.getStats() in milliseconds. */\nexport const DEFAULT_STATS_POLLING_INTERVAL_MS = 1000;\n\n/** Number of initial samples used to build a baseline for spike detection. */\nexport const DEFAULT_STATS_BASELINE_SAMPLES = 10;\n\n/** Duration in ms with no inbound audio packets before emitting a critical issue. */\nexport const DEFAULT_STATS_NO_PACKET_THRESHOLD_MS = 2000;\n\n/** Multiplier applied to baseline RTT to detect a warning-level RTT spike. */\nexport const DEFAULT_STATS_RTT_SPIKE_MULTIPLIER = 3;\n\n/** Packet loss fraction (0-1) above which a warning is emitted. */\nexport const DEFAULT_STATS_PACKET_LOSS_THRESHOLD = 0.05;\n\n/** Multiplier applied to baseline jitter to detect a jitter spike. */\nexport const DEFAULT_STATS_JITTER_SPIKE_MULTIPLIER = 4;\n\n/** Number of seconds of metrics history to retain. */\nexport const DEFAULT_STATS_HISTORY_SIZE = 30;\n\n// =============================================================================\n// KEYFRAME THROTTLING DEFAULTS (Section 2)\n// =============================================================================\n\n/** Maximum keyframe requests allowed within a single burst window. */\nexport const DEFAULT_KEYFRAME_MAX_BURST = 3;\n\n/** Duration of the keyframe burst window in milliseconds. */\nexport const DEFAULT_KEYFRAME_BURST_WINDOW_MS = 3000;\n\n/** Cooldown period in ms after burst limit is reached before allowing more keyframes. */\nexport const DEFAULT_KEYFRAME_COOLDOWN_MS = 10_000;\n\n// =============================================================================\n// RE-INVITE / ICE RESTART DEFAULTS (Section 2 & 19)\n// =============================================================================\n\n/** Minimum time between re-INVITE attempts in milliseconds. */\nexport const DEFAULT_REINVITE_DEBOUNCE_TIME_MS = 10_000;\n\n/** Maximum number of re-INVITE attempts per call. */\nexport const DEFAULT_REINVITE_MAX_ATTEMPTS = 3;\n\n/** Timeout for a single re-INVITE attempt in milliseconds. */\nexport const DEFAULT_REINVITE_TIMEOUT_MS = 5000;\n\n// =============================================================================\n// RECOVERY PIPELINE DEFAULTS (Section 19)\n// =============================================================================\n\n/** Debounce window in ms to collapse multiple detection signals into one trigger. */\nexport const DEFAULT_RECOVERY_DEBOUNCE_TIME_MS = 2000;\n\n/** Cooldown period in ms between recovery attempts. */\nexport const DEFAULT_RECOVERY_COOLDOWN_MS = 10_000;\n\n/** Grace period in ms before treating ICE 'disconnected' as a failure. */\nexport const DEFAULT_ICE_DISCONNECTED_GRACE_PERIOD_MS = 3000;\n\n/** Timeout for a single ICE restart attempt in milliseconds. */\nexport const DEFAULT_ICE_RESTART_TIMEOUT_MS = 5000;\n\n/** Maximum recovery attempts before emitting 'max_attempts_reached'. */\nexport const DEFAULT_MAX_RECOVERY_ATTEMPTS = 3;\n\n/** Upper bound in ms for waiting on iceGatheringState === 'complete' after an ICE restart. */\nexport const ICE_GATHERING_COMPLETE_TIMEOUT_MS = 10_000;\n\n/** Upper bound in ms for waiting on RTCPeerConnection.connectionState === 'connected' after a recovery ICE restart. */\nexport const PEER_CONNECTION_RECOVERY_WAIT_MS = 5000;\n\n/** Polling interval in ms while waiting for RTCPeerConnection.connectionState to transition. */\nexport const PEER_CONNECTION_RECOVERY_POLL_MS = 100;\n\n// =============================================================================\n// AUDIO PIPELINE (local mic metering / gain / VAD)\n// =============================================================================\n\n/** Polling interval for LocalAudioPipeline.level$ (ms). ~30fps is smooth for meters. */\nexport const AUDIO_LEVEL_POLL_INTERVAL_MS = 33;\n\n/** RMS level threshold (0..1) above which the local participant is considered speaking. */\nexport const VAD_THRESHOLD = 0.03;\n\n/** Hold window in ms below the threshold before speaking$ flips back to false. */\nexport const VAD_HOLD_MS = 250;\n\n// =============================================================================\n// DEVICE MANAGEMENT DEFAULTS (Section 5)\n// =============================================================================\n\n/** Whether to persist device selections to storage by default. */\nexport const DEFAULT_PERSIST_DEVICE_SELECTION = true;\n\n/** Whether to auto-apply device changes to active calls by default. */\nexport const DEFAULT_SYNC_DEVICES_TO_ACTIVE_CALLS = true;\n\n/** Storage keys for persisted device selections. */\nexport const DEVICE_STORAGE_KEY_AUDIO_INPUT = 'sw:device:audioinput';\nexport const DEVICE_STORAGE_KEY_AUDIO_OUTPUT = 'sw:device:audiooutput';\nexport const DEVICE_STORAGE_KEY_VIDEO_INPUT = 'sw:device:videoinput';\n\n/** SDK storage key prefix used for targeted cleanup (factory reset). */\nexport const SDK_STORAGE_KEY_PREFIX = 'sw:';\n\n// =============================================================================\n// VISIBILITY DEFAULTS (Section 4)\n// =============================================================================\n\n/** Whether to auto-mute video when the tab becomes hidden. */\nexport const DEFAULT_AUTO_MUTE_VIDEO_ON_HIDDEN = false;\n\n/** Whether to re-enumerate devices when the page becomes visible. */\nexport const DEFAULT_REFRESH_DEVICES_ON_VISIBLE = true;\n\n/** Whether to check peer connection health when the page becomes visible. */\nexport const DEFAULT_CHECK_CONNECTION_ON_VISIBLE = true;\n\n// =============================================================================\n// DEGRADATION THRESHOLDS (Section 22)\n// =============================================================================\n\n/** Whether automatic video degradation on low bandwidth is enabled. */\nexport const DEFAULT_ENABLE_AUTO_DEGRADATION = true;\n\n/** Bitrate in kbps below which video is automatically disabled. */\nexport const DEFAULT_DEGRADATION_BITRATE_THRESHOLD_KBPS = 150;\n\n/** Bitrate in kbps above which video is automatically re-enabled (hysteresis). */\nexport const DEFAULT_DEGRADATION_RECOVERY_THRESHOLD_KBPS = 300;\n\n// =============================================================================\n// NETWORK RECOVERY FEATURE FLAGS (Section 19)\n// =============================================================================\n\n/** Whether relay-only escalation is enabled as a last-resort recovery tier. */\nexport const DEFAULT_ENABLE_RELAY_FALLBACK = true;\n\n/** Whether to listen for browser online/offline/connection events. */\nexport const DEFAULT_ENABLE_NETWORK_CHANGE_DETECTION = true;\n\n/** Whether to intercept server-sent media-timeout hangups and attempt recovery. */\nexport const DEFAULT_ENABLE_SERVER_HANGUP_INTERCEPTION = true;\n\n// =============================================================================\n// DEFAULT AUDIO/VIDEO CONSTRAINTS (Section 16.5 & 16.6)\n// =============================================================================\n\n/** Default audio track constraints applied when no explicit constraints are provided. */\nexport const DEFAULT_AUDIO_CONSTRAINTS: MediaTrackConstraints = {\n echoCancellation: true,\n noiseSuppression: true,\n autoGainControl: true\n};\n\n/** Default video track constraints applied when video is enabled without explicit constraints. */\nexport const DEFAULT_VIDEO_CONSTRAINTS: MediaTrackConstraints = {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n aspectRatio: 16 / 9\n};\n\n/** Whether stereo Opus is enabled by default. */\nexport const DEFAULT_STEREO_AUDIO = false;\n\n/** Max average bitrate for stereo Opus in bits per second. */\nexport const DEFAULT_STEREO_MAX_AVERAGE_BITRATE = 510_000;\n\n// =============================================================================\n// QUALITY LEVEL THRESHOLDS (Section 21)\n// =============================================================================\n\n/** MOS score threshold: at or above this is 'excellent'. */\nexport const QUALITY_THRESHOLD_EXCELLENT = 4.0;\n\n/** MOS score threshold: at or above this is 'good'. */\nexport const QUALITY_THRESHOLD_GOOD = 3.5;\n\n/** MOS score threshold: at or above this is 'fair'. */\nexport const QUALITY_THRESHOLD_FAIR = 3.0;\n\n/** MOS score threshold: at or above this is 'poor'. */\nexport const QUALITY_THRESHOLD_POOR = 2.0;\n\n/** MOS score at or below QUALITY_THRESHOLD_POOR is 'critical'. */\n\n// =============================================================================\n// PREFLIGHT DEFAULTS (Section 20)\n// =============================================================================\n\n/** Default duration for the preflight media/bandwidth test in seconds. */\nexport const DEFAULT_PREFLIGHT_DURATION_SEC = 10;\n","import { MEDIA_ACCESS_DENIAL_NAMES } from './constants';\n\nexport class UnexpectedError extends Error {\n constructor(\n public at?: string,\n options?: ErrorOptions\n ) {\n super(`Unexpected Error${at ? ` at ${at}` : ''}`, options);\n this.name = 'UnexpectedError';\n }\n}\n\nexport class UnimplementedError extends Error {\n constructor(\n public reason = 'Not Implemented',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'UnimplementedError';\n }\n}\n\nexport class NotConnectedError extends Error {\n constructor(\n public reason = 'Not Connected',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'NotConnectedError';\n }\n}\n\nexport class InvalidCredentialsError extends Error {\n constructor(\n public reason = 'Invalid Credentials',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'InvalidCredentialsError';\n }\n}\n\nexport class WebSocketConnectionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WebSocketConnectionError';\n }\n}\n\nexport class TransportConnectionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'TransportConnectionError';\n }\n}\n\nexport class WebSocketTimeoutError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WebSocketTimeoutError';\n }\n}\n\nexport class RequestTimeoutError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'RequestTimeoutError';\n }\n}\n\nexport class RequestError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'RequestError';\n }\n}\n\nexport class InvalidListenerError extends Error {\n constructor(options?: ErrorOptions) {\n super('listener is not a function', options);\n this.name = 'InvalidListenerError';\n }\n}\n\nexport class RPCTimeoutError extends Error {\n constructor(\n public requestId: string,\n public timeoutMs: number,\n options?: ErrorOptions\n ) {\n super(`RPC request ${requestId} timed out after ${timeoutMs}ms`, options);\n this.name = 'RPCTimeoutError';\n }\n}\n\nexport class AuthStateHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling authorization state update', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'AuthStateHandlerError';\n }\n}\n\nexport class InvalidStateTransitionError extends Error {\n constructor(\n public currentState: string,\n public targetState: string,\n options?: ErrorOptions\n ) {\n super(\n `Invalid transition: cannot transition from \"${currentState}\" to \"${targetState}\"`,\n options\n );\n this.name = 'InvalidStateTransitionError';\n }\n}\n\nexport class InvalidOptionError extends Error {\n constructor(\n public value: string,\n public availableOptions: string[],\n options?: ErrorOptions\n ) {\n super(\n `Invalid option: \"${value}\" must be one of the available options: ${availableOptions.join(', ')}`,\n options\n );\n this.name = 'InvalidOptionError';\n }\n}\n\nexport class StorageNotAvailableError extends Error {\n constructor(\n public storageType: string = 'localStorage',\n options?: ErrorOptions\n ) {\n super(`${storageType} is not available in this environment`, options);\n this.name = 'StorageNotAvailableError';\n }\n}\n\nexport class SerializationError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to serialize value for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'SerializationError';\n }\n}\n\nexport class DeserializationError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to deserialize value for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'DeserializationError';\n }\n}\n\nexport class StorageWriteError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to write to storage for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'StorageWriteError';\n }\n}\n\nexport class StorageReadError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to read from storage \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'StorageReadError';\n }\n}\n\nexport class InvalidStorageValueError extends Error {\n constructor(\n public key: string,\n public valueType: string,\n options?: ErrorOptions\n ) {\n super(\n `Cannot serialize value of type \"${valueType}\" for key \"${key}\": This type cannot be serialized to JSON`,\n options\n );\n this.name = 'InvalidStorageValueError';\n }\n}\n\nexport class DependencyError extends Error {\n constructor(\n public description: string,\n options?: ErrorOptions\n ) {\n super(`Dependency ${description} is not set or available.`, options);\n this.name = 'DependencyError';\n }\n}\n\nexport class DeviceNotFoundError extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'DeviceNotFoundError';\n }\n}\n\n// =============================================================================\n// CALL ERROR TYPES\n// =============================================================================\n\n/**\n * Semantic category of a call-lifecycle error.\n *\n * - `'media'` – RTCPeerConnection / media device failure\n * - `'signaling'` – Verto / JSON-RPC protocol error\n * - `'timeout'` – Call setup timed out waiting for a response\n * - `'rejected'` – Remote side rejected the call\n * - `'network'` – Transport lost during an active call\n * - `'internal'` – Unexpected / unknown error\n */\nexport type CallErrorKind = 'media' | 'signaling' | 'timeout' | 'rejected' | 'network' | 'internal';\n\n/**\n * Structured error emitted on `call.errors$`.\n *\n * Provides actionable metadata so consumers can react without\n * resorting to `instanceof` checks on raw `Error` objects.\n */\nexport interface CallError {\n /** Semantic category of the error. */\n readonly kind: CallErrorKind;\n /**\n * Whether the error terminates the call.\n * When `true`, the call will automatically transition to `'failed'`\n * and be destroyed — no further action is needed from the consumer.\n */\n readonly fatal: boolean;\n /** The underlying error. */\n readonly error: Error;\n /** ID of the call that produced this error. */\n readonly callId: string;\n}\n\nexport class CallCreateError extends Error {\n constructor(\n public message: string,\n public error: unknown = null,\n public direction: 'inbound' | 'outbound' = 'outbound',\n options?: ErrorOptions\n ) {\n super(message, {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'CallCreateError';\n }\n}\n\nexport class JSONRPCError extends Error {\n constructor(\n public code: number | string,\n message: string,\n public data?: unknown,\n options?: ErrorOptions,\n public requestId?: string\n ) {\n super(message, options);\n this.name = 'JSONRPCError';\n }\n}\n\nexport class InvalidParams extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'InvalidParams';\n }\n}\n\nexport class ConversationError extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'ConversationError';\n }\n}\n\nexport class VertoInviteHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling Verto invite', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'VertoInviteHandlerError';\n }\n}\n\nexport class VertoAttachHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling Verto attach', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'VertoAttachHandlerError';\n }\n}\n\nexport class HttpRequestError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'HttpRequestError';\n }\n}\n\nexport class ValidationError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ValidationError';\n }\n}\n\nexport class VertoPongError extends Error {\n constructor(public originalError: unknown) {\n super('Failed to send Verto pong - call may disconnect', {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'VertoPongError';\n }\n}\n\nexport class MessageParseError extends Error {\n constructor(public originalError: unknown) {\n super('Failed to parse incoming WebSocket message', {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'MessageParseError';\n }\n}\n\nexport class CollectionFetchError extends Error {\n constructor(\n public operation: string,\n public originalError: unknown\n ) {\n super(`Collection fetch failed during ${operation}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'CollectionFetchError';\n }\n}\n\nexport class MediaTrackError extends Error {\n constructor(\n public operation: string,\n public kind: string,\n public originalError: unknown\n ) {\n super(`Media track ${operation} failed for ${kind}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'MediaTrackError';\n }\n}\n\n/** True when a `getUserMedia`/`getDisplayMedia` rejection is a permission denial. */\nfunction isMediaAccessDenial(originalError: unknown): boolean {\n return originalError instanceof Error && MEDIA_ACCESS_DENIAL_NAMES.includes(originalError.name);\n}\n\n/**\n * Failure to acquire local media (camera, microphone, or screen capture)\n * via `getUserMedia`/`getDisplayMedia`.\n *\n * Non-fatal by default: screenshare and additional-device failures never\n * end the call, and main-connection failures degrade to receive-only when\n * possible. The wrapping site sets `fatal` to `true` only when the call\n * cannot continue (receive-only fallback disabled or no receive intent).\n */\nexport class MediaAccessError extends Error {\n constructor(\n /** The SDK operation that failed, e.g. `'acquireLocalMedia'`, `'startScreenShare'`, `'addInputDevice'`. */\n public operation: string,\n /** The media being acquired: `'audio' | 'video' | 'audiovideo' | 'screen'`. */\n public media: string,\n /** The raw `getUserMedia`/`getDisplayMedia` error (typically a `DOMException`). */\n public originalError: unknown,\n /** Whether this failure terminates the call. */\n public readonly fatal: boolean = false\n ) {\n super(\n `Media access ${isMediaAccessDenial(originalError) ? 'denied' : 'failed'} for ${operation} (${media})`,\n {\n cause: originalError instanceof Error ? originalError : undefined\n }\n );\n this.name = 'MediaAccessError';\n }\n\n /** True when the underlying failure is a permission denial (user or policy). */\n get denied(): boolean {\n return isMediaAccessDenial(this.originalError);\n }\n}\n\n// =============================================================================\n// DPOP / CLIENT BOUND SAT ERROR TYPES\n// =============================================================================\n\nexport class DPoPInitError extends Error {\n constructor(\n public originalError: unknown,\n message = 'Failed to initialize DPoP key pair'\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'DPoPInitError';\n }\n}\n\n// =============================================================================\n// RESILIENCE ERROR TYPES\n// =============================================================================\n\n/**\n * Error thrown when a recovery attempt fails.\n *\n * Carries the recovery action and attempt number for diagnostic purposes.\n */\nexport class RecoveryError extends Error {\n constructor(\n public action: string,\n public attempt: number,\n public originalError?: unknown\n ) {\n super(`Recovery failed: ${action} (attempt ${attempt})`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'RecoveryError';\n }\n}\n\n/**\n * Error thrown when getUserMedia fails with OverconstrainedError\n * and all fallback levels have been exhausted.\n */\nexport class OverconstrainedFallbackError extends Error {\n constructor(\n public deviceKind: string,\n public originalError?: unknown\n ) {\n super(`All constraint fallback levels exhausted for ${deviceKind}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'OverconstrainedFallbackError';\n }\n}\n\n/**\n * Error thrown when the preflight connectivity test fails.\n */\nexport class PreflightError extends Error {\n constructor(\n public phase: string,\n public originalError?: unknown\n ) {\n super(`Preflight test failed during ${phase}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'PreflightError';\n }\n}\n\n// =============================================================================\n// DPOP / CLIENT BOUND SAT ERROR TYPES\n// =============================================================================\n\nexport class DeviceTokenError extends Error {\n constructor(\n message: string,\n public originalError?: unknown\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'DeviceTokenError';\n }\n}\n\nexport class TokenRefreshError extends Error {\n constructor(\n message: string,\n public originalError?: unknown\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'TokenRefreshError';\n }\n}\n","import log from 'loglevel';\n\n// =============================================================================\n// Public Interfaces\n// =============================================================================\n\n/** Log level names supported by the SDK. */\nexport type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent';\n\n/**\n * Logger interface that consumers can implement to replace the built-in logger.\n * All methods accept variadic arguments matching the browser console API.\n */\nexport interface SDKLogger {\n error(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n info(...args: unknown[]): void;\n debug(...args: unknown[]): void;\n trace(...args: unknown[]): void;\n}\n\n/** Options for WebSocket traffic logging. */\nexport interface WsTrafficOptions {\n type: 'send' | 'recv' | 'http';\n /** Parsed object or raw string — will be JSON.stringify'd for display if an object. */\n payload: unknown;\n}\n\n/**\n * Options for WebSocket traffic logging using raw strings.\n * The string is only parsed when logging is enabled, avoiding\n * unnecessary JSON.parse on every message.\n */\nexport interface WsTrafficRawOptions {\n type: 'send' | 'recv';\n raw: string;\n}\n\n/** Debug options that control verbose SDK logging. */\nexport interface DebugOptions {\n /** Log all WebSocket send/recv traffic to the console. */\n logWsTraffic?: boolean;\n}\n\n/** Extended logger with SDK-internal helpers (wsTraffic). */\nexport interface InternalSDKLogger extends SDKLogger {\n wsTraffic: (options: WsTrafficOptions | WsTrafficRawOptions) => void;\n}\n\n// =============================================================================\n// Default Logger (loglevel)\n// =============================================================================\n\nconst datetime = () => new Date().toISOString();\nconst defaultLogger = log.getLogger('signalwire');\n\nconst originalFactory = defaultLogger.methodFactory;\ndefaultLogger.methodFactory = (methodName, logLevel, loggerName) => {\n const rawMethod = originalFactory(methodName, logLevel, loggerName);\n\n return function (...args: unknown[]) {\n const prefixed = [datetime(), '-', ...args];\n // eslint-disable-next-line prefer-spread\n rawMethod.apply(undefined, prefixed);\n };\n};\n\n// Default to WARN in production; consumers opt in to verbose logging\nconst defaultLoggerLevel = defaultLogger.levels.WARN;\ndefaultLogger.setLevel(defaultLoggerLevel);\n\n// =============================================================================\n// Logger State\n// =============================================================================\n\nlet userLogger: SDKLogger | null = null;\n\n/** Replace the built-in logger with a custom implementation. Pass `null` to restore defaults. */\nconst setLogger = (logger: SDKLogger | null): void => {\n userLogger = logger;\n};\n\nlet debugOptions: DebugOptions = {};\n\n/** Configure debug options (e.g., `{ logWsTraffic: true }`). */\nconst setDebugOptions = (options: DebugOptions | null): void => {\n if (options == null) {\n debugOptions = {};\n return;\n }\n debugOptions = { ...debugOptions, ...options };\n};\n\n/**\n * Set the log level for the built-in logger.\n * Has no effect when a custom logger is set via `setLogger()`.\n */\nconst setLogLevel = (level: LogLevel): void => {\n defaultLogger.setLevel(level);\n};\n\n// =============================================================================\n// Logger Instance\n// =============================================================================\n\nconst getLoggerInstance = (): SDKLogger => {\n // loglevel's Logger matches SDKLogger (error, warn, info, debug, trace)\n return userLogger ?? (defaultLogger as SDKLogger);\n};\n\nconst shouldStringify = (payload: unknown): boolean => {\n if (payload != null && typeof payload === 'object' && 'method' in payload) {\n return (payload as Record<string, unknown>).method !== 'signalwire.ping';\n }\n return true;\n};\n\nconst wsTraffic: InternalSDKLogger['wsTraffic'] = (options) => {\n const { logWsTraffic } = debugOptions;\n\n if (!logWsTraffic) {\n return;\n }\n\n const loggerInstance = getLoggerInstance();\n\n // Support raw string payloads — parse only when logging is enabled\n let payload: unknown;\n if ('raw' in options) {\n try {\n payload = JSON.parse(options.raw);\n } catch {\n loggerInstance.debug(`[WebSocket] ${options.type.toUpperCase()}: non-JSON message`);\n return;\n }\n } else {\n ({ payload } = options);\n }\n\n const msg = shouldStringify(payload) ? JSON.stringify(payload, null, 2) : payload;\n loggerInstance.debug(`${options.type.toUpperCase()}: \\n`, msg, '\\n');\n};\n\nconst getLogger = (): InternalSDKLogger => {\n const logger = getLoggerInstance();\n\n return new Proxy(logger, {\n get(_target, prop: string | symbol, _receiver) {\n if (prop === 'wsTraffic') {\n return wsTraffic;\n }\n // Always resolve from the current logger instance so that\n // setLogger() takes effect for all existing references.\n const instance = getLoggerInstance();\n const value: unknown = Reflect.get(instance, prop);\n if (typeof value === 'function') {\n return (value as (...args: unknown[]) => unknown).bind(instance);\n }\n return value;\n }\n }) as InternalSDKLogger;\n};\n\nexport { setLogger, getLogger, setDebugOptions, setLogLevel };\n","import { filter } from 'rxjs';\n\nimport type { OperatorFunction } from 'rxjs';\n\n/**\n * RxJS operator that filters out `null` and `undefined` values with type narrowing.\n *\n * @example\n * ```ts\n * source$.pipe(filterNull()).subscribe(value => {\n * // value is guaranteed non-null\n * });\n * ```\n */\nexport function filterNull<T>(): OperatorFunction<T | null | undefined, T> {\n return filter((value): value is T => value != null);\n}\n","export const getValueFrom = <T = unknown>(\n obj: unknown,\n path: string,\n defaultValue?: T\n): T | undefined => {\n const keys = path.split('.');\n let result = obj;\n for (const key of keys) {\n if (result && typeof result === 'object' && key in result) {\n result = (result as Record<string, unknown>)[key];\n } else {\n return defaultValue;\n }\n }\n return (result === undefined ? defaultValue : result) as T;\n};\n","import { pipe } from 'rxjs';\nimport { filter, map } from 'rxjs/operators';\n\nimport { getValueFrom } from '../utils/getValueFrom';\n\nimport type { OperatorFunction } from 'rxjs';\n\n/**\n * Type helper to extract nested property types using dot notation.\n * Supports up to 4 levels of nesting.\n *\n * @example\n * type Example = { a: { b: { c: string } } }\n * type Result = PathValue<Example, 'a.b.c'> // string\n */\ntype PathValue<T, P extends string> = P extends `${infer Key}.${infer Rest}`\n ? Key extends keyof T\n ? PathValue<T[Key], Rest>\n : never\n : P extends keyof T\n ? T[P]\n : never;\n\n// Usage:\n// source$.pipe(\n// isEvent(\n// (event) => event.type === 'call.started',\n// (event) => ({ id: event.id, timestamp: event.timestamp })\n// )\n// );\n\n/**\n * RxJS operator that filters events based on a predicate and maps matching events.\n *\n * This operator combines filter and map operations:\n * 1. Only events that match the predicate are emitted\n * 2. Matching events are transformed using the map function\n *\n * @template TInput - The type of input events\n * @template TOutput - The type of output after mapping\n * @param predicate - Function to test each event. Returns true to include the event.\n * @param mapFn - Function to transform matching events\n * @returns An operator function that filters and maps events\n *\n * @example\n * ```typescript\n * interface CallEvent {\n * type: 'call.started' | 'call.ended';\n * id: string;\n * timestamp: number;\n * }\n *\n * events$.pipe(\n * isEvent(\n * (event: CallEvent) => event.type === 'call.started',\n * (event: CallEvent) => ({ id: event.id, timestamp: event.timestamp })\n * )\n * ).subscribe(startEvent => {\n * console.log('Call started:', startEvent);\n * });\n * ```\n */\nexport function ifIsMap<TInput, TOutput>(\n predicate: (event: unknown) => event is TInput,\n mapFn: (event: TInput) => TOutput\n): OperatorFunction<unknown, TOutput> {\n return pipe(filter(predicate), map(mapFn));\n}\n\n/**\n * Generic RxJS operator that filters events using a type guard and extracts a property.\n *\n * This is the generic version that works with any type, not just JSONRPCRequest.\n * Use this when you need to filter and extract properties from already-narrowed types.\n *\n * **Type inference**: The output type is automatically inferred from the input type and path!\n *\n * @template TInput - The type to narrow to (via type guard)\n * @template TPath - The dot-notation path to extract (inferred from parameter)\n * @param predicate - Type guard function to filter events\n * @param resultPath - Dot-notation path to extract (e.g., 'params', 'params.data')\n * @returns An operator function that filters and extracts\n *\n * @example\n * ```typescript\n * interface EventParams {\n * event_type: string;\n * data: { value: number };\n * }\n *\n * const isAuthEvent = (e: unknown): e is EventParams =>\n * typeof e === 'object' && e !== null && 'event_type' in e;\n *\n * // Type of 'data' is automatically inferred as { value: number }\n * params$.pipe(\n * filterAs(isAuthEvent, 'data')\n * ).subscribe(data => {\n * console.log('Event data:', data.value); // TypeScript knows about .value!\n * });\n *\n * // Deeply nested properties are also inferred\n * params$.pipe(\n * filterAs(isAuthEvent, 'data.value')\n * ).subscribe(value => {\n * console.log(value); // Type is 'number'\n * });\n * ```\n */\nexport function filterAs<TInput, TPath extends string>(\n predicate: (event: unknown) => event is TInput,\n resultPath: TPath\n): OperatorFunction<unknown, PathValue<TInput, TPath>> {\n return pipe(\n ifIsMap(predicate, (event) => {\n const result = getValueFrom<PathValue<TInput, TPath>>(event, resultPath);\n return result;\n }),\n filter((value): value is PathValue<TInput, TPath> => value !== undefined)\n );\n}\n","import { map, type OperatorFunction } from 'rxjs';\n\nimport { JSONRPCError } from '../core/errors';\nimport { getLogger } from '../utils/logger';\n\nimport type { JSONRPCResponse } from '../core/RPCMessages/types/base';\n\nconst logger = getLogger();\n\n/**\n * RxJS operator that throws a {@link JSONRPCError} when the RPC response contains an error.\n * Passes successful responses through unchanged.\n */\nexport function throwOnRPCError<T extends JSONRPCResponse>(): OperatorFunction<T, T> {\n return map((response: T) => {\n if (response.error) {\n logger.error('[throwOnRPCError] RPC error response:', {\n code: response.error.code,\n message: response.error.message,\n data: response.error.data\n });\n\n throw new JSONRPCError(response.error.code, response.error.message, response.error.data);\n }\n logger.debug('[throwOnRPCError] RPC successful response:', response);\n return response;\n });\n}\n"],"mappings":";;;;;AAAA,MAAa,iBAAiB;AAC9B,MAAa,mCAAmC;AAChD,MAAa,mCAAmC;AAChD,MAAa,qCAAqC,MAAS;AAE3D,MAAa,gCAAgC;AAC7C,MAAa,iCAAiC;AAC9C,MAAa,iCAAiC;AAC9C,MAAa,kCAAkC;AAC/C,MAAa,qCAAqC;AAClD,MAAa,0BAA0B;;AAGvC,MAAa,oBAAoB;;AAGjC,MAAa,wBAAwB;AACrC,MAAa,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACgDhD,SAAgB,QACd,WACA,OACoC;AACpC,QAAO,KAAKC,SAAO,UAAU,EAAEC,MAAI,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0C5C,SAAgB,SACd,WACA,YACqD;AACrD,QAAO,KACL,QAAQ,YAAY,UAAU;AAE5B,SADe,aAAuC,OAAO,WAAW;GAExE,EACFD,UAAQ,UAA6C,UAAU,OAAU,CAC1E;;;;;AC/GH,MAAM,SAAS,WAAW;;;;;AAM1B,SAAgB,kBAAqE;AACnF,QAAO,KAAK,aAAgB;AAC1B,MAAI,SAAS,OAAO;AAClB,UAAO,MAAM,yCAAyC;IACpD,MAAM,SAAS,MAAM;IACrB,SAAS,SAAS,MAAM;IACxB,MAAM,SAAS,MAAM;IACtB,CAAC;AAEF,SAAM,IAAI,aAAa,SAAS,MAAM,MAAM,SAAS,MAAM,SAAS,SAAS,MAAM,KAAK;;AAE1F,SAAO,MAAM,8CAA8C,SAAS;AACpE,SAAO;GACP"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@signalwire/js",
3
- "version": "4.0.0-rc.1",
3
+ "version": "4.0.0-rc.2",
4
4
  "description": "SignalWire Browser SDK",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -1 +0,0 @@
1
- {"version":3,"file":"operators-CX_lCCJm.mjs","names":["at?: string","requestId: string","timeoutMs: number","error: unknown","storageType: string","key: string","originalError: Error","description: string","message: string","direction: 'inbound' | 'outbound'","code: number | string","data?: unknown","requestId?: string","originalError: unknown","operation: string","kind: string","action: string","attempt: number","originalError?: unknown","deviceKind: string","phase: string","userLogger: SDKLogger | null","logger","debugOptions: DebugOptions","wsTraffic: InternalSDKLogger['wsTraffic']","payload: unknown","value: unknown","filter","map"],"sources":["../src/core/errors.ts","../src/utils/logger.ts","../src/operators/filterNull.ts","../src/utils/getValueFrom.ts","../src/operators/filterEventAs.ts","../src/operators/throwOnRPCError.ts"],"sourcesContent":["export class UnexpectedError extends Error {\n constructor(\n public at?: string,\n options?: ErrorOptions\n ) {\n super(`Unexpected Error${at ? ` at ${at}` : ''}`, options);\n this.name = 'UnexpectedError';\n }\n}\n\nexport class UnimplementedError extends Error {\n constructor(\n public reason = 'Not Implemented',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'UnimplementedError';\n }\n}\n\nexport class NotConnectedError extends Error {\n constructor(\n public reason = 'Not Connected',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'NotConnectedError';\n }\n}\n\nexport class InvalidCredentialsError extends Error {\n constructor(\n public reason = 'Invalid Credentials',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'InvalidCredentialsError';\n }\n}\n\nexport class WebSocketConnectionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WebSocketConnectionError';\n }\n}\n\nexport class TransportConnectionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'TransportConnectionError';\n }\n}\n\nexport class WebSocketTimeoutError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WebSocketTimeoutError';\n }\n}\n\nexport class RequestTimeoutError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'RequestTimeoutError';\n }\n}\n\nexport class RequestError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'RequestError';\n }\n}\n\nexport class InvalidListenerError extends Error {\n constructor(options?: ErrorOptions) {\n super('listener is not a function', options);\n this.name = 'InvalidListenerError';\n }\n}\n\nexport class RPCTimeoutError extends Error {\n constructor(\n public requestId: string,\n public timeoutMs: number,\n options?: ErrorOptions\n ) {\n super(`RPC request ${requestId} timed out after ${timeoutMs}ms`, options);\n this.name = 'RPCTimeoutError';\n }\n}\n\nexport class AuthStateHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling authorization state update', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'AuthStateHandlerError';\n }\n}\n\nexport class InvalidStateTransitionError extends Error {\n constructor(\n public currentState: string,\n public targetState: string,\n options?: ErrorOptions\n ) {\n super(\n `Invalid transition: cannot transition from \"${currentState}\" to \"${targetState}\"`,\n options\n );\n this.name = 'InvalidStateTransitionError';\n }\n}\n\nexport class InvalidOptionError extends Error {\n constructor(\n public value: string,\n public availableOptions: string[],\n options?: ErrorOptions\n ) {\n super(\n `Invalid option: \"${value}\" must be one of the available options: ${availableOptions.join(', ')}`,\n options\n );\n this.name = 'InvalidOptionError';\n }\n}\n\nexport class StorageNotAvailableError extends Error {\n constructor(\n public storageType: string = 'localStorage',\n options?: ErrorOptions\n ) {\n super(`${storageType} is not available in this environment`, options);\n this.name = 'StorageNotAvailableError';\n }\n}\n\nexport class SerializationError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to serialize value for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'SerializationError';\n }\n}\n\nexport class DeserializationError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to deserialize value for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'DeserializationError';\n }\n}\n\nexport class StorageWriteError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to write to storage for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'StorageWriteError';\n }\n}\n\nexport class StorageReadError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to read from storage \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'StorageReadError';\n }\n}\n\nexport class InvalidStorageValueError extends Error {\n constructor(\n public key: string,\n public valueType: string,\n options?: ErrorOptions\n ) {\n super(\n `Cannot serialize value of type \"${valueType}\" for key \"${key}\": This type cannot be serialized to JSON`,\n options\n );\n this.name = 'InvalidStorageValueError';\n }\n}\n\nexport class DependencyError extends Error {\n constructor(\n public description: string,\n options?: ErrorOptions\n ) {\n super(`Dependency ${description} is not set or available.`, options);\n this.name = 'DependencyError';\n }\n}\n\nexport class DeviceNotFoundError extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'DeviceNotFoundError';\n }\n}\n\n// =============================================================================\n// CALL ERROR TYPES\n// =============================================================================\n\n/**\n * Semantic category of a call-lifecycle error.\n *\n * - `'media'` – RTCPeerConnection / media device failure\n * - `'signaling'` – Verto / JSON-RPC protocol error\n * - `'timeout'` – Call setup timed out waiting for a response\n * - `'rejected'` – Remote side rejected the call\n * - `'network'` – Transport lost during an active call\n * - `'internal'` – Unexpected / unknown error\n */\nexport type CallErrorKind = 'media' | 'signaling' | 'timeout' | 'rejected' | 'network' | 'internal';\n\n/**\n * Structured error emitted on `call.errors$`.\n *\n * Provides actionable metadata so consumers can react without\n * resorting to `instanceof` checks on raw `Error` objects.\n */\nexport interface CallError {\n /** Semantic category of the error. */\n readonly kind: CallErrorKind;\n /**\n * Whether the error terminates the call.\n * When `true`, the call will automatically transition to `'failed'`\n * and be destroyed — no further action is needed from the consumer.\n */\n readonly fatal: boolean;\n /** The underlying error. */\n readonly error: Error;\n /** ID of the call that produced this error. */\n readonly callId: string;\n}\n\nexport class CallCreateError extends Error {\n constructor(\n public message: string,\n public error: unknown = null,\n public direction: 'inbound' | 'outbound' = 'outbound',\n options?: ErrorOptions\n ) {\n super(message, {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'CallCreateError';\n }\n}\n\nexport class JSONRPCError extends Error {\n constructor(\n public code: number | string,\n message: string,\n public data?: unknown,\n options?: ErrorOptions,\n public requestId?: string\n ) {\n super(message, options);\n this.name = 'JSONRPCError';\n }\n}\n\nexport class InvalidParams extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'InvalidParams';\n }\n}\n\nexport class ConversationError extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'ConversationError';\n }\n}\n\nexport class VertoInviteHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling Verto invite', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'VertoInviteHandlerError';\n }\n}\n\nexport class VertoAttachHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling Verto attach', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'VertoAttachHandlerError';\n }\n}\n\nexport class HttpRequestError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'HttpRequestError';\n }\n}\n\nexport class ValidationError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ValidationError';\n }\n}\n\nexport class VertoPongError extends Error {\n constructor(public originalError: unknown) {\n super('Failed to send Verto pong - call may disconnect', {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'VertoPongError';\n }\n}\n\nexport class MessageParseError extends Error {\n constructor(public originalError: unknown) {\n super('Failed to parse incoming WebSocket message', {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'MessageParseError';\n }\n}\n\nexport class CollectionFetchError extends Error {\n constructor(\n public operation: string,\n public originalError: unknown\n ) {\n super(`Collection fetch failed during ${operation}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'CollectionFetchError';\n }\n}\n\nexport class MediaTrackError extends Error {\n constructor(\n public operation: string,\n public kind: string,\n public originalError: unknown\n ) {\n super(`Media track ${operation} failed for ${kind}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'MediaTrackError';\n }\n}\n\n// =============================================================================\n// DPOP / CLIENT BOUND SAT ERROR TYPES\n// =============================================================================\n\nexport class DPoPInitError extends Error {\n constructor(\n public originalError: unknown,\n message = 'Failed to initialize DPoP key pair'\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'DPoPInitError';\n }\n}\n\n// =============================================================================\n// RESILIENCE ERROR TYPES\n// =============================================================================\n\n/**\n * Error thrown when a recovery attempt fails.\n *\n * Carries the recovery action and attempt number for diagnostic purposes.\n */\nexport class RecoveryError extends Error {\n constructor(\n public action: string,\n public attempt: number,\n public originalError?: unknown\n ) {\n super(`Recovery failed: ${action} (attempt ${attempt})`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'RecoveryError';\n }\n}\n\n/**\n * Error thrown when getUserMedia fails with OverconstrainedError\n * and all fallback levels have been exhausted.\n */\nexport class OverconstrainedFallbackError extends Error {\n constructor(\n public deviceKind: string,\n public originalError?: unknown\n ) {\n super(`All constraint fallback levels exhausted for ${deviceKind}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'OverconstrainedFallbackError';\n }\n}\n\n/**\n * Error thrown when the preflight connectivity test fails.\n */\nexport class PreflightError extends Error {\n constructor(\n public phase: string,\n public originalError?: unknown\n ) {\n super(`Preflight test failed during ${phase}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'PreflightError';\n }\n}\n\n// =============================================================================\n// DPOP / CLIENT BOUND SAT ERROR TYPES\n// =============================================================================\n\nexport class DeviceTokenError extends Error {\n constructor(\n message: string,\n public originalError?: unknown\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'DeviceTokenError';\n }\n}\n\nexport class TokenRefreshError extends Error {\n constructor(\n message: string,\n public originalError?: unknown\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'TokenRefreshError';\n }\n}\n","import log from 'loglevel';\n\n// =============================================================================\n// Public Interfaces\n// =============================================================================\n\n/** Log level names supported by the SDK. */\nexport type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent';\n\n/**\n * Logger interface that consumers can implement to replace the built-in logger.\n * All methods accept variadic arguments matching the browser console API.\n */\nexport interface SDKLogger {\n error(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n info(...args: unknown[]): void;\n debug(...args: unknown[]): void;\n trace(...args: unknown[]): void;\n}\n\n/** Options for WebSocket traffic logging. */\nexport interface WsTrafficOptions {\n type: 'send' | 'recv' | 'http';\n /** Parsed object or raw string — will be JSON.stringify'd for display if an object. */\n payload: unknown;\n}\n\n/**\n * Options for WebSocket traffic logging using raw strings.\n * The string is only parsed when logging is enabled, avoiding\n * unnecessary JSON.parse on every message.\n */\nexport interface WsTrafficRawOptions {\n type: 'send' | 'recv';\n raw: string;\n}\n\n/** Debug options that control verbose SDK logging. */\nexport interface DebugOptions {\n /** Log all WebSocket send/recv traffic to the console. */\n logWsTraffic?: boolean;\n}\n\n/** Extended logger with SDK-internal helpers (wsTraffic). */\nexport interface InternalSDKLogger extends SDKLogger {\n wsTraffic: (options: WsTrafficOptions | WsTrafficRawOptions) => void;\n}\n\n// =============================================================================\n// Default Logger (loglevel)\n// =============================================================================\n\nconst datetime = () => new Date().toISOString();\nconst defaultLogger = log.getLogger('signalwire');\n\nconst originalFactory = defaultLogger.methodFactory;\ndefaultLogger.methodFactory = (methodName, logLevel, loggerName) => {\n const rawMethod = originalFactory(methodName, logLevel, loggerName);\n\n return function (...args: unknown[]) {\n const prefixed = [datetime(), '-', ...args];\n // eslint-disable-next-line prefer-spread\n rawMethod.apply(undefined, prefixed);\n };\n};\n\n// Default to WARN in production; consumers opt in to verbose logging\nconst defaultLoggerLevel = defaultLogger.levels.WARN;\ndefaultLogger.setLevel(defaultLoggerLevel);\n\n// =============================================================================\n// Logger State\n// =============================================================================\n\nlet userLogger: SDKLogger | null = null;\n\n/** Replace the built-in logger with a custom implementation. Pass `null` to restore defaults. */\nconst setLogger = (logger: SDKLogger | null): void => {\n userLogger = logger;\n};\n\nlet debugOptions: DebugOptions = {};\n\n/** Configure debug options (e.g., `{ logWsTraffic: true }`). */\nconst setDebugOptions = (options: DebugOptions | null): void => {\n if (options == null) {\n debugOptions = {};\n return;\n }\n debugOptions = { ...debugOptions, ...options };\n};\n\n/**\n * Set the log level for the built-in logger.\n * Has no effect when a custom logger is set via `setLogger()`.\n */\nconst setLogLevel = (level: LogLevel): void => {\n defaultLogger.setLevel(level);\n};\n\n// =============================================================================\n// Logger Instance\n// =============================================================================\n\nconst getLoggerInstance = (): SDKLogger => {\n // loglevel's Logger matches SDKLogger (error, warn, info, debug, trace)\n return userLogger ?? (defaultLogger as SDKLogger);\n};\n\nconst shouldStringify = (payload: unknown): boolean => {\n if (payload != null && typeof payload === 'object' && 'method' in payload) {\n return (payload as Record<string, unknown>).method !== 'signalwire.ping';\n }\n return true;\n};\n\nconst wsTraffic: InternalSDKLogger['wsTraffic'] = (options) => {\n const { logWsTraffic } = debugOptions;\n\n if (!logWsTraffic) {\n return;\n }\n\n const loggerInstance = getLoggerInstance();\n\n // Support raw string payloads — parse only when logging is enabled\n let payload: unknown;\n if ('raw' in options) {\n try {\n payload = JSON.parse(options.raw);\n } catch {\n loggerInstance.debug(`[WebSocket] ${options.type.toUpperCase()}: non-JSON message`);\n return;\n }\n } else {\n ({ payload } = options);\n }\n\n const msg = shouldStringify(payload) ? JSON.stringify(payload, null, 2) : payload;\n loggerInstance.debug(`${options.type.toUpperCase()}: \\n`, msg, '\\n');\n};\n\nconst getLogger = (): InternalSDKLogger => {\n const logger = getLoggerInstance();\n\n return new Proxy(logger, {\n get(_target, prop: string | symbol, _receiver) {\n if (prop === 'wsTraffic') {\n return wsTraffic;\n }\n // Always resolve from the current logger instance so that\n // setLogger() takes effect for all existing references.\n const instance = getLoggerInstance();\n const value: unknown = Reflect.get(instance, prop);\n if (typeof value === 'function') {\n return (value as (...args: unknown[]) => unknown).bind(instance);\n }\n return value;\n }\n }) as InternalSDKLogger;\n};\n\nexport { setLogger, getLogger, setDebugOptions, setLogLevel };\n","import { filter } from 'rxjs';\n\nimport type { OperatorFunction } from 'rxjs';\n\n/**\n * RxJS operator that filters out `null` and `undefined` values with type narrowing.\n *\n * @example\n * ```ts\n * source$.pipe(filterNull()).subscribe(value => {\n * // value is guaranteed non-null\n * });\n * ```\n */\nexport function filterNull<T>(): OperatorFunction<T | null | undefined, T> {\n return filter((value): value is T => value != null);\n}\n","export const getValueFrom = <T = unknown>(\n obj: unknown,\n path: string,\n defaultValue?: T\n): T | undefined => {\n const keys = path.split('.');\n let result = obj;\n for (const key of keys) {\n if (result && typeof result === 'object' && key in result) {\n result = (result as Record<string, unknown>)[key];\n } else {\n return defaultValue;\n }\n }\n return (result === undefined ? defaultValue : result) as T;\n};\n","import { pipe } from 'rxjs';\nimport { filter, map } from 'rxjs/operators';\n\nimport { getValueFrom } from '../utils/getValueFrom';\n\nimport type { OperatorFunction } from 'rxjs';\n\n/**\n * Type helper to extract nested property types using dot notation.\n * Supports up to 4 levels of nesting.\n *\n * @example\n * type Example = { a: { b: { c: string } } }\n * type Result = PathValue<Example, 'a.b.c'> // string\n */\ntype PathValue<T, P extends string> = P extends `${infer Key}.${infer Rest}`\n ? Key extends keyof T\n ? PathValue<T[Key], Rest>\n : never\n : P extends keyof T\n ? T[P]\n : never;\n\n// Usage:\n// source$.pipe(\n// isEvent(\n// (event) => event.type === 'call.started',\n// (event) => ({ id: event.id, timestamp: event.timestamp })\n// )\n// );\n\n/**\n * RxJS operator that filters events based on a predicate and maps matching events.\n *\n * This operator combines filter and map operations:\n * 1. Only events that match the predicate are emitted\n * 2. Matching events are transformed using the map function\n *\n * @template TInput - The type of input events\n * @template TOutput - The type of output after mapping\n * @param predicate - Function to test each event. Returns true to include the event.\n * @param mapFn - Function to transform matching events\n * @returns An operator function that filters and maps events\n *\n * @example\n * ```typescript\n * interface CallEvent {\n * type: 'call.started' | 'call.ended';\n * id: string;\n * timestamp: number;\n * }\n *\n * events$.pipe(\n * isEvent(\n * (event: CallEvent) => event.type === 'call.started',\n * (event: CallEvent) => ({ id: event.id, timestamp: event.timestamp })\n * )\n * ).subscribe(startEvent => {\n * console.log('Call started:', startEvent);\n * });\n * ```\n */\nexport function ifIsMap<TInput, TOutput>(\n predicate: (event: unknown) => event is TInput,\n mapFn: (event: TInput) => TOutput\n): OperatorFunction<unknown, TOutput> {\n return pipe(filter(predicate), map(mapFn));\n}\n\n/**\n * Generic RxJS operator that filters events using a type guard and extracts a property.\n *\n * This is the generic version that works with any type, not just JSONRPCRequest.\n * Use this when you need to filter and extract properties from already-narrowed types.\n *\n * **Type inference**: The output type is automatically inferred from the input type and path!\n *\n * @template TInput - The type to narrow to (via type guard)\n * @template TPath - The dot-notation path to extract (inferred from parameter)\n * @param predicate - Type guard function to filter events\n * @param resultPath - Dot-notation path to extract (e.g., 'params', 'params.data')\n * @returns An operator function that filters and extracts\n *\n * @example\n * ```typescript\n * interface EventParams {\n * event_type: string;\n * data: { value: number };\n * }\n *\n * const isAuthEvent = (e: unknown): e is EventParams =>\n * typeof e === 'object' && e !== null && 'event_type' in e;\n *\n * // Type of 'data' is automatically inferred as { value: number }\n * params$.pipe(\n * filterAs(isAuthEvent, 'data')\n * ).subscribe(data => {\n * console.log('Event data:', data.value); // TypeScript knows about .value!\n * });\n *\n * // Deeply nested properties are also inferred\n * params$.pipe(\n * filterAs(isAuthEvent, 'data.value')\n * ).subscribe(value => {\n * console.log(value); // Type is 'number'\n * });\n * ```\n */\nexport function filterAs<TInput, TPath extends string>(\n predicate: (event: unknown) => event is TInput,\n resultPath: TPath\n): OperatorFunction<unknown, PathValue<TInput, TPath>> {\n return pipe(\n ifIsMap(predicate, (event) => {\n const result = getValueFrom<PathValue<TInput, TPath>>(event, resultPath);\n return result;\n }),\n filter((value): value is PathValue<TInput, TPath> => value !== undefined)\n );\n}\n","import { map, type OperatorFunction } from 'rxjs';\n\nimport { JSONRPCError } from '../core/errors';\nimport { getLogger } from '../utils/logger';\n\nimport type { JSONRPCResponse } from '../core/RPCMessages/types/base';\n\nconst logger = getLogger();\n\n/**\n * RxJS operator that throws a {@link JSONRPCError} when the RPC response contains an error.\n * Passes successful responses through unchanged.\n */\nexport function throwOnRPCError<T extends JSONRPCResponse>(): OperatorFunction<T, T> {\n return map((response: T) => {\n if (response.error) {\n logger.error('[throwOnRPCError] RPC error response:', {\n code: response.error.code,\n message: response.error.message,\n data: response.error.data\n });\n\n throw new JSONRPCError(response.error.code, response.error.message, response.error.data);\n }\n logger.debug('[throwOnRPCError] RPC successful response:', response);\n return response;\n });\n}\n"],"mappings":";;;;;AAAA,IAAa,kBAAb,cAAqC,MAAM;CACzC,YACE,AAAOA,IACP,SACA;AACA,QAAM,mBAAmB,KAAK,OAAO,OAAO,MAAM,QAAQ;EAHnD;AAIP,OAAK,OAAO;;;AAIhB,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YACE,AAAO,SAAS,mBAChB,SACA;AACA,QAAM,QAAQ,QAAQ;EAHf;AAIP,OAAK,OAAO;;;AAchB,IAAa,0BAAb,cAA6C,MAAM;CACjD,YACE,AAAO,SAAS,uBAChB,SACA;AACA,QAAM,QAAQ,QAAQ;EAHf;AAIP,OAAK,OAAO;;;AAIhB,IAAa,2BAAb,cAA8C,MAAM;CAClD,YAAY,SAAiB,SAAwB;AACnD,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;;;AAIhB,IAAa,2BAAb,cAA8C,MAAM;CAClD,YAAY,SAAiB,SAAwB;AACnD,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;;;AAIhB,IAAa,wBAAb,cAA2C,MAAM;CAC/C,YAAY,SAAiB,SAAwB;AACnD,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;;;AAIhB,IAAa,sBAAb,cAAyC,MAAM;CAC7C,YAAY,SAAiB,SAAwB;AACnD,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;;;AAIhB,IAAa,eAAb,cAAkC,MAAM;CACtC,YAAY,SAAiB,SAAwB;AACnD,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;;;AAWhB,IAAa,kBAAb,cAAqC,MAAM;CACzC,YACE,AAAO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,UAAQ,UAA6C,UAAU,OAAU,CAC1E;;;;;AC/GH,MAAM,SAAS,WAAW;;;;;AAM1B,SAAgB,kBAAqE;AACnF,QAAO,KAAK,aAAgB;AAC1B,MAAI,SAAS,OAAO;AAClB,UAAO,MAAM,yCAAyC;IACpD,MAAM,SAAS,MAAM;IACrB,SAAS,SAAS,MAAM;IACxB,MAAM,SAAS,MAAM;IACtB,CAAC;AAEF,SAAM,IAAI,aAAa,SAAS,MAAM,MAAM,SAAS,MAAM,SAAS,SAAS,MAAM,KAAK;;AAE1F,SAAO,MAAM,8CAA8C,SAAS;AACpE,SAAO;GACP"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"operators-D6a2J1KA.cjs","names":["at?: string","requestId: string","timeoutMs: number","error: unknown","storageType: string","key: string","originalError: Error","description: string","message: string","direction: 'inbound' | 'outbound'","code: number | string","data?: unknown","requestId?: string","originalError: unknown","operation: string","kind: string","action: string","attempt: number","originalError?: unknown","deviceKind: string","phase: string","log","userLogger: SDKLogger | null","logger","debugOptions: DebugOptions","wsTraffic: InternalSDKLogger['wsTraffic']","payload: unknown","value: unknown"],"sources":["../src/core/errors.ts","../src/utils/logger.ts","../src/operators/filterNull.ts","../src/utils/getValueFrom.ts","../src/operators/filterEventAs.ts","../src/operators/throwOnRPCError.ts"],"sourcesContent":["export class UnexpectedError extends Error {\n constructor(\n public at?: string,\n options?: ErrorOptions\n ) {\n super(`Unexpected Error${at ? ` at ${at}` : ''}`, options);\n this.name = 'UnexpectedError';\n }\n}\n\nexport class UnimplementedError extends Error {\n constructor(\n public reason = 'Not Implemented',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'UnimplementedError';\n }\n}\n\nexport class NotConnectedError extends Error {\n constructor(\n public reason = 'Not Connected',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'NotConnectedError';\n }\n}\n\nexport class InvalidCredentialsError extends Error {\n constructor(\n public reason = 'Invalid Credentials',\n options?: ErrorOptions\n ) {\n super(reason, options);\n this.name = 'InvalidCredentialsError';\n }\n}\n\nexport class WebSocketConnectionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WebSocketConnectionError';\n }\n}\n\nexport class TransportConnectionError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'TransportConnectionError';\n }\n}\n\nexport class WebSocketTimeoutError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WebSocketTimeoutError';\n }\n}\n\nexport class RequestTimeoutError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'RequestTimeoutError';\n }\n}\n\nexport class RequestError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'RequestError';\n }\n}\n\nexport class InvalidListenerError extends Error {\n constructor(options?: ErrorOptions) {\n super('listener is not a function', options);\n this.name = 'InvalidListenerError';\n }\n}\n\nexport class RPCTimeoutError extends Error {\n constructor(\n public requestId: string,\n public timeoutMs: number,\n options?: ErrorOptions\n ) {\n super(`RPC request ${requestId} timed out after ${timeoutMs}ms`, options);\n this.name = 'RPCTimeoutError';\n }\n}\n\nexport class AuthStateHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling authorization state update', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'AuthStateHandlerError';\n }\n}\n\nexport class InvalidStateTransitionError extends Error {\n constructor(\n public currentState: string,\n public targetState: string,\n options?: ErrorOptions\n ) {\n super(\n `Invalid transition: cannot transition from \"${currentState}\" to \"${targetState}\"`,\n options\n );\n this.name = 'InvalidStateTransitionError';\n }\n}\n\nexport class InvalidOptionError extends Error {\n constructor(\n public value: string,\n public availableOptions: string[],\n options?: ErrorOptions\n ) {\n super(\n `Invalid option: \"${value}\" must be one of the available options: ${availableOptions.join(', ')}`,\n options\n );\n this.name = 'InvalidOptionError';\n }\n}\n\nexport class StorageNotAvailableError extends Error {\n constructor(\n public storageType: string = 'localStorage',\n options?: ErrorOptions\n ) {\n super(`${storageType} is not available in this environment`, options);\n this.name = 'StorageNotAvailableError';\n }\n}\n\nexport class SerializationError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to serialize value for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'SerializationError';\n }\n}\n\nexport class DeserializationError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to deserialize value for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'DeserializationError';\n }\n}\n\nexport class StorageWriteError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to write to storage for key \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'StorageWriteError';\n }\n}\n\nexport class StorageReadError extends Error {\n constructor(\n public key: string,\n public originalError: Error\n ) {\n super(`Failed to read from storage \"${key}\": ${originalError.message}`, {\n cause: originalError\n });\n this.name = 'StorageReadError';\n }\n}\n\nexport class InvalidStorageValueError extends Error {\n constructor(\n public key: string,\n public valueType: string,\n options?: ErrorOptions\n ) {\n super(\n `Cannot serialize value of type \"${valueType}\" for key \"${key}\": This type cannot be serialized to JSON`,\n options\n );\n this.name = 'InvalidStorageValueError';\n }\n}\n\nexport class DependencyError extends Error {\n constructor(\n public description: string,\n options?: ErrorOptions\n ) {\n super(`Dependency ${description} is not set or available.`, options);\n this.name = 'DependencyError';\n }\n}\n\nexport class DeviceNotFoundError extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'DeviceNotFoundError';\n }\n}\n\n// =============================================================================\n// CALL ERROR TYPES\n// =============================================================================\n\n/**\n * Semantic category of a call-lifecycle error.\n *\n * - `'media'` – RTCPeerConnection / media device failure\n * - `'signaling'` – Verto / JSON-RPC protocol error\n * - `'timeout'` – Call setup timed out waiting for a response\n * - `'rejected'` – Remote side rejected the call\n * - `'network'` – Transport lost during an active call\n * - `'internal'` – Unexpected / unknown error\n */\nexport type CallErrorKind = 'media' | 'signaling' | 'timeout' | 'rejected' | 'network' | 'internal';\n\n/**\n * Structured error emitted on `call.errors$`.\n *\n * Provides actionable metadata so consumers can react without\n * resorting to `instanceof` checks on raw `Error` objects.\n */\nexport interface CallError {\n /** Semantic category of the error. */\n readonly kind: CallErrorKind;\n /**\n * Whether the error terminates the call.\n * When `true`, the call will automatically transition to `'failed'`\n * and be destroyed — no further action is needed from the consumer.\n */\n readonly fatal: boolean;\n /** The underlying error. */\n readonly error: Error;\n /** ID of the call that produced this error. */\n readonly callId: string;\n}\n\nexport class CallCreateError extends Error {\n constructor(\n public message: string,\n public error: unknown = null,\n public direction: 'inbound' | 'outbound' = 'outbound',\n options?: ErrorOptions\n ) {\n super(message, {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'CallCreateError';\n }\n}\n\nexport class JSONRPCError extends Error {\n constructor(\n public code: number | string,\n message: string,\n public data?: unknown,\n options?: ErrorOptions,\n public requestId?: string\n ) {\n super(message, options);\n this.name = 'JSONRPCError';\n }\n}\n\nexport class InvalidParams extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'InvalidParams';\n }\n}\n\nexport class ConversationError extends Error {\n constructor(\n public message: string,\n options?: ErrorOptions\n ) {\n super(message, options);\n this.name = 'ConversationError';\n }\n}\n\nexport class VertoInviteHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling Verto invite', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'VertoInviteHandlerError';\n }\n}\n\nexport class VertoAttachHandlerError extends Error {\n constructor(\n public error: unknown = null,\n options?: ErrorOptions\n ) {\n super('Error handling Verto attach', {\n ...options,\n cause: options?.cause ?? (error instanceof Error ? error : undefined)\n });\n this.name = 'VertoAttachHandlerError';\n }\n}\n\nexport class HttpRequestError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'HttpRequestError';\n }\n}\n\nexport class ValidationError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'ValidationError';\n }\n}\n\nexport class VertoPongError extends Error {\n constructor(public originalError: unknown) {\n super('Failed to send Verto pong - call may disconnect', {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'VertoPongError';\n }\n}\n\nexport class MessageParseError extends Error {\n constructor(public originalError: unknown) {\n super('Failed to parse incoming WebSocket message', {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'MessageParseError';\n }\n}\n\nexport class CollectionFetchError extends Error {\n constructor(\n public operation: string,\n public originalError: unknown\n ) {\n super(`Collection fetch failed during ${operation}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'CollectionFetchError';\n }\n}\n\nexport class MediaTrackError extends Error {\n constructor(\n public operation: string,\n public kind: string,\n public originalError: unknown\n ) {\n super(`Media track ${operation} failed for ${kind}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'MediaTrackError';\n }\n}\n\n// =============================================================================\n// DPOP / CLIENT BOUND SAT ERROR TYPES\n// =============================================================================\n\nexport class DPoPInitError extends Error {\n constructor(\n public originalError: unknown,\n message = 'Failed to initialize DPoP key pair'\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'DPoPInitError';\n }\n}\n\n// =============================================================================\n// RESILIENCE ERROR TYPES\n// =============================================================================\n\n/**\n * Error thrown when a recovery attempt fails.\n *\n * Carries the recovery action and attempt number for diagnostic purposes.\n */\nexport class RecoveryError extends Error {\n constructor(\n public action: string,\n public attempt: number,\n public originalError?: unknown\n ) {\n super(`Recovery failed: ${action} (attempt ${attempt})`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'RecoveryError';\n }\n}\n\n/**\n * Error thrown when getUserMedia fails with OverconstrainedError\n * and all fallback levels have been exhausted.\n */\nexport class OverconstrainedFallbackError extends Error {\n constructor(\n public deviceKind: string,\n public originalError?: unknown\n ) {\n super(`All constraint fallback levels exhausted for ${deviceKind}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'OverconstrainedFallbackError';\n }\n}\n\n/**\n * Error thrown when the preflight connectivity test fails.\n */\nexport class PreflightError extends Error {\n constructor(\n public phase: string,\n public originalError?: unknown\n ) {\n super(`Preflight test failed during ${phase}`, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'PreflightError';\n }\n}\n\n// =============================================================================\n// DPOP / CLIENT BOUND SAT ERROR TYPES\n// =============================================================================\n\nexport class DeviceTokenError extends Error {\n constructor(\n message: string,\n public originalError?: unknown\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'DeviceTokenError';\n }\n}\n\nexport class TokenRefreshError extends Error {\n constructor(\n message: string,\n public originalError?: unknown\n ) {\n super(message, {\n cause: originalError instanceof Error ? originalError : undefined\n });\n this.name = 'TokenRefreshError';\n }\n}\n","import log from 'loglevel';\n\n// =============================================================================\n// Public Interfaces\n// =============================================================================\n\n/** Log level names supported by the SDK. */\nexport type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent';\n\n/**\n * Logger interface that consumers can implement to replace the built-in logger.\n * All methods accept variadic arguments matching the browser console API.\n */\nexport interface SDKLogger {\n error(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n info(...args: unknown[]): void;\n debug(...args: unknown[]): void;\n trace(...args: unknown[]): void;\n}\n\n/** Options for WebSocket traffic logging. */\nexport interface WsTrafficOptions {\n type: 'send' | 'recv' | 'http';\n /** Parsed object or raw string — will be JSON.stringify'd for display if an object. */\n payload: unknown;\n}\n\n/**\n * Options for WebSocket traffic logging using raw strings.\n * The string is only parsed when logging is enabled, avoiding\n * unnecessary JSON.parse on every message.\n */\nexport interface WsTrafficRawOptions {\n type: 'send' | 'recv';\n raw: string;\n}\n\n/** Debug options that control verbose SDK logging. */\nexport interface DebugOptions {\n /** Log all WebSocket send/recv traffic to the console. */\n logWsTraffic?: boolean;\n}\n\n/** Extended logger with SDK-internal helpers (wsTraffic). */\nexport interface InternalSDKLogger extends SDKLogger {\n wsTraffic: (options: WsTrafficOptions | WsTrafficRawOptions) => void;\n}\n\n// =============================================================================\n// Default Logger (loglevel)\n// =============================================================================\n\nconst datetime = () => new Date().toISOString();\nconst defaultLogger = log.getLogger('signalwire');\n\nconst originalFactory = defaultLogger.methodFactory;\ndefaultLogger.methodFactory = (methodName, logLevel, loggerName) => {\n const rawMethod = originalFactory(methodName, logLevel, loggerName);\n\n return function (...args: unknown[]) {\n const prefixed = [datetime(), '-', ...args];\n // eslint-disable-next-line prefer-spread\n rawMethod.apply(undefined, prefixed);\n };\n};\n\n// Default to WARN in production; consumers opt in to verbose logging\nconst defaultLoggerLevel = defaultLogger.levels.WARN;\ndefaultLogger.setLevel(defaultLoggerLevel);\n\n// =============================================================================\n// Logger State\n// =============================================================================\n\nlet userLogger: SDKLogger | null = null;\n\n/** Replace the built-in logger with a custom implementation. Pass `null` to restore defaults. */\nconst setLogger = (logger: SDKLogger | null): void => {\n userLogger = logger;\n};\n\nlet debugOptions: DebugOptions = {};\n\n/** Configure debug options (e.g., `{ logWsTraffic: true }`). */\nconst setDebugOptions = (options: DebugOptions | null): void => {\n if (options == null) {\n debugOptions = {};\n return;\n }\n debugOptions = { ...debugOptions, ...options };\n};\n\n/**\n * Set the log level for the built-in logger.\n * Has no effect when a custom logger is set via `setLogger()`.\n */\nconst setLogLevel = (level: LogLevel): void => {\n defaultLogger.setLevel(level);\n};\n\n// =============================================================================\n// Logger Instance\n// =============================================================================\n\nconst getLoggerInstance = (): SDKLogger => {\n // loglevel's Logger matches SDKLogger (error, warn, info, debug, trace)\n return userLogger ?? (defaultLogger as SDKLogger);\n};\n\nconst shouldStringify = (payload: unknown): boolean => {\n if (payload != null && typeof payload === 'object' && 'method' in payload) {\n return (payload as Record<string, unknown>).method !== 'signalwire.ping';\n }\n return true;\n};\n\nconst wsTraffic: InternalSDKLogger['wsTraffic'] = (options) => {\n const { logWsTraffic } = debugOptions;\n\n if (!logWsTraffic) {\n return;\n }\n\n const loggerInstance = getLoggerInstance();\n\n // Support raw string payloads — parse only when logging is enabled\n let payload: unknown;\n if ('raw' in options) {\n try {\n payload = JSON.parse(options.raw);\n } catch {\n loggerInstance.debug(`[WebSocket] ${options.type.toUpperCase()}: non-JSON message`);\n return;\n }\n } else {\n ({ payload } = options);\n }\n\n const msg = shouldStringify(payload) ? JSON.stringify(payload, null, 2) : payload;\n loggerInstance.debug(`${options.type.toUpperCase()}: \\n`, msg, '\\n');\n};\n\nconst getLogger = (): InternalSDKLogger => {\n const logger = getLoggerInstance();\n\n return new Proxy(logger, {\n get(_target, prop: string | symbol, _receiver) {\n if (prop === 'wsTraffic') {\n return wsTraffic;\n }\n // Always resolve from the current logger instance so that\n // setLogger() takes effect for all existing references.\n const instance = getLoggerInstance();\n const value: unknown = Reflect.get(instance, prop);\n if (typeof value === 'function') {\n return (value as (...args: unknown[]) => unknown).bind(instance);\n }\n return value;\n }\n }) as InternalSDKLogger;\n};\n\nexport { setLogger, getLogger, setDebugOptions, setLogLevel };\n","import { filter } from 'rxjs';\n\nimport type { OperatorFunction } from 'rxjs';\n\n/**\n * RxJS operator that filters out `null` and `undefined` values with type narrowing.\n *\n * @example\n * ```ts\n * source$.pipe(filterNull()).subscribe(value => {\n * // value is guaranteed non-null\n * });\n * ```\n */\nexport function filterNull<T>(): OperatorFunction<T | null | undefined, T> {\n return filter((value): value is T => value != null);\n}\n","export const getValueFrom = <T = unknown>(\n obj: unknown,\n path: string,\n defaultValue?: T\n): T | undefined => {\n const keys = path.split('.');\n let result = obj;\n for (const key of keys) {\n if (result && typeof result === 'object' && key in result) {\n result = (result as Record<string, unknown>)[key];\n } else {\n return defaultValue;\n }\n }\n return (result === undefined ? defaultValue : result) as T;\n};\n","import { pipe } from 'rxjs';\nimport { filter, map } from 'rxjs/operators';\n\nimport { getValueFrom } from '../utils/getValueFrom';\n\nimport type { OperatorFunction } from 'rxjs';\n\n/**\n * Type helper to extract nested property types using dot notation.\n * Supports up to 4 levels of nesting.\n *\n * @example\n * type Example = { a: { b: { c: string } } }\n * type Result = PathValue<Example, 'a.b.c'> // string\n */\ntype PathValue<T, P extends string> = P extends `${infer Key}.${infer Rest}`\n ? Key extends keyof T\n ? PathValue<T[Key], Rest>\n : never\n : P extends keyof T\n ? T[P]\n : never;\n\n// Usage:\n// source$.pipe(\n// isEvent(\n// (event) => event.type === 'call.started',\n// (event) => ({ id: event.id, timestamp: event.timestamp })\n// )\n// );\n\n/**\n * RxJS operator that filters events based on a predicate and maps matching events.\n *\n * This operator combines filter and map operations:\n * 1. Only events that match the predicate are emitted\n * 2. Matching events are transformed using the map function\n *\n * @template TInput - The type of input events\n * @template TOutput - The type of output after mapping\n * @param predicate - Function to test each event. Returns true to include the event.\n * @param mapFn - Function to transform matching events\n * @returns An operator function that filters and maps events\n *\n * @example\n * ```typescript\n * interface CallEvent {\n * type: 'call.started' | 'call.ended';\n * id: string;\n * timestamp: number;\n * }\n *\n * events$.pipe(\n * isEvent(\n * (event: CallEvent) => event.type === 'call.started',\n * (event: CallEvent) => ({ id: event.id, timestamp: event.timestamp })\n * )\n * ).subscribe(startEvent => {\n * console.log('Call started:', startEvent);\n * });\n * ```\n */\nexport function ifIsMap<TInput, TOutput>(\n predicate: (event: unknown) => event is TInput,\n mapFn: (event: TInput) => TOutput\n): OperatorFunction<unknown, TOutput> {\n return pipe(filter(predicate), map(mapFn));\n}\n\n/**\n * Generic RxJS operator that filters events using a type guard and extracts a property.\n *\n * This is the generic version that works with any type, not just JSONRPCRequest.\n * Use this when you need to filter and extract properties from already-narrowed types.\n *\n * **Type inference**: The output type is automatically inferred from the input type and path!\n *\n * @template TInput - The type to narrow to (via type guard)\n * @template TPath - The dot-notation path to extract (inferred from parameter)\n * @param predicate - Type guard function to filter events\n * @param resultPath - Dot-notation path to extract (e.g., 'params', 'params.data')\n * @returns An operator function that filters and extracts\n *\n * @example\n * ```typescript\n * interface EventParams {\n * event_type: string;\n * data: { value: number };\n * }\n *\n * const isAuthEvent = (e: unknown): e is EventParams =>\n * typeof e === 'object' && e !== null && 'event_type' in e;\n *\n * // Type of 'data' is automatically inferred as { value: number }\n * params$.pipe(\n * filterAs(isAuthEvent, 'data')\n * ).subscribe(data => {\n * console.log('Event data:', data.value); // TypeScript knows about .value!\n * });\n *\n * // Deeply nested properties are also inferred\n * params$.pipe(\n * filterAs(isAuthEvent, 'data.value')\n * ).subscribe(value => {\n * console.log(value); // Type is 'number'\n * });\n * ```\n */\nexport function filterAs<TInput, TPath extends string>(\n predicate: (event: unknown) => event is TInput,\n resultPath: TPath\n): OperatorFunction<unknown, PathValue<TInput, TPath>> {\n return pipe(\n ifIsMap(predicate, (event) => {\n const result = getValueFrom<PathValue<TInput, TPath>>(event, resultPath);\n return result;\n }),\n filter((value): value is PathValue<TInput, TPath> => value !== undefined)\n );\n}\n","import { map, type OperatorFunction } from 'rxjs';\n\nimport { JSONRPCError } from '../core/errors';\nimport { getLogger } from '../utils/logger';\n\nimport type { JSONRPCResponse } from '../core/RPCMessages/types/base';\n\nconst logger = getLogger();\n\n/**\n * RxJS operator that throws a {@link JSONRPCError} when the RPC response contains an error.\n * Passes successful responses through unchanged.\n */\nexport function throwOnRPCError<T extends JSONRPCResponse>(): OperatorFunction<T, T> {\n return map((response: T) => {\n if (response.error) {\n logger.error('[throwOnRPCError] RPC error response:', {\n code: response.error.code,\n message: response.error.message,\n data: response.error.data\n });\n\n throw new JSONRPCError(response.error.code, response.error.message, response.error.data);\n }\n logger.debug('[throwOnRPCError] RPC successful response:', response);\n return response;\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAa,kBAAb,cAAqC,MAAM;CACzC,YACE,AAAOA,IACP,SACA;AACA,QAAM,mBAAmB,KAAK,OAAO,OAAO,MAAM,QAAQ;EAHnD;AAIP,OAAK,OAAO;;;AAIhB,IAAa,q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