import { EventEmitter } from 'events'; /** * Core type definitions for WaSP (WhatsApp Session Protocol) */ /** * Session status enumeration */ declare enum SessionStatus { CONNECTING = "CONNECTING", CONNECTED = "CONNECTED", DISCONNECTED = "DISCONNECTED", BANNED = "BANNED", THROTTLED = "THROTTLED", ERROR = "ERROR" } /** * Message type enumeration */ declare enum MessageType { TEXT = "TEXT", IMAGE = "IMAGE", VIDEO = "VIDEO", AUDIO = "AUDIO", DOCUMENT = "DOCUMENT", LOCATION = "LOCATION", CONTACT = "CONTACT", REACTION = "REACTION", STICKER = "STICKER", POLL = "POLL", POLL_UPDATE = "POLL_UPDATE" } /** * Event type enumeration */ declare enum EventType { MESSAGE_RECEIVED = "MESSAGE_RECEIVED", MESSAGE_SENT = "MESSAGE_SENT", MESSAGE_DELIVERED = "MESSAGE_DELIVERED", MESSAGE_READ = "MESSAGE_READ", SESSION_CONNECTED = "SESSION_CONNECTED", SESSION_DISCONNECTED = "SESSION_DISCONNECTED", SESSION_QR = "SESSION_QR", SESSION_ERROR = "SESSION_ERROR", GROUP_JOIN = "GROUP_JOIN", GROUP_LEAVE = "GROUP_LEAVE", PRESENCE_UPDATE = "PRESENCE_UPDATE", REACHOUT_TIMELOCK = "REACHOUT_TIMELOCK", BAN_RISK_HIGH = "BAN_RISK_HIGH" } /** * Provider type enumeration */ declare enum ProviderType { BAILEYS = "BAILEYS", WHATSMEOW = "WHATSMEOW", CLOUD_API = "CLOUD_API" } /** * Session metadata interface */ interface SessionMetadata { /** Organization ID (for multi-tenant applications) */ orgId?: string; /** Application-specific data */ [key: string]: unknown; } /** * Reachout timelock state from WhatsApp */ interface ReachoutTimelockInfo { isActive: boolean; enforcementType?: string; expiresAt?: Date; /** Whether new-contact messages are currently blocked */ newContactsBlocked: boolean; } /** * Session state */ interface Session { /** Unique session identifier */ id: string; /** WhatsApp phone number (with country code, e.g., "27821234567") */ phone?: string; /** Current session status */ status: SessionStatus; /** Provider type */ provider: ProviderType; /** Organization ID */ orgId?: string; /** Timestamp when session connected */ connectedAt?: Date; /** Timestamp when session was created */ createdAt: Date; /** Timestamp of last activity */ lastActivityAt?: Date; /** Additional metadata */ metadata?: SessionMetadata; } /** * Quoted/replied message reference */ interface QuotedMessage { /** Message ID being quoted */ id: string; /** Sender of quoted message */ from: string; /** Content of quoted message */ content: string; } /** * Normalized message format */ interface Message { /** Unique message identifier */ id: string; /** Sender phone number */ from: string; /** Recipient phone number or group ID */ to: string; /** Message type */ type: MessageType; /** Message content (text, caption, or serialized data) */ content: string; /** Timestamp when message was created */ timestamp: Date; /** Whether message is from a group */ isGroup: boolean; /** Group ID if isGroup is true */ groupId?: string; /** Quoted/replied message */ quotedMessage?: QuotedMessage; /** Media URL (for IMAGE, VIDEO, AUDIO, DOCUMENT) */ mediaUrl?: string; /** Media MIME type */ mediaMimeType?: string; /** Additional provider-specific data */ raw?: unknown; } /** * WaSP event */ interface WaspEvent { /** Event type */ type: EventType; /** Session ID that triggered the event */ sessionId: string; /** Event timestamp */ timestamp: Date; /** Event-specific data */ data: T; } /** * Message send options */ interface SendMessageOptions { /** Message to quote/reply to */ quoted?: string; /** Priority (higher = sent first) */ priority?: number; /** Skip anti-ban queue (use with caution) */ immediate?: boolean; /** Media URL or buffer */ media?: string | Buffer; /** Media MIME type */ mediaMimeType?: string; } /** * Queue configuration options */ interface QueueOptions { /** Minimum delay between messages (ms) */ minDelay: number; /** Maximum delay between messages (ms) */ maxDelay: number; /** Maximum concurrent message processing */ maxConcurrent: number; /** Enable priority lanes (priority messages skip delay) */ priorityLanes: boolean; /** Maximum queue size per session (0 = unlimited) */ maxQueueSize?: number; } /** * Provider interface - must be implemented by all WhatsApp libraries */ interface Provider { /** Provider type */ readonly type: ProviderType; /** Event emitter for provider events */ readonly events: EventEmitter; /** * Connect to WhatsApp * @param sessionId Session identifier * @param options Provider-specific connection options */ connect(sessionId: string, options?: unknown): Promise; /** * Disconnect from WhatsApp */ disconnect(): Promise; /** * Send a message * @param to Recipient phone number or group ID * @param content Message content * @param options Send options */ sendMessage(to: string, content: string, options?: SendMessageOptions): Promise; /** * Send a reaction to a message * @param messageId Message ID to react to * @param emoji Reaction emoji */ sendReaction(messageId: string, emoji: string): Promise; /** * Get QR code for authentication (if applicable) */ getQR?(): Promise; /** * Check if provider is connected */ isConnected(): boolean; /** * Get session phone number */ getPhoneNumber(): string | null; } /** * Session store interface - CRUD operations for session data */ interface SessionStore { /** * Save session state * @param session Session to save */ save(session: Session): Promise; /** * Load session state * @param id Session ID */ load(id: string): Promise; /** * Delete session state * @param id Session ID */ delete(id: string): Promise; /** * List all sessions * @param filter Optional filter criteria * @param limit Optional limit on number of results * @param offset Optional offset for pagination */ list(filter?: Partial, limit?: number, offset?: number): Promise; /** * Check if session exists * @param id Session ID */ exists(id: string): Promise; /** * Update session metadata * @param id Session ID * @param updates Partial session updates */ update(id: string, updates: Partial): Promise; } /** * Store interface - pluggable session storage * @deprecated Use SessionStore instead (backward compatibility alias) */ type Store = SessionStore; /** * Credential store interface - auth tokens, device credentials, encrypted keys */ interface CredentialStore { /** * Save a credential * @param sessionId Session ID * @param key Credential key (e.g., 'auth-token', 'device-key') * @param value Credential value (string or Buffer) */ saveCredential(sessionId: string, key: string, value: string | Buffer): Promise; /** * Load a credential * @param sessionId Session ID * @param key Credential key * @returns Credential value or null if not found */ loadCredential(sessionId: string, key: string): Promise; /** * Delete a credential * @param sessionId Session ID * @param key Credential key */ deleteCredential(sessionId: string, key: string): Promise; /** * List all credential keys for a session * @param sessionId Session ID * @returns Array of credential keys */ listCredentialKeys(sessionId: string): Promise; /** * Clear all credentials for a session * @param sessionId Session ID */ clearCredentials(sessionId: string): Promise; } /** * Cache store interface - namespaced ephemeral data with TTL support */ interface CacheStore { /** * Get cached value * @param namespace Cache namespace (e.g., 'group', 'device') * @param key Cache key * @returns Cached value or null if not found/expired */ getCached(namespace: string, key: string): Promise; /** * Set cached value * @param namespace Cache namespace * @param key Cache key * @param value Value to cache * @param ttlMs Optional TTL in milliseconds (undefined = no expiry) */ setCached(namespace: string, key: string, value: T, ttlMs?: number): Promise; /** * Delete cached value * @param namespace Cache namespace * @param key Cache key */ deleteCached(namespace: string, key: string): Promise; /** * Clear all cached values in a namespace * @param namespace Cache namespace */ clearCache(namespace: string): Promise; } /** * Metrics store interface - health stats and per-session counters */ interface MetricsStore { /** * Increment a metric counter * @param sessionId Session ID * @param metric Metric name * @param delta Amount to increment by (default: 1) */ increment(sessionId: string, metric: string, delta?: number): Promise; /** * Get a metric value * @param sessionId Session ID * @param metric Metric name * @returns Metric value (0 if not found) */ get(sessionId: string, metric: string): Promise; /** * Get all metrics for a session * @param sessionId Session ID * @returns Record of metric names to values */ getAll(sessionId: string): Promise>; /** * Reset metrics for a session * @param sessionId Session ID * @param metric Optional specific metric to reset (undefined = reset all) */ reset(sessionId: string, metric?: string): Promise; } /** * Backend interface - composes all four domain stores */ interface Backend extends SessionStore, CredentialStore, CacheStore, MetricsStore { } /** * Webhook configuration */ interface WebhookConfig { /** Webhook URL to POST events to */ url: string; /** HMAC signing secret (optional) */ secret?: string; /** Event filter - which events to send (default: all) */ events?: EventType[]; /** Number of retry attempts on failure (default: 3) */ retries?: number; /** Request timeout in ms (default: 5000) */ timeout?: number; } /** * WaSP configuration */ interface WaspConfig { /** Session store (defaults to in-memory) */ store?: SessionStore; /** Full backend implementation (overrides individual stores) */ backend?: Backend; /** Credential store (auth tokens, device keys) */ credentialStore?: CredentialStore; /** Cache store (namespaced ephemeral data) */ cacheStore?: CacheStore; /** Metrics store (session counters) */ metricsStore?: MetricsStore; /** Message queue options */ queue?: Partial; /** Default provider options */ defaultProvider?: ProviderType; /** Enable debug logging */ debug?: boolean; /** Custom logger */ logger?: { debug: (message: string, ...args: unknown[]) => void; info: (message: string, ...args: unknown[]) => void; warn: (message: string, ...args: unknown[]) => void; error: (message: string, ...args: unknown[]) => void; }; /** Webhook configurations */ webhooks?: WebhookConfig[]; /** Ban risk detector configuration */ banRiskDetector?: { enabled?: boolean; checkInterval?: number; rapidRestartThreshold?: number; highErrorRatePercent?: number; disconnectThreshold?: number; qrRescanThreshold?: number; }; } /** * Middleware function type */ interface Middleware { (event: WaspEvent, next: () => Promise): Promise; } /** * Message queue item */ interface QueueItem { /** Session ID */ sessionId: string; /** Recipient */ to: string; /** Message content */ content: string; /** Send options */ options?: SendMessageOptions; /** Promise resolve - can return void or Promise */ resolve: (message?: Message) => void | Promise; /** Promise reject */ reject: (error: Error) => void; /** Timestamp when queued */ queuedAt: Date; /** Priority */ priority: number; } /** * Clock sync sample for RTT-adjusted time synchronization */ interface ClockSyncSample { /** Local timestamp when request was sent (ms since epoch) */ localSentAt: number; /** Local timestamp when response was received (ms since epoch) */ localReceivedAt: number; /** Server timestamp reported in response (ms since epoch) */ serverTimestamp: number; } /** * Clock sync statistics */ interface ClockSyncStats { /** Estimated clock skew in ms (negative = local ahead, positive = local behind) */ skewMs: number; /** Estimated round-trip time in ms */ estimatedRttMs: number; /** Number of samples collected */ sampleCount: number; /** Confidence level based on sample count and variance */ confidence: 'low' | 'medium' | 'high'; /** Timestamp when stats were last updated */ lastUpdatedAt: number; } /** * Clock sync configuration */ interface ClockSyncConfig { /** Rolling window size for samples (default: 10) */ sampleWindowSize?: number; /** Minimum RTT samples before trusting skew (default: 3) */ minRttSamples?: number; } /** * Health/stats information */ interface HealthStats { /** Uptime in milliseconds */ uptime: number; /** Session statistics */ sessions: { total: number; connected: number; disconnected: number; }; /** Message statistics */ messages: { sent: number; received: number; }; /** Memory usage */ memory: { heapUsed: number; heapTotal: number; }; /** Clock sync statistics */ clockSync?: ClockSyncStats; /** Cache statistics */ cache?: { size: number; }; /** Credential count */ credentials?: { total: number; }; } /** * TC Token for error 463 prevention */ interface TcToken$1 { /** Token buffer (raw bytes) */ token: Buffer; /** Receiver timestamp (when token was issued) */ timestamp: number; /** Sender timestamp (when we sent the token) */ senderTimestamp?: number; } /** * TC Token manager configuration */ interface TcTokenConfig$1 { /** Rolling bucket size in seconds (default: 7 days) */ bucketSize?: number; /** Number of rolling buckets (default: 4) */ numBuckets?: number; /** Sender mode bucket size in seconds (default: 7 days) */ senderBucketSize?: number; /** Sender mode number of buckets (default: 4) */ senderNumBuckets?: number; /** Pruning interval in ms (default: 24h) */ pruneInterval?: number; /** CS token LRU cache size (default: 5) */ cstokenCacheSize?: number; /** Disable TC token feature entirely */ disabled?: boolean; } /** * Clock synchronization utility * * RTT-adjusted clock sync inspired by jlucaso1/whatsapp-rust's unified_session approach. * Calculates server-to-local time skew using rolling median to resist outliers. */ /** * Clock synchronization manager * * Maintains a rolling window of RTT samples to estimate clock skew between * local and server time. Uses median of skew measurements to resist outliers. * * @example * ```typescript * const clockSync = new ClockSync({ sampleWindowSize: 10 }); * * // When you get a server timestamp from a request/response round-trip: * clockSync.recordSample({ * localSentAt: Date.now(), * localReceivedAt: Date.now() + 100, * serverTimestamp: serverTime * }); * * // Adjust local time to server time: * const serverTime = clockSync.toServerTime(Date.now()); * * // Get stats: * const stats = clockSync.getStats(); * console.log(`Skew: ${stats.skewMs}ms, Confidence: ${stats.confidence}`); * ``` */ declare class ClockSync { private config; private samples; private lastUpdatedAt; constructor(config?: ClockSyncConfig); /** * Record a new clock sync sample * * Calculates RTT and skew from the round-trip, adds to rolling window. * * @param sample Clock sync sample */ recordSample(sample: ClockSyncSample): void; /** * Get estimated clock skew in milliseconds * * Returns median skew from all samples (resists outliers). * Returns 0 if insufficient samples. * * @returns Skew in ms (negative = local ahead, positive = local behind) */ getSkewMs(): number; /** * Adjust local timestamp to server-aligned time * * @param localMs Local timestamp in milliseconds * @returns Server-aligned timestamp */ toServerTime(localMs: number): number; /** * Adjust server timestamp to local-aligned time * * @param serverMs Server timestamp in milliseconds * @returns Local-aligned timestamp */ toLocalTime(serverMs: number): number; /** * Get clock sync statistics * * @returns Current statistics */ getStats(): ClockSyncStats; /** * Reset all samples */ reset(): void; /** * Calculate median of an array */ private median; /** * Calculate standard deviation of an array */ private standardDeviation; } /** * Ban Risk Detection * * Monitors session health signals and emits ban_risk_high events * when elevated ban risk is detected. */ /** * Ban risk level */ type BanRiskLevel = 'medium' | 'high' | 'critical'; /** * Ban risk event data */ interface BanRiskEvent { sessionId: string; riskLevel: BanRiskLevel; signals: string[]; recommendation: string; timestamp: Date; } /** * Ban risk detector configuration */ interface BanRiskConfig { /** Check interval in ms (default: 30000 = 30s) */ checkInterval?: number; /** Enable detector (default: true) */ enabled?: boolean; /** Rapid restart threshold (restarts in 5min window, default: 3) */ rapidRestartThreshold?: number; /** High error rate percentage (default: 10%) */ highErrorRatePercent?: number; /** Disconnect threshold (disconnects in 10min window, default: 5) */ disconnectThreshold?: number; /** QR rescan threshold (rescans in 10min window, default: 3) */ qrRescanThreshold?: number; } /** * Ban risk detector * * Analyzes session metrics and cache data to detect ban risk patterns. * Emits ban_risk_high events when thresholds are exceeded. */ declare class BanRiskDetector { private config; private metrics; private cache; private checkTimer; constructor(metrics: MetricsStore, cache: CacheStore, config?: BanRiskConfig); /** * Start periodic ban risk checks * * @param sessionIds Array of session IDs to monitor * @param onRiskDetected Callback when risk is detected */ start(sessionIds: () => string[], onRiskDetected: (event: BanRiskEvent) => void): void; /** * Stop periodic checks */ stop(): void; /** * Check a specific session for ban risk * * @param sessionId Session ID to check * @returns BanRiskEvent if risk detected, null otherwise */ checkSession(sessionId: string): Promise; /** * Get count of recent events from time-series cache */ private getRecentCount; /** * Calculate error rate based on recent message metrics */ private getErrorRate; /** * Generate human-readable recommendation */ private generateRecommendation; /** * Record a restart event */ recordRestart(sessionId: string): Promise; /** * Record a disconnect event */ recordDisconnect(sessionId: string): Promise; /** * Record a QR scan event */ recordQRScan(sessionId: string): Promise; /** * Record a rate limit error */ recordRateLimitError(sessionId: string): Promise; /** * Record an account reachout restricted error */ recordReachoutRestricted(sessionId: string, expiresAt?: Date): Promise; /** * Record a message error */ recordMessageError(sessionId: string): Promise; /** * Record a generic event to time-series cache */ private recordEvent; } /** * WaSP - WhatsApp Session Protocol * * Core class that manages WhatsApp sessions, message routing, * event handling, and multi-tenant isolation. */ /** * WaSP - WhatsApp Session Protocol * * Main class for managing WhatsApp sessions and message routing. * * @example * ```typescript * import { WaSP } from '@wasp/core'; * * const wasp = new WaSP({ * debug: true, * queue: { * minDelay: 3000, * maxDelay: 7000, * }, * }); * * // Create session * const session = await wasp.createSession('my-session', 'BAILEYS'); * * // Listen for events * wasp.on('MESSAGE_RECEIVED', (event) => { * console.log('New message:', event.data); * }); * * // Send message * await wasp.sendMessage('my-session', '27821234567', 'Hello!'); * ``` */ declare class WaSP extends EventEmitter { private config; private sessionStore; private credStore; private cacheStoreImpl; private metricsStoreImpl; private clockSyncImpl; private banRiskDetectorImpl; private queue; private activeSessions; private middlewares; private webhookManager; private startTime; private messageStats; constructor(config?: WaspConfig); /** * Create and connect a new session * * @param id Unique session identifier * @param providerType Provider to use (BAILEYS, WHATSMEOW, CLOUD_API) * @param options Provider-specific connection options * @returns Created session * * @example * ```typescript * const session = await wasp.createSession('org-123-user-456', 'BAILEYS', { * authDir: './auth_states', * }); * ``` */ createSession(id: string, providerType?: ProviderType, options?: { orgId?: string; metadata?: Record; }): Promise; /** * Destroy a session * * Disconnects and removes all session data. * * @param id Session ID */ destroySession(id: string): Promise; /** * Get session by ID * * @param id Session ID * @returns Session or null if not found */ getSession(id: string): Promise; /** * List all sessions * * @param filter Optional filter criteria * @returns Array of sessions */ listSessions(filter?: Partial): Promise; /** * Send a message * * Messages are queued with anti-ban delays unless immediate option is set. * * @param sessionId Session ID to send from * @param to Recipient phone number or group ID * @param content Message content * @param options Send options * @returns Sent message * * @example * ```typescript * // Regular message * await wasp.sendMessage('session-1', '27821234567', 'Hello!'); * * // Priority message (reduced delay) * await wasp.sendMessage('session-1', '27821234567', 'URGENT', { priority: 10 }); * * // Immediate message (skip queue) * await wasp.sendMessage('session-1', '27821234567', 'Alert', { immediate: true }); * ``` */ sendMessage(sessionId: string, to: string, content: string, options?: SendMessageOptions): Promise; /** * Subscribe to events * * @param event Event type or '*' for all events * @param handler Event handler * * @example * ```typescript * wasp.on('MESSAGE_RECEIVED', (event) => { * console.log('New message:', event.data); * }); * * wasp.on('*', (event) => { * console.log('Any event:', event.type); * }); * ``` */ on(event: EventType | '*', handler: (event: WaspEvent) => void): this; /** * Add middleware * * Middleware is executed in order for each event. * * @param middleware Middleware function * * @example * ```typescript * import { logger, autoReconnect } from '@wasp/core/middleware'; * * wasp.use(logger()); * wasp.use(autoReconnect({ maxAttempts: 5 })); * ``` */ use(middleware: Middleware): this; /** * Get queue statistics */ getQueueStats(): { totalQueued: number; sessionCount: number; processingCount: number; }; /** * Get session count */ getSessionCount(): number; /** * Get provider for a specific session * * @param sessionId Session ID * @returns Provider instance or null if session not found */ getProvider(sessionId: string): Provider | null; /** * Get all active session IDs * * @returns Array of session IDs */ getSessions(): string[]; /** * Get session store */ get sessions(): SessionStore; /** * Get credential store */ get credentials(): CredentialStore; /** * Get cache store */ get cache(): CacheStore; /** * Get metrics store */ get metrics(): MetricsStore; /** * Get clock sync */ get clock(): ClockSync; /** * Get ban risk detector */ get banRiskDetector(): BanRiskDetector; /** * Get health and statistics * * Returns current system health including uptime, session counts, * message statistics, and memory usage. * * @returns Health stats * * @example * ```typescript * const health = wasp.getHealth(); * console.log('Uptime:', health.uptime); * console.log('Connected sessions:', health.sessions.connected); * console.log('Messages sent:', health.messages.sent); * ``` */ getHealth(): HealthStats; /** * Create provider instance */ private createProvider; /** * Setup provider event handlers */ private setupProviderEvents; /** * Setup queue event forwarding */ private setupQueueEvents; /** * Emit event through middleware chain */ private emitEvent; /** * Internal logger */ private log; } /** * WaSP Admin Router * * Optional Express router for managing WaSP sessions via HTTP. * Provides list / connect / disconnect / qr endpoints per session. * * @example * ```typescript * import express from 'express'; * import { WaSP, createAdminRouter } from 'wasp-protocol'; * * const app = express(); * const wasp = new WaSP(config); * * app.use('/wa-admin', createAdminRouter(wasp, { token: process.env.ADMIN_TOKEN })); * ``` */ interface Req { params: Record; body?: Record; headers: Record; } interface Res { status(code: number): Res; json(body: unknown): void; } type Next = () => void; type Handler = (req: Req, res: Res, next: Next) => void | Promise; interface ExpressRouter { use(handler: Handler): ExpressRouter; get(path: string, handler: Handler): ExpressRouter; post(path: string, handler: Handler): ExpressRouter; } interface AdminRouterOptions { /** Bearer token for auth. If omitted no auth is applied — never expose publicly without one. */ token?: string; /** Default provider type for new sessions. Defaults to 'BAILEYS'. */ defaultProvider?: ProviderType; /** Extra options forwarded to wasp.createSession(). */ sessionOptions?: Record; } declare function createAdminRouter(wasp: WaSP, options?: AdminRouterOptions): ExpressRouter; /** * Anti-ban message queue * * Implements human-like delays, rate limiting, and priority lanes * to prevent WhatsApp from flagging accounts as spam/bots. */ /** * Anti-ban message queue * * Queues messages per session with human-like random delays * to avoid WhatsApp rate limiting and ban detection. */ declare class MessageQueue extends EventEmitter { private options; private queues; private processing; private lastSent; private timelocked; private sleepAbortHandlers; constructor(options?: Partial); /** * Add message to queue * * @param item Queue item * @returns Promise that resolves when message is sent */ enqueue(item: QueueItem): Promise; /** * Process queue for a session * * @param sessionId Session ID */ private processQueue; /** * Calculate delay before sending next message * * @param sessionId Session ID * @param item Queue item * @returns Delay in milliseconds */ private calculateDelay; /** * Generate random delay with human-like distribution * * Uses a slight bias toward the middle of the range * to mimic human typing patterns. * * @param min Minimum delay (ms) * @param max Maximum delay (ms) * @returns Random delay */ private randomDelay; /** * Sleep for specified duration, interruptible via interrupt() */ private sleep; /** * Interrupt all pending and in-flight messages for a session. * * Wakes any sleeping processQueue, drains the queue (rejecting all items), * and emits 'interrupted'. Use for /stop or bid-conflict resolution. */ interrupt(sessionId: string): void; /** * Bypass the queue and execute a QueueItem immediately. * * For priority commands (/stop, /approve, /deny) that must not wait * behind pending messages. Does not affect the existing queue. */ bypass(sessionId: string, item: QueueItem): Promise; /** * Mark a session as timelocked — new-contact messages will be held */ setTimelocked(sessionId: string, expiresAt?: Date, enforcementType?: string): void; /** * Clear timelock for a session */ clearTimelocked(sessionId: string): void; /** * Check if a session is timelocked */ isSessionTimelocked(sessionId: string): boolean; /** * Get queue size for a session * * @param sessionId Session ID * @returns Queue size */ getQueueSize(sessionId: string): number; /** * Clear queue for a session * * @param sessionId Session ID */ clearQueue(sessionId: string): void; /** * Clear all queues */ clearAll(): void; /** * Get statistics */ getStats(): { totalQueued: number; sessionCount: number; processingCount: number; }; } /** * Webhook delivery system * * Handles POST delivery of WaSP events to configured webhook URLs * with retry logic and HMAC signature verification. */ declare class WebhookManager { private webhooks; private logger?; constructor(webhooks: WebhookConfig[], logger?: any); /** * Deliver event to all configured webhooks * Fire-and-forget with retry logic */ deliverEvent(event: WaspEvent): Promise; /** * Deliver event to a specific webhook with retry logic */ private deliverToWebhook; /** * POST event to webhook URL with HMAC signature */ private postToWebhook; } /** * wrapSocket — WaSP Socket Wrapper * * Wraps an existing Baileys socket's sendMessage with WaSP's anti-ban queue. * Use this when you have an existing Baileys socket (e.g. from OpenClaw or * another agent runtime) and want WaSP's queue without replacing session management. * * @example * ```ts * import { wrapSocket } from 'wasp-protocol'; * * // After your existing Baileys/OpenClaw socket is created: * const wrappedSock = wrapSocket(sock, 'my-session-id'); * * // Use exactly like normal sock — delays + anti-ban applied automatically * await wrappedSock.sendMessage(jid, { text: 'Hello!' }); * ``` */ interface WrappedSocket { sendMessage: (...args: unknown[]) => Promise; /** Access the underlying WaSP queue for priority/config */ _waspQueue: MessageQueue; /** Access the original unwrapped socket */ _originalSocket: unknown; } /** * Wrap an existing Baileys socket with WaSP's anti-ban message queue. * * @param sock - Existing Baileys socket (from makeWASocket or OpenClaw) * @param sessionId - Unique session identifier for queue tracking * @param queueOptions - Optional WaSP queue configuration * @returns Wrapped socket with WaSP queue applied to sendMessage */ declare function wrapSocket Promise; }>(sock: T, sessionId: string, queueOptions?: Partial): T & WrappedSocket; /** * In-memory session store * * Simple Map-based store for development and testing. * NOT recommended for production - sessions are lost on restart. */ /** * In-memory session store (implements full Backend interface) */ declare class MemoryStore implements Backend { private sessions; private credentials; private cache; private metrics; private cacheSweepInterval; constructor(); /** * Save session state */ save(session: Session): Promise; /** * Load session state */ load(id: string): Promise; /** * Delete session state */ delete(id: string): Promise; /** * List all sessions */ list(filter?: Partial, limit?: number, offset?: number): Promise; /** * Check if session exists */ exists(id: string): Promise; /** * Update session metadata */ update(id: string, updates: Partial): Promise; /** * Clear all sessions (useful for testing) */ clear(): Promise; /** * Get session count */ get size(): number; /** * Save a credential */ saveCredential(sessionId: string, key: string, value: string | Buffer): Promise; /** * Load a credential */ loadCredential(sessionId: string, key: string): Promise; /** * Delete a credential */ deleteCredential(sessionId: string, key: string): Promise; /** * List all credential keys for a session */ listCredentialKeys(sessionId: string): Promise; /** * Clear all credentials for a session */ clearCredentials(sessionId: string): Promise; /** * Get cached value (best-effort, never throws) */ getCached(namespace: string, key: string): Promise; /** * Set cached value (best-effort, never throws) */ setCached(namespace: string, key: string, value: T, ttlMs?: number): Promise; /** * Delete cached value */ deleteCached(namespace: string, key: string): Promise; /** * Clear all cached values in a namespace */ clearCache(namespace: string): Promise; /** * Get cache size */ getCacheSize(): number; /** * Background sweep for expired cache entries */ private sweepExpiredCache; /** * Increment a metric counter */ increment(sessionId: string, metric: string, delta?: number): Promise; /** * Get a metric value */ get(sessionId: string, metric: string): Promise; /** * Get all metrics for a session */ getAll(sessionId: string): Promise>; /** * Reset metrics for a session */ reset(sessionId: string, metric?: string): Promise; /** * Get total credential count across all sessions */ getTotalCredentialCount(): number; /** * Cleanup on shutdown */ destroy(): void; } /** * Redis session store * * Persistent session storage using Redis. * Recommended for production multi-instance deployments. */ /** * Redis store configuration */ interface RedisStoreConfig { /** Redis host */ host?: string; /** Redis port */ port?: number; /** Redis password */ password?: string; /** Redis database number */ db?: number; /** Key prefix */ keyPrefix?: string; /** Session TTL (seconds) - 0 for no expiry */ ttl?: number; } /** * Redis session store * * Uses ioredis for Redis connectivity. * Sessions are stored as JSON with optional TTL. * Uses SCAN for listing (not KEYS) to avoid blocking. * * @example * ```typescript * import { RedisStore } from '@wasp/core/stores/redis'; * * const store = new RedisStore({ * host: 'localhost', * port: 6379, * keyPrefix: 'wasp:session:', * ttl: 86400, // 24 hours * }); * ``` */ declare class RedisStore implements Backend { private redis; private config; private initPromise; constructor(config?: RedisStoreConfig); /** * Initialize Redis client (dynamic import for optional peer dependency) */ private initializeRedis; /** * Ensure Redis is initialized */ private ensureInitialized; /** * Get Redis key with prefix */ private getKey; /** * Serialize session to JSON (handle Date fields) */ private serialize; /** * Deserialize session from JSON (restore Date fields) */ private deserialize; /** * Save session to Redis */ save(session: Session): Promise; /** * Load session from Redis */ load(id: string): Promise; /** * Delete session from Redis */ delete(id: string): Promise; /** * List all sessions matching filter * Uses SCAN to avoid blocking (not KEYS) */ list(filter?: Partial, limit?: number, offset?: number): Promise; /** * Check if session exists */ exists(id: string): Promise; /** * Update session metadata */ update(id: string, updates: Partial): Promise; /** * Close Redis connection */ close(): Promise; saveCredential(sessionId: string, key: string, value: string | Buffer): Promise; loadCredential(sessionId: string, key: string): Promise; deleteCredential(sessionId: string, key: string): Promise; listCredentialKeys(sessionId: string): Promise; clearCredentials(sessionId: string): Promise; getCached(namespace: string, key: string): Promise; setCached(namespace: string, key: string, value: T, ttlMs?: number): Promise; deleteCached(namespace: string, key: string): Promise; clearCache(namespace: string): Promise; increment(sessionId: string, metric: string, delta?: number): Promise; get(sessionId: string, metric: string): Promise; getAll(sessionId: string): Promise>; reset(sessionId: string, metric?: string): Promise; /** * Get total credential count across all sessions */ getTotalCredentialCount(): Promise; /** * Get cache size */ getCacheSize(): Promise; } /** * PostgreSQL session store * * Persistent session storage using PostgreSQL. * Recommended for production when you need relational queries. */ /** * PostgreSQL store configuration */ interface PostgresStoreConfig { /** PostgreSQL connection string */ connectionString?: string; /** Table name for sessions */ tableName?: string; /** Table name prefix for all tables (credentials, cache, metrics) */ tablePrefix?: string; /** Auto-create table if not exists */ autoCreate?: boolean; } /** * PostgreSQL session store * * Uses pg connection pool for optimal performance. * Auto-creates table schema if autoCreate is enabled. * * @example * ```typescript * import { PostgresStore } from '@wasp/core/stores/postgres'; * * const store = new PostgresStore({ * connectionString: 'postgresql://user:pass@localhost/wasp', * tableName: 'wasp_sessions', * autoCreate: true, * }); * ``` * * Table schema: * ```sql * CREATE TABLE wasp_sessions ( * id VARCHAR(255) PRIMARY KEY, * phone VARCHAR(50), * status VARCHAR(50) NOT NULL, * provider VARCHAR(50) NOT NULL, * org_id VARCHAR(255), * connected_at TIMESTAMP, * created_at TIMESTAMP NOT NULL, * last_activity_at TIMESTAMP, * metadata JSONB * ); * CREATE INDEX idx_wasp_sessions_org_id ON wasp_sessions(org_id); * CREATE INDEX idx_wasp_sessions_status ON wasp_sessions(status); * ``` */ declare class PostgresStore implements Backend { private pool; private config; private initPromise; private credentialsTable; private cacheTable; private metricsTable; constructor(config?: PostgresStoreConfig); /** * Initialize PostgreSQL connection pool */ private initializePool; /** * Ensure pool is initialized */ private ensureInitialized; /** * Create table and indexes if they don't exist */ private createTableIfNotExists; /** * Save session (upsert) */ save(session: Session): Promise; /** * Load session by ID */ load(id: string): Promise; /** * Delete session */ delete(id: string): Promise; /** * List sessions with optional filter */ list(filter?: Partial, limit?: number, offset?: number): Promise; /** * Check if session exists */ exists(id: string): Promise; /** * Update session */ update(id: string, updates: Partial): Promise; /** * Convert database row to Session object */ private rowToSession; /** * Close connection pool */ close(): Promise; saveCredential(sessionId: string, key: string, value: string | Buffer): Promise; loadCredential(sessionId: string, key: string): Promise; deleteCredential(sessionId: string, key: string): Promise; listCredentialKeys(sessionId: string): Promise; clearCredentials(sessionId: string): Promise; getCached(namespace: string, key: string): Promise; setCached(namespace: string, key: string, value: T, ttlMs?: number): Promise; deleteCached(namespace: string, key: string): Promise; clearCache(namespace: string): Promise; increment(sessionId: string, metric: string, delta?: number): Promise; get(sessionId: string, metric: string): Promise; getAll(sessionId: string): Promise>; reset(sessionId: string, metric?: string): Promise; /** * Get total credential count across all sessions */ getTotalCredentialCount(): Promise; /** * Get cache size */ getCacheSize(): Promise; } type BaileysSocket = any; /** * Baileys provider options */ interface BaileysProviderOptions { /** Authentication state directory */ authDir?: string; /** Print QR to console */ printQR?: boolean; /** Browser metadata [name, description, version] */ browser?: [string, string, string]; /** Pino logger instance */ logger?: any; /** Proxy URL (SOCKS5) */ proxyUrl?: string; /** Maximum reconnection attempts (only used when internalReconnect=true) */ maxReconnectAttempts?: number; /** * If true, BaileysProvider auto-reconnects internally via setTimeout on * recoverable close events. If false (default), the provider always emits * 'disconnected' on close and lets the consumer (e.g. baileys-keep-alive) * own the reconnect lifecycle. Recommended: false — single source of truth * avoids racing reconnect attempts. */ internalReconnect?: boolean; /** Allowed media directory (for file path security) */ allowedMediaDir?: string; /** TC token configuration for error 463 prevention */ tcTokenConfig?: TcTokenConfig$1; } /** * Baileys provider * * Implements the Provider interface using @whiskeysockets/baileys. * Includes production-ready patterns: exponential backoff, Bad MAC handling, * proper disconnect detection, and memory leak mitigation. * * @example * ```typescript * import { BaileysProvider } from '@wasp/core/providers/baileys'; * * const provider = new BaileysProvider({ * authDir: './auth_states', * printQR: true, * }); * * await provider.connect('session-1'); * await provider.sendMessage('27821234567@s.whatsapp.net', 'Hello!'); * ``` */ declare class BaileysProvider implements Provider { readonly type: ProviderType; readonly events: EventEmitter; private socket; private phoneNumber; private qrCode; private options; private currentSessionId; private reconnectAttempts; private isConnecting; private isManualDisconnect; private _connected; private timelockState; private tcTokenManager; private processedMessages; private readonly MAX_PROCESSED_MESSAGES; constructor(options?: BaileysProviderOptions); /** * Calculate reconnection delay with exponential backoff and jitter */ private getReconnectDelay; /** * Connect to WhatsApp using Baileys */ connect(sessionId: string, _options?: unknown): Promise; /** * Recreate the underlying Baileys socket using existing auth state and * return it. Intended for use by external reconnect managers * (e.g. baileys-keep-alive's reconnectFactory) when internalReconnect is off. */ recreateSocket(): Promise; /** * Disconnect from WhatsApp */ disconnect(): Promise; /** * Send a message */ sendMessage(to: string, content: string, options?: SendMessageOptions): Promise; /** * Send a reaction */ sendReaction(_messageId: string, _emoji: string): Promise; /** * Get QR code for authentication */ getQR(): Promise; /** * Check if connected */ isConnected(): boolean; /** * Get session phone number */ getPhoneNumber(): string | null; /** * Get current reachout timelock state */ getTimelockState(): { isActive: boolean; enforcementType?: string; expiresAt?: Date; } | null; /** * Get raw WASocket instance * * Useful for advanced operations like media downloads, * presence updates, group operations, etc. * * @returns WASocket instance or null if not connected */ getSocket(): BaileysSocket | null; /** * Normalize Baileys message to WaSP format */ private normalizeMessage; /** * Format phone number to WhatsApp JID */ private formatJid; /** * Issue privacy token to recipient (fire-and-forget) * * @param jid Recipient JID */ private issuePrivacyToken; } /** * TC Token Manager for Error 463 Prevention * * Implements rolling bucket-based TC token management and CS token fallback * to prevent WhatsApp's privacy token errors (error 463). * * Architecture: * - TC tokens: Extracted from history sync and privacy_token notifications * - CS tokens: Computed via HMAC-SHA256(nctSalt, recipientLid) as fallback * - Rolling bucket expiration: Tokens expire after (numBuckets * bucketSize) seconds * - Monotonicity guard: Reject older tokens when newer ones exist * - LRU cache: CS tokens cached for performance (max 5 entries) * * @module baileys-tc-token */ /** TC Token representation */ interface TcToken { /** Token buffer (raw bytes) */ token: Buffer; /** Receiver timestamp (when token was issued) */ timestamp: number; /** Sender timestamp (when we sent the token) */ senderTimestamp?: number; } /** TC Token manager configuration */ interface TcTokenConfig { /** Rolling bucket size in seconds (default: 7 days) */ bucketSize?: number; /** Number of rolling buckets (default: 4) */ numBuckets?: number; /** Sender mode bucket size in seconds (default: 7 days) */ senderBucketSize?: number; /** Sender mode number of buckets (default: 4) */ senderNumBuckets?: number; /** Pruning interval in ms (default: 24h) */ pruneInterval?: number; /** CS token LRU cache size (default: 5) */ cstokenCacheSize?: number; /** Disable TC token feature entirely */ disabled?: boolean; } /** * TC Token Manager * * Manages TC tokens (from history sync / privacy notifications) and CS tokens * (computed via HMAC) for WhatsApp error 463 prevention. */ declare class TcTokenManager { private config; private authDir; private logger?; /** TC token store (JID → token) */ private tokens; /** NCT salt for CS token computation */ private nctSalt; /** CS token LRU cache */ private csTokenCache; /** Pruning interval handle */ private pruneTimer; constructor(options: { authDir: string; sessionId: string; logger?: any; config?: TcTokenConfig; }); /** * Check if a token is expired using rolling bucket logic * * @param timestamp Token timestamp (seconds) * @param mode 'receiver' or 'sender' * @returns true if expired */ isTokenExpired(timestamp: number, mode: 'sender' | 'receiver'): boolean; /** * Get TC token for a JID * * @param jid WhatsApp JID * @returns Token or null if not found / expired */ getTokenForJid(jid: string): TcToken | null; /** * Store a TC token with monotonicity guard * * @param jid WhatsApp JID * @param token Token to store * @returns true if stored, false if rejected (older than existing) */ storeToken(jid: string, token: TcToken): boolean; /** * Compute CS token for a recipient LID * * @param recipientLid Recipient's LID (phone number part of JID) * @returns CS token buffer or null if no nctSalt available */ computeCsToken(recipientLid: string): Buffer | null; /** * Get token nodes for message stanza injection * * @param jid Recipient JID * @returns Array of WABinaryNode-compatible objects or null */ getTokenNodes(jid: string): { tag: string; attrs: Record; content: Buffer; }[] | null; /** * Check if we should send a new privacy token to this JID * * @param jid Recipient JID * @returns true if re-issuance needed */ shouldSendNewToken(jid: string): boolean; /** * Process history sync to extract TC tokens * * @param conversations Array of conversation objects from Baileys */ processHistorySync(conversations: any[]): void; /** * Process privacy_token notification stanza * * @param node Privacy token notification node */ processPrivacyTokenNotification(node: any): void; /** * Set NCT salt for CS token computation * * @param salt NCT salt buffer */ setNctSalt(salt: Buffer): void; /** * Prune expired tokens * * @returns Number of tokens removed */ pruneExpired(): number; /** * Start automatic pruning interval */ startPruning(): void; /** * Stop automatic pruning interval */ stopPruning(): void; /** * Persist tokens to disk */ persist(): Promise; /** * Load tokens from disk */ load(): Promise; /** * Destroy manager (cleanup timers and caches) */ destroy(): void; /** * Get statistics */ getStats(): { totalTokens: number; csTokenCacheSize: number; hasNctSalt: boolean; }; } /** * Meta WhatsApp Cloud API provider implementation * * REST-based provider for Meta's WhatsApp Cloud API. * Enables interactive messages (buttons, lists) that aren't available in Baileys. */ /** * Cloud API provider options */ interface CloudAPIProviderOptions { /** Meta access token (starts with EAA...) */ accessToken: string; /** WhatsApp Business Phone Number ID */ phoneNumberId: string; /** WhatsApp Business Account ID (optional) */ wabaId?: string; /** Graph API version (default: v22.0) */ apiVersion?: string; /** Webhook verify token for incoming webhooks */ webhookVerifyToken?: string; /** Base URL for Graph API (default: https://graph.facebook.com) */ baseUrl?: string; /** Phone number for this account (optional, fetched if not provided) */ phoneNumber?: string; } /** * Interactive button message structure */ interface InteractiveButton { type: 'reply'; reply: { id: string; title: string; }; } /** * Interactive list section */ interface ListSection { title?: string; rows: Array<{ id: string; title: string; description?: string; }>; } /** * Interactive message content */ interface InteractiveMessage { type: 'interactive'; interactive: { type: 'button' | 'list'; header?: { type: 'text' | 'image' | 'video' | 'document'; text?: string; image?: { link: string; }; video?: { link: string; }; document?: { link: string; }; }; body: { text: string; }; footer?: { text: string; }; action: { buttons?: InteractiveButton[]; button?: string; sections?: ListSection[]; }; }; } /** * Template message */ interface TemplateMessage { type: 'template'; template: { name: string; language: { code: string; }; components?: Array<{ type: string; parameters: Array<{ type: string; text?: string; image?: { link: string; }; video?: { link: string; }; document?: { link: string; }; }>; }>; }; } /** * Location message */ interface LocationMessage { type: 'location'; location: { latitude: number; longitude: number; name?: string; address?: string; }; } /** * Contact message */ interface ContactMessage { type: 'contacts'; contacts: Array<{ name: { formatted_name: string; first_name?: string; last_name?: string; }; phones?: Array<{ phone: string; type?: string; }>; emails?: Array<{ email: string; type?: string; }>; }>; } /** * Media message */ interface MediaMessage { type: 'image' | 'video' | 'audio' | 'document'; [key: string]: any; } /** * Reaction message */ interface ReactionMessage { type: 'reaction'; reaction: { message_id: string; emoji: string; }; } /** * Union type for all Cloud API message types */ type CloudAPIMessageContent = string | InteractiveMessage | TemplateMessage | LocationMessage | ContactMessage | MediaMessage | ReactionMessage; /** * Cloud API Provider * * Implements the Provider interface using Meta's WhatsApp Cloud API. * This is a REST-based provider (no WebSocket) that supports advanced * interactive messages like buttons and lists. * * @example * ```typescript * import { CloudAPIProvider } from '@wasp/core/providers/cloud-api'; * * const provider = new CloudAPIProvider({ * accessToken: 'YOUR_ACCESS_TOKEN', * phoneNumberId: '123456789012345', * }); * * await provider.connect('session-1'); * * // Send button message * await provider.sendMessage('15551234567', { * type: 'interactive', * interactive: { * type: 'button', * body: { text: 'Choose an option' }, * action: { * buttons: [ * { type: 'reply', reply: { id: 'yes', title: 'Yes' }}, * { type: 'reply', reply: { id: 'no', title: 'No' }}, * ] * } * } * }); * ``` */ declare class CloudAPIProvider implements Provider { readonly type: ProviderType; readonly events: EventEmitter; private options; private _connected; private currentSessionId; constructor(options: CloudAPIProviderOptions); /** * Connect to WhatsApp Cloud API * * For Cloud API, this verifies the access token by making a test API call */ connect(sessionId: string, _options?: unknown): Promise; /** * Disconnect from Cloud API * * For REST API, this just sets connected state to false */ disconnect(): Promise; /** * Send a message via Cloud API */ sendMessage(to: string, content: string | CloudAPIMessageContent, options?: SendMessageOptions): Promise; /** * Send a reaction */ sendReaction(messageId: string, emoji: string): Promise; /** * Cloud API doesn't use QR codes */ getQR(): Promise; /** * Check if connected */ isConnected(): boolean; /** * Get phone number */ getPhoneNumber(): string | null; /** * Cloud API doesn't have a socket */ getSocket(): null; /** * Verify webhook signature (for incoming webhooks) * * @param req Request object with query parameters * @param verifyToken Your webhook verify token * @returns Challenge string if verification succeeds, null otherwise */ static verifyWebhook(req: { query: Record; }, verifyToken: string): string | null; /** * Parse incoming webhook payload into WaSP messages * * @param body Webhook POST body from Meta * @returns Array of normalized WaSP messages */ static parseWebhook(body: any): Message[]; /** * Normalize a webhook message to WaSP format */ private static normalizeWebhookMessage; /** * Format phone number (remove @ suffix if present) */ private formatPhoneNumber; /** * Extract text content from complex message types */ private extractContentText; /** * Map Cloud API message type to WaSP MessageType */ private mapToMessageType; } /** * Logger middleware * * Logs all WaSP events to console or custom logger. */ interface LoggerOptions { /** Custom log function */ log?: (message: string, ...args: unknown[]) => void; /** Include event data in logs */ includeData?: boolean; } /** * Logger middleware * * Logs all events passing through the pipeline. * * @example * ```typescript * wasp.use(logger()); * * // With custom logger * wasp.use(logger({ * log: (msg) => winston.info(msg), * includeData: true, * })); * ``` */ declare function logger(options?: LoggerOptions): Middleware; /** * Auto-reconnect middleware * * Automatically reconnects sessions on disconnect with exponential backoff. */ interface AutoReconnectOptions { /** Maximum reconnection attempts */ maxAttempts?: number; /** Base delay for exponential backoff (ms) */ baseDelay?: number; } /** * Auto-reconnect middleware * * Handles automatic reconnection on session disconnect. * * @example * ```typescript * wasp.use(autoReconnect({ * maxAttempts: 5, * baseDelay: 1000, // 1s, 2s, 4s, 8s, 16s * })); * ``` */ declare function autoReconnect(options?: AutoReconnectOptions): Middleware; /** * Error handler middleware * * Catches and handles errors in the middleware pipeline. */ type ErrorCallback = (error: Error, event: WaspEvent) => void; /** * Error handler middleware * * Catches errors and passes them to a custom handler. * * @example * ```typescript * wasp.use(errorHandler((error, event) => { * console.error(`Error in ${event.type}:`, error); * Sentry.captureException(error); * })); * ``` */ declare function errorHandler(onError: ErrorCallback): Middleware; /** * Rate limit middleware * * Limits message sending rate per session. */ interface RateLimitOptions { /** Maximum messages per window */ maxMessages?: number; /** Time window in milliseconds */ windowMs?: number; } /** * Rate limit middleware * * Prevents sessions from exceeding message rate limits. * * @example * ```typescript * wasp.use(rateLimit({ * maxMessages: 10, * windowMs: 60000, // 10 messages per minute * })); * ``` */ declare function rateLimit(options?: RateLimitOptions): Middleware; /** * Session key convention: platform:chatType:chatId * * Mirrors the Hermes gateway routing schema for deterministic session lookup * across multi-platform deployments. Always build/parse via these helpers — * never hand-construct the string. * * Examples: * whatsapp:private:27821234567 * whatsapp:group:120363000000000001@g.us * telegram:private:123456789 */ type Platform = 'whatsapp' | 'telegram' | 'instagram' | (string & {}); type ChatType = 'private' | 'group' | 'channel' | (string & {}); interface SessionKeyParts { platform: Platform; chatType: ChatType; chatId: string; } declare function buildSessionKey(platform: Platform, chatType: ChatType, chatId: string): string; declare function parseSessionKey(key: string): SessionKeyParts | null; /** * Custom error types for WaSP * * Type-safe errors for better error handling and debugging. */ /** * Error thrown when a session is not found */ declare class SessionNotFoundError extends Error { constructor(sessionId: string); } /** * Error thrown when attempting operations on a disconnected session */ declare class NotConnectedError extends Error { constructor(message?: string); } /** * Error thrown when a session ID is invalid */ declare class InvalidSessionIdError extends Error { constructor(sessionId: string); } /** * Error thrown when queue is full */ declare class QueueFullError extends Error { constructor(sessionId: string, maxSize: number); } /** * Error thrown when a table name is invalid */ declare class InvalidTableNameError extends Error { constructor(tableName: string); } export { type AdminRouterOptions, type Backend, BaileysProvider, type BaileysProviderOptions, type BanRiskConfig, BanRiskDetector, type BanRiskEvent, type BanRiskLevel, type CacheStore, type ChatType, ClockSync, type ClockSyncConfig, type ClockSyncSample, type ClockSyncStats, type CloudAPIMessageContent, CloudAPIProvider, type CloudAPIProviderOptions, type ContactMessage, type CredentialStore, EventType, type HealthStats, type InteractiveButton, type InteractiveMessage, InvalidSessionIdError, InvalidTableNameError, type ListSection, type LocationMessage, type MediaMessage, MemoryStore, type Message, MessageQueue, MessageType, type MetricsStore, type Middleware, NotConnectedError, type Platform, PostgresStore, type PostgresStoreConfig, type Provider, ProviderType, QueueFullError, type QueueOptions, type QuotedMessage, type ReachoutTimelockInfo, type ReactionMessage, RedisStore, type RedisStoreConfig, type SendMessageOptions, type Session, type SessionKeyParts, type SessionMetadata, SessionNotFoundError, SessionStatus, type SessionStore, type Store, type TcToken$1 as TcToken, type TcTokenConfig$1 as TcTokenConfig, TcTokenManager, type TemplateMessage, WaSP, type WaspConfig, type WaspEvent, type WebhookConfig, WebhookManager, type WrappedSocket, autoReconnect, buildSessionKey, createAdminRouter, errorHandler, logger, parseSessionKey, rateLimit, wrapSocket };