@yellowdotai/yellow-chat-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1623 @@
1
+ /**
2
+ * YellowChat Configuration Types
3
+ */
4
+ /**
5
+ * Public SDK Configuration - Options exposed to end users
6
+ *
7
+ * Only includes options that end users need to configure.
8
+ * Internal details like XMPP domains, WebSocket routes, etc. are hidden.
9
+ */
10
+ interface SDKConfig {
11
+ /** Bot ID (required) - Your Yellow.ai bot identifier */
12
+ bot: string;
13
+ /** API host URL (default: 'https://cloud.yellow.ai') */
14
+ host?: string;
15
+ /**
16
+ * Message source identifier (default: 'yellowmessenger')
17
+ *
18
+ * This determines how messages are routed through Yellow.ai's backend.
19
+ *
20
+ * Options:
21
+ * - 'yellowmessenger' (default): Use for fully headless SDK-only integrations.
22
+ * The SDK handles all communication via WebSocket/XMPP. Best for custom chat
23
+ * widgets where the SDK is the primary communication channel.
24
+ *
25
+ * - 'syncApi': Use when integrating with the /integrations/sync/v1/message REST API.
26
+ * Required for hybrid mode where you start with REST API calls and switch to
27
+ * WebSocket when a live agent connects. This ensures ticket consistency between
28
+ * REST and WebSocket channels.
29
+ *
30
+ * @example
31
+ * // Fully headless - SDK only
32
+ * sdk.init({ bot: 'your-bot', source: 'yellowmessenger' });
33
+ *
34
+ * @example
35
+ * // Hybrid mode - REST API + SDK for live agent
36
+ * sdk.init({ bot: 'your-bot', source: 'syncApi' });
37
+ */
38
+ source?: string;
39
+ /** User identifier (optional - SDK will auto-generate if not provided) */
40
+ userId?: string;
41
+ /** User display name */
42
+ name?: string;
43
+ /** Custom payload to send with messages */
44
+ payload?: Record<string, unknown>;
45
+ /** Authentication token (if required by your bot) */
46
+ ymAuthenticationToken?: string;
47
+ /** Device token for push notifications */
48
+ deviceToken?: string;
49
+ /** Journey to trigger on connect */
50
+ triggerJourney?: string;
51
+ /** Trigger event name */
52
+ trigger?: string;
53
+ /**
54
+ * Suppress welcome messages on connect (default: false)
55
+ *
56
+ * Set to true in hybrid mode when connecting to WebSocket after already
57
+ * having a conversation via REST API. This prevents duplicate welcome messages.
58
+ *
59
+ * @example
60
+ * // Hybrid mode - conversation already started via REST
61
+ * sdk.init({
62
+ * bot: 'your-bot',
63
+ * source: 'syncApi',
64
+ * disableWelcomeMessage: true // Suppress welcome since REST chat already started
65
+ * });
66
+ */
67
+ disableWelcomeMessage?: boolean;
68
+ /** UTM parameters for analytics */
69
+ utmSource?: string;
70
+ utmCampaign?: string;
71
+ utmMedium?: string;
72
+ utmTerm?: string;
73
+ utmContent?: string;
74
+ /** Enable debug logging (default: false) */
75
+ debug?: boolean;
76
+ }
77
+
78
+ /**
79
+ * YellowChat Message Types
80
+ *
81
+ * This module contains type definitions for all message-related data
82
+ * in the SDK, including incoming messages from bots/agents and outgoing
83
+ * messages from users.
84
+ *
85
+ * @packageDocumentation
86
+ */
87
+ /**
88
+ * Type of message content.
89
+ *
90
+ * Determines how the message should be rendered in the UI.
91
+ *
92
+ * - `text` - Plain text message
93
+ * - `image` - Image with optional caption
94
+ * - `file` - Downloadable file attachment
95
+ * - `video` - Video with playback controls
96
+ * - `audio` - Audio clip
97
+ * - `cards` - Carousel of cards with actions
98
+ * - `quickReplies` - Quick reply buttons
99
+ * - `webView` - Embedded web view
100
+ * - `rating` - Rating request (stars, emoji, thumbs)
101
+ * - `location` - Map location
102
+ * - `multiSelect` - Multi-selection options
103
+ * - `date` - Date picker
104
+ * - `feedback` - Text feedback input
105
+ * - `system` - System notification
106
+ */
107
+ type MessageType = 'text' | 'image' | 'file' | 'video' | 'audio' | 'cards' | 'quickReplies' | 'webView' | 'webViews' | 'rating' | 'location' | 'flightDetails' | 'boardingPass' | 'docSearchCards' | 'notification' | 'question' | 'multiSelect' | 'date' | 'feedback' | 'system';
108
+ /**
109
+ * Who sent the message.
110
+ *
111
+ * - `bot` - Automated bot response
112
+ * - `agent` - Live human agent
113
+ * - `user` - The current user (echoed back)
114
+ * - `system` - System notification
115
+ */
116
+ type MessageSender = 'bot' | 'agent' | 'user' | 'system';
117
+ /**
118
+ * Message received from the server (from bot, agent, or system).
119
+ *
120
+ * Incoming messages are delivered via the `message:received` event.
121
+ * The `type` field determines what content is available.
122
+ *
123
+ * @example
124
+ * ```typescript
125
+ * sdk.on('message:received', (message: IncomingMessage) => {
126
+ * console.log(`[${message.sender}]: ${message.content.text}`);
127
+ *
128
+ * if (message.type === 'quickReplies') {
129
+ * // Show quick reply buttons
130
+ * renderQuickReplies(message.content.quickReplies);
131
+ * }
132
+ * });
133
+ * ```
134
+ */
135
+ interface IncomingMessage {
136
+ /** Unique message ID */
137
+ id: string;
138
+ /** Trace ID for debugging */
139
+ traceId?: string;
140
+ /** Message timestamp */
141
+ timestamp: Date;
142
+ /** Message type */
143
+ type: MessageType;
144
+ /** Message content */
145
+ content: MessageContent;
146
+ /** Who sent the message */
147
+ sender: MessageSender;
148
+ /** Agent profile if sent by agent */
149
+ agentProfile?: AgentProfile;
150
+ /** Additional metadata */
151
+ metadata?: Record<string, unknown>;
152
+ /** Journey slug for analytics */
153
+ journeySlug?: string;
154
+ /** Step slug for analytics */
155
+ stepSlug?: string;
156
+ }
157
+ /**
158
+ * Message sent by the user.
159
+ *
160
+ * Outgoing messages are created when calling `sdk.sendMessage()`.
161
+ * The `message:sent` event includes this structure.
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * sdk.on('message:sent', (message: OutgoingMessage) => {
166
+ * console.log('Sent:', message.message);
167
+ * });
168
+ * ```
169
+ */
170
+ interface OutgoingMessage {
171
+ /** Unique message ID */
172
+ id: string;
173
+ /** Message text */
174
+ message: string;
175
+ /** Message timestamp */
176
+ timestamp: Date;
177
+ /** Optional title */
178
+ title?: string;
179
+ /** Additional metadata */
180
+ metadata?: Record<string, unknown>;
181
+ }
182
+ /**
183
+ * Container for message content.
184
+ *
185
+ * Only one content type is typically populated based on `MessageType`.
186
+ * For example, a `type: 'image'` message will have `content.image` set.
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * // Handle different content types
191
+ * if (message.content.text) {
192
+ * renderText(message.content.text);
193
+ * } else if (message.content.image) {
194
+ * renderImage(message.content.image.url, message.content.image.caption);
195
+ * } else if (message.content.cards) {
196
+ * renderCardCarousel(message.content.cards);
197
+ * }
198
+ * ```
199
+ */
200
+ interface MessageContent {
201
+ /** Text content */
202
+ text?: string;
203
+ /** Image content */
204
+ image?: ImageContent;
205
+ /** File content */
206
+ file?: FileContent;
207
+ /** Video content */
208
+ video?: VideoContent;
209
+ /** Audio content */
210
+ audio?: AudioContent;
211
+ /** Card carousel */
212
+ cards?: CardContent[];
213
+ /** Quick reply buttons */
214
+ quickReplies?: QuickReplyContent;
215
+ /** Web view configuration */
216
+ webView?: WebViewContent;
217
+ /** Multiple web views */
218
+ webViews?: WebViewContent[];
219
+ /** Rating request */
220
+ rating?: RatingContent;
221
+ /** Location data */
222
+ location?: LocationContent;
223
+ /** Multi-select options */
224
+ multiSelect?: MultiSelectContent;
225
+ /** Date picker */
226
+ date?: DateContent;
227
+ /** Feedback request */
228
+ feedback?: FeedbackContent;
229
+ }
230
+ /**
231
+ * Image message content.
232
+ */
233
+ interface ImageContent {
234
+ /** Image URL */
235
+ url: string;
236
+ /** Optional caption text */
237
+ caption?: string;
238
+ /** Alt text for accessibility */
239
+ altText?: string;
240
+ }
241
+ /**
242
+ * File attachment content.
243
+ */
244
+ interface FileContent {
245
+ /** Download URL */
246
+ url: string;
247
+ /** Original file name */
248
+ name: string;
249
+ /** File size in bytes */
250
+ size?: number;
251
+ /** MIME type (e.g., 'application/pdf') */
252
+ mimeType?: string;
253
+ }
254
+ /**
255
+ * Video message content with playback options.
256
+ */
257
+ interface VideoContent {
258
+ /** Video URL */
259
+ url: string;
260
+ /** Thumbnail image URL */
261
+ thumbnail?: string;
262
+ /** Duration in seconds */
263
+ duration?: number;
264
+ /** Show playback controls */
265
+ controls?: boolean;
266
+ /** Auto-play on load */
267
+ autoplay?: boolean;
268
+ /** Loop playback */
269
+ loop?: boolean;
270
+ /** Start muted */
271
+ muted?: boolean;
272
+ /** Allow download */
273
+ downloadable?: boolean;
274
+ }
275
+ /**
276
+ * Audio message content.
277
+ */
278
+ interface AudioContent {
279
+ /** Audio URL */
280
+ url: string;
281
+ /** Duration in seconds */
282
+ duration?: number;
283
+ }
284
+ /**
285
+ * Card in a carousel.
286
+ *
287
+ * Cards can have an image, title, description, and action buttons.
288
+ * Multiple cards are displayed as a horizontal carousel.
289
+ */
290
+ interface CardContent {
291
+ /** Card title */
292
+ title: string;
293
+ /** Card description text */
294
+ description?: string;
295
+ /** Card image URL */
296
+ image?: string;
297
+ /** Link URL when card is clicked */
298
+ url?: string;
299
+ /** Action buttons on the card */
300
+ actions?: CardAction[];
301
+ }
302
+ /**
303
+ * Action button on a card.
304
+ */
305
+ interface CardAction {
306
+ /** Button label */
307
+ title: string;
308
+ /** Action type: 'url' opens link, 'postback' sends value to bot, 'call' initiates call, 'share' shares content */
309
+ type: 'url' | 'postback' | 'call' | 'share';
310
+ /** Value to send for postback actions */
311
+ payload?: string;
312
+ /** URL for url/call actions */
313
+ url?: string;
314
+ }
315
+ /**
316
+ * Quick reply buttons shown below a message.
317
+ *
318
+ * Quick replies provide predefined response options for the user.
319
+ */
320
+ interface QuickReplyContent {
321
+ /** Optional prompt text above buttons */
322
+ title?: string;
323
+ /** Quick reply button options */
324
+ options: QuickReply[];
325
+ }
326
+ /**
327
+ * A quick reply button option.
328
+ */
329
+ interface QuickReply {
330
+ /** Button label text */
331
+ title: string;
332
+ /** Value sent to bot when selected (defaults to title) */
333
+ value?: string;
334
+ /** Optional icon URL or emoji */
335
+ icon?: string;
336
+ }
337
+ /**
338
+ * Web view (iframe) content configuration.
339
+ *
340
+ * Used to embed external web pages within the chat.
341
+ */
342
+ interface WebViewContent {
343
+ /** Web page URL to embed */
344
+ url: string;
345
+ /** Title shown in header */
346
+ title?: string;
347
+ /** Height of web view: 'compact' (50%), 'tall' (75%), 'full' (100%) */
348
+ height?: 'compact' | 'tall' | 'full';
349
+ /** Close web view when form is submitted */
350
+ closeOnSubmit?: boolean;
351
+ }
352
+ /**
353
+ * Rating/feedback request configuration.
354
+ *
355
+ * Prompts user to rate the conversation or experience.
356
+ */
357
+ interface RatingContent {
358
+ /** Prompt text */
359
+ title?: string;
360
+ /** Minimum rating value (default: 1) */
361
+ minRating?: number;
362
+ /** Maximum rating value (default: 5) */
363
+ maxRating?: number;
364
+ /** Visual style: 'star', 'emoji', or 'thumbs' */
365
+ ratingType?: 'star' | 'emoji' | 'thumbs';
366
+ }
367
+ /**
368
+ * Geographic location content.
369
+ */
370
+ interface LocationContent {
371
+ /** Latitude coordinate */
372
+ latitude: number;
373
+ /** Longitude coordinate */
374
+ longitude: number;
375
+ /** Location name */
376
+ name?: string;
377
+ /** Full address text */
378
+ address?: string;
379
+ }
380
+ /**
381
+ * Multi-select options content.
382
+ *
383
+ * Allows user to select multiple options from a list.
384
+ */
385
+ interface MultiSelectContent {
386
+ /** Prompt text */
387
+ title?: string;
388
+ /** Selectable options */
389
+ options: MultiSelectOption[];
390
+ /** Minimum required selections */
391
+ minSelection?: number;
392
+ /** Maximum allowed selections */
393
+ maxSelection?: number;
394
+ }
395
+ /**
396
+ * An option in a multi-select list.
397
+ */
398
+ interface MultiSelectOption {
399
+ /** Display label */
400
+ label: string;
401
+ /** Value sent to bot when selected */
402
+ value: string;
403
+ /** Pre-selected state */
404
+ selected?: boolean;
405
+ }
406
+ /**
407
+ * Date picker content configuration.
408
+ */
409
+ interface DateContent {
410
+ /** Prompt text */
411
+ title?: string;
412
+ /** Minimum selectable date (ISO format) */
413
+ minDate?: string;
414
+ /** Maximum selectable date (ISO format) */
415
+ maxDate?: string;
416
+ /** Date format string */
417
+ format?: string;
418
+ }
419
+ /**
420
+ * Text feedback input configuration.
421
+ */
422
+ interface FeedbackContent {
423
+ /** Prompt text */
424
+ title?: string;
425
+ /** Input placeholder text */
426
+ placeholder?: string;
427
+ /** Submit button text */
428
+ submitText?: string;
429
+ }
430
+ /**
431
+ * Live agent profile information.
432
+ *
433
+ * Available when a live agent is assigned to the conversation.
434
+ */
435
+ interface AgentProfile {
436
+ /** Agent username/ID */
437
+ username: string;
438
+ /** Agent display name */
439
+ name: string;
440
+ /** Profile picture URL */
441
+ profilePicture?: string;
442
+ /** Agent description/title */
443
+ description?: string;
444
+ /** WebRTC username for voice/video calls */
445
+ webrtcUsername?: string;
446
+ /** Agent's organization/team owner */
447
+ owner?: string;
448
+ }
449
+ /**
450
+ * Welcome message configuration.
451
+ */
452
+ interface WelcomeMessage {
453
+ /** Welcome message text */
454
+ message: string;
455
+ /** Delay before showing (milliseconds) */
456
+ delay?: number;
457
+ }
458
+ /**
459
+ * Message from conversation history.
460
+ *
461
+ * Extends `IncomingMessage` with delivery status information.
462
+ */
463
+ interface HistoryMessage extends IncomingMessage {
464
+ /** Message delivery status */
465
+ status?: 'sent' | 'delivered' | 'read';
466
+ }
467
+ /**
468
+ * Options for sending a message.
469
+ *
470
+ * @example
471
+ * ```typescript
472
+ * await sdk.sendMessage('Option 1', {
473
+ * metadata: { selectedOption: 'opt-1' }
474
+ * });
475
+ * ```
476
+ */
477
+ interface SendMessageOptions {
478
+ /** Optional title for the message */
479
+ title?: string;
480
+ /** Additional metadata to send with the message */
481
+ metadata?: Record<string, unknown>;
482
+ /** Skip rate limiting check (use with caution) */
483
+ skipRateLimit?: boolean;
484
+ }
485
+ /**
486
+ * Response returned after successfully sending a message.
487
+ */
488
+ interface MessageResponse {
489
+ /** Message ID assigned by server */
490
+ id: string;
491
+ /** Trace ID for debugging and tracking */
492
+ traceId?: string;
493
+ /** Server timestamp when message was received */
494
+ timestamp: Date;
495
+ }
496
+ /**
497
+ * Response returned after successfully uploading a file.
498
+ */
499
+ interface FileUploadResponse {
500
+ /** Uploaded file URL (CDN hosted) */
501
+ url: string;
502
+ /** Original file name */
503
+ name: string;
504
+ /** File size in bytes */
505
+ size: number;
506
+ }
507
+
508
+ /**
509
+ * YellowChat Bot Types
510
+ *
511
+ * This module contains type definitions for bot configuration and
512
+ * customization options loaded during SDK initialization.
513
+ *
514
+ * @packageDocumentation
515
+ */
516
+ /**
517
+ * Bot information and configuration.
518
+ *
519
+ * Available after `sdk.init()` completes via `sdk.getBotInfo()`.
520
+ * Contains bot identity, UI theme, and feature flags.
521
+ *
522
+ * @example
523
+ * ```typescript
524
+ * const botInfo = sdk.getBotInfo();
525
+ * if (botInfo) {
526
+ * document.title = botInfo.name;
527
+ * if (botInfo.icon) {
528
+ * setFavicon(botInfo.icon);
529
+ * }
530
+ * }
531
+ * ```
532
+ */
533
+ interface BotInfo {
534
+ /** Bot ID */
535
+ botId: string;
536
+ /** Bot display name */
537
+ name: string;
538
+ /** Bot icon URL */
539
+ icon?: string;
540
+ /** Bot description */
541
+ description?: string;
542
+ /** Bot type */
543
+ botType?: string;
544
+ /** Subscription ID */
545
+ subscriptionId?: string;
546
+ /** Whether secure UID is required */
547
+ useSecureUid?: boolean;
548
+ /** Frontend UID */
549
+ feUID?: string;
550
+ /** Whether bot is turned off */
551
+ turnOff?: boolean;
552
+ /** Bot skin/theme configuration */
553
+ skin?: BotSkin;
554
+ /** Bot features */
555
+ features?: BotFeatures;
556
+ /** Available languages */
557
+ languages?: string[];
558
+ /** Default language */
559
+ defaultLanguage?: string;
560
+ }
561
+ /**
562
+ * Bot UI theme and styling configuration.
563
+ *
564
+ * Use these values to customize your chat UI to match the bot's branding.
565
+ * All colors are CSS color strings (hex, rgb, etc.).
566
+ *
567
+ * @example
568
+ * ```typescript
569
+ * const skin = sdk.getBotInfo()?.skin;
570
+ * if (skin) {
571
+ * document.documentElement.style.setProperty('--primary-color', skin.primaryColor);
572
+ * document.documentElement.style.setProperty('--bot-bubble', skin.botBubbleColor);
573
+ * }
574
+ * ```
575
+ */
576
+ interface BotSkin {
577
+ /** Primary brand color */
578
+ primaryColor?: string;
579
+ /** Secondary color */
580
+ secondaryColor?: string;
581
+ /** Bot bubble color */
582
+ botBubbleColor?: string;
583
+ /** Bot text color */
584
+ botTextColor?: string;
585
+ /** User bubble color */
586
+ userBubbleColor?: string;
587
+ /** User text color */
588
+ userTextColor?: string;
589
+ /** Header background color */
590
+ headerColor?: string;
591
+ /** Header text color */
592
+ headerTextColor?: string;
593
+ /** Font family */
594
+ fontFamily?: string;
595
+ /** Font size */
596
+ fontSize?: string;
597
+ /** Border radius */
598
+ borderRadius?: string;
599
+ /** Show typing indicator */
600
+ showTyping?: boolean;
601
+ /** Enable sound */
602
+ enableSound?: boolean;
603
+ /** Show branding */
604
+ showBranding?: boolean;
605
+ }
606
+ /**
607
+ * Feature flags indicating what capabilities are enabled for the bot.
608
+ *
609
+ * Use these to conditionally show/hide UI elements based on bot configuration.
610
+ *
611
+ * @example
612
+ * ```typescript
613
+ * const features = sdk.getBotInfo()?.features;
614
+ *
615
+ * if (features?.fileUpload) {
616
+ * showAttachmentButton();
617
+ * }
618
+ * if (features?.voiceInput) {
619
+ * showMicrophoneButton();
620
+ * }
621
+ * if (features?.liveAgent) {
622
+ * showRequestAgentButton();
623
+ * }
624
+ * ```
625
+ */
626
+ interface BotFeatures {
627
+ /** File upload allowed */
628
+ fileUpload?: boolean;
629
+ /** Enable voice input */
630
+ voiceInput?: boolean;
631
+ /** Enable location sharing */
632
+ locationSharing?: boolean;
633
+ /** Enable message history */
634
+ messageHistory?: boolean;
635
+ /** Enable typing indicator */
636
+ typingIndicator?: boolean;
637
+ /** Enable read receipts */
638
+ readReceipts?: boolean;
639
+ /** Enable push notifications */
640
+ pushNotifications?: boolean;
641
+ /** Enable live agent support */
642
+ liveAgent?: boolean;
643
+ /** Enable feedback */
644
+ feedback?: boolean;
645
+ /** Enable emoji */
646
+ emoji?: boolean;
647
+ /** Enable attachments */
648
+ attachments?: boolean;
649
+ /** Enable multi-language */
650
+ multiLanguage?: boolean;
651
+ }
652
+ /**
653
+ * Response from bot load API.
654
+ *
655
+ * Internal type returned when loading bot details during initialization.
656
+ */
657
+ interface BotLoadResponse {
658
+ /** Bot configuration */
659
+ botConfig: BotInfo;
660
+ /** Welcome messages */
661
+ welcomeMessages?: Array<{
662
+ message: string;
663
+ delay?: number;
664
+ }>;
665
+ /** Banners configuration */
666
+ banners?: BannerConfig[];
667
+ /** User information */
668
+ userInfo?: {
669
+ uid: string;
670
+ name?: string;
671
+ email?: string;
672
+ };
673
+ /** Session information */
674
+ session?: {
675
+ sessionId: string;
676
+ expiresAt?: number;
677
+ };
678
+ }
679
+ /**
680
+ * Banner/announcement configuration.
681
+ *
682
+ * Banners can be displayed at the top or bottom of the chat interface
683
+ * to show important messages, promotions, or alerts.
684
+ */
685
+ interface BannerConfig {
686
+ /** Unique banner ID */
687
+ id: string;
688
+ /** Banner title */
689
+ title: string;
690
+ /** Banner message */
691
+ message?: string;
692
+ /** Banner image URL */
693
+ image?: string;
694
+ /** Banner action URL */
695
+ actionUrl?: string;
696
+ /** Banner action text */
697
+ actionText?: string;
698
+ /** Banner position */
699
+ position?: 'top' | 'bottom';
700
+ /** Banner type */
701
+ type?: 'info' | 'warning' | 'error' | 'success';
702
+ /** Auto dismiss time in ms */
703
+ autoDismiss?: number;
704
+ }
705
+
706
+ /**
707
+ * YellowChat Error Types
708
+ *
709
+ * This module contains error type definitions and utility functions
710
+ * for handling SDK errors.
711
+ *
712
+ * @packageDocumentation
713
+ */
714
+ /**
715
+ * Error codes returned by the SDK.
716
+ *
717
+ * Use the error code to determine the type of error and how to handle it.
718
+ *
719
+ * **Connection Errors:**
720
+ * - `CONNECTION_FAILED` - Could not connect to server
721
+ * - `CONNECTION_TIMEOUT` - Connection attempt timed out
722
+ * - `CONNECTION_CLOSED` - Connection was closed unexpectedly
723
+ *
724
+ * **Authentication Errors:**
725
+ * - `AUTH_FAILED` - Authentication failed
726
+ * - `AUTH_TOKEN_EXPIRED` - Auth token has expired
727
+ * - `AUTH_TOKEN_INVALID` - Auth token is invalid
728
+ *
729
+ * **Message Errors:**
730
+ * - `MESSAGE_SEND_FAILED` - Failed to send message
731
+ * - `MESSAGE_TIMEOUT` - Message send timed out
732
+ * - `MESSAGE_RATE_LIMITED` - Too many messages sent
733
+ *
734
+ * **File Errors:**
735
+ * - `FILE_UPLOAD_FAILED` - File upload failed
736
+ * - `FILE_TOO_LARGE` - File exceeds size limit
737
+ * - `FILE_TYPE_NOT_ALLOWED` - File type not supported
738
+ *
739
+ * **Other Errors:**
740
+ * - `BOT_LOAD_FAILED` - Could not load bot configuration
741
+ * - `HISTORY_LOAD_FAILED` - Could not load chat history
742
+ * - `NETWORK_ERROR` - Network connectivity issue
743
+ * - `INVALID_CONFIG` - Invalid SDK configuration
744
+ * - `INVALID_MESSAGE` - Invalid message format
745
+ * - `API_ERROR` - REST API error
746
+ * - `UNKNOWN_ERROR` - Unexpected error
747
+ *
748
+ * @example
749
+ * ```typescript
750
+ * try {
751
+ * await sdk.sendMessage('Hello');
752
+ * } catch (error) {
753
+ * if (error instanceof YellowChatError) {
754
+ * switch (error.code) {
755
+ * case 'MESSAGE_RATE_LIMITED':
756
+ * showToast('Please wait before sending another message');
757
+ * break;
758
+ * case 'CONNECTION_CLOSED':
759
+ * await sdk.connect();
760
+ * break;
761
+ * default:
762
+ * console.error('Error:', error.message);
763
+ * }
764
+ * }
765
+ * }
766
+ * ```
767
+ */
768
+ type SDKErrorCode = 'CONNECTION_FAILED' | 'CONNECTION_TIMEOUT' | 'CONNECTION_CLOSED' | 'AUTH_FAILED' | 'AUTH_TOKEN_EXPIRED' | 'AUTH_TOKEN_INVALID' | 'MESSAGE_SEND_FAILED' | 'MESSAGE_TIMEOUT' | 'MESSAGE_RATE_LIMITED' | 'FILE_UPLOAD_FAILED' | 'FILE_TOO_LARGE' | 'FILE_TYPE_NOT_ALLOWED' | 'BOT_LOAD_FAILED' | 'HISTORY_LOAD_FAILED' | 'NETWORK_ERROR' | 'INVALID_CONFIG' | 'INVALID_MESSAGE' | 'XMPP_ERROR' | 'STREAM_ERROR' | 'API_ERROR' | 'UNKNOWN_ERROR';
769
+ /**
770
+ * Structured error object returned by SDK operations.
771
+ *
772
+ * Provides detailed error information including error code, message,
773
+ * and whether the error is recoverable (can be retried).
774
+ */
775
+ interface SDKError {
776
+ /** Error code identifying the type of error */
777
+ code: SDKErrorCode;
778
+ /** Human-readable error message */
779
+ message: string;
780
+ /** Additional error details (varies by error type) */
781
+ details?: Record<string, unknown>;
782
+ /** Original error if this error wraps another */
783
+ originalError?: Error;
784
+ /** Timestamp when error occurred */
785
+ timestamp: Date;
786
+ /** Whether the operation can be retried */
787
+ recoverable: boolean;
788
+ }
789
+ /**
790
+ * Create a new SDK error object.
791
+ *
792
+ * Use this to create error objects for event payloads or logging.
793
+ * For throwing errors, use `new YellowChatError()` instead.
794
+ *
795
+ * @param code - Error code identifying the type of error
796
+ * @param message - Human-readable error message
797
+ * @param options - Optional additional error details
798
+ * @returns A structured SDKError object
799
+ *
800
+ * @example
801
+ * ```typescript
802
+ * const error = createSDKError('MESSAGE_SEND_FAILED', 'Failed to send message', {
803
+ * details: { messageId: '123' },
804
+ * recoverable: true
805
+ * });
806
+ * ```
807
+ */
808
+ declare function createSDKError(code: SDKErrorCode, message: string, options?: {
809
+ details?: Record<string, unknown>;
810
+ originalError?: Error;
811
+ recoverable?: boolean;
812
+ }): SDKError;
813
+ /**
814
+ * Error class thrown by SDK operations.
815
+ *
816
+ * Extends the standard `Error` class with additional properties for
817
+ * error categorization and handling.
818
+ *
819
+ * @example
820
+ * ```typescript
821
+ * try {
822
+ * await sdk.init({ bot: '' });
823
+ * } catch (error) {
824
+ * if (error instanceof YellowChatError) {
825
+ * console.error(`[${error.code}] ${error.message}`);
826
+ *
827
+ * if (error.code === 'INVALID_CONFIG') {
828
+ * // Show configuration error to user
829
+ * }
830
+ *
831
+ * if (error.recoverable) {
832
+ * // Can retry the operation
833
+ * }
834
+ * }
835
+ * }
836
+ * ```
837
+ */
838
+ declare class YellowChatError extends Error {
839
+ /** Error code identifying the type of error */
840
+ readonly code: SDKErrorCode;
841
+ /** Additional error details */
842
+ readonly details?: Record<string, unknown>;
843
+ /** Whether the operation can be retried */
844
+ readonly recoverable: boolean;
845
+ /** When the error occurred */
846
+ readonly timestamp: Date;
847
+ /**
848
+ * Create a new YellowChatError.
849
+ *
850
+ * @param code - Error code
851
+ * @param message - Human-readable error message
852
+ * @param options - Optional additional details
853
+ */
854
+ constructor(code: SDKErrorCode, message: string, options?: {
855
+ details?: Record<string, unknown>;
856
+ recoverable?: boolean;
857
+ });
858
+ /**
859
+ * Convert this error to an SDKError object.
860
+ *
861
+ * Useful for passing error data to event handlers or serialization.
862
+ *
863
+ * @returns SDKError representation of this error
864
+ */
865
+ toSDKError(): SDKError;
866
+ }
867
+
868
+ /**
869
+ * YellowChat Event Types
870
+ *
871
+ * This module defines all events emitted by the SDK. Use `sdk.on(eventName, handler)`
872
+ * to subscribe to events, and `sdk.off(eventName, handler)` to unsubscribe.
873
+ *
874
+ * @packageDocumentation
875
+ */
876
+
877
+ /**
878
+ * Current state of the WebSocket connection.
879
+ *
880
+ * Use `connection:stateChange` event to monitor state transitions.
881
+ *
882
+ * - `disconnected` - Not connected to server
883
+ * - `connecting` - Connection attempt in progress
884
+ * - `connected` - Successfully connected and ready
885
+ * - `reconnecting` - Connection lost, attempting to reconnect
886
+ * - `failed` - Connection failed and will not retry
887
+ *
888
+ * @example
889
+ * ```typescript
890
+ * sdk.on('connection:stateChange', (state: ConnectionState) => {
891
+ * switch (state) {
892
+ * case 'connected':
893
+ * showConnectedIndicator();
894
+ * break;
895
+ * case 'reconnecting':
896
+ * showReconnectingSpinner();
897
+ * break;
898
+ * case 'failed':
899
+ * showErrorMessage();
900
+ * break;
901
+ * }
902
+ * });
903
+ * ```
904
+ */
905
+ type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'failed';
906
+ /**
907
+ * Information about why a disconnection occurred.
908
+ *
909
+ * Provided in the `connection:disconnected` event payload.
910
+ */
911
+ interface DisconnectReason {
912
+ /** Disconnect code (e.g., 'NETWORK_ERROR', 'USER_INITIATED') */
913
+ code: string;
914
+ /** Human-readable disconnect message */
915
+ message: string;
916
+ /** Whether the connection was closed cleanly (vs. dropped unexpectedly) */
917
+ wasClean: boolean;
918
+ }
919
+ /**
920
+ * Configuration for the chat input field.
921
+ *
922
+ * Sent via `ui:showInput` event to control input behavior.
923
+ */
924
+ interface InputOptions {
925
+ /** Whether input is enabled/disabled */
926
+ enabled: boolean;
927
+ /** Placeholder text in input field */
928
+ placeholder?: string;
929
+ /** Maximum input length */
930
+ maxLength?: number;
931
+ /** Input type for mobile keyboards */
932
+ inputType?: 'text' | 'number' | 'email' | 'tel';
933
+ /** Show file attachment button */
934
+ showAttachment?: boolean;
935
+ /** Show microphone button for voice input */
936
+ showMic?: boolean;
937
+ }
938
+ /**
939
+ * Configuration for file upload prompt.
940
+ *
941
+ * Sent via `ui:showFilePrompt` event to configure file picker.
942
+ */
943
+ interface FilePromptOptions {
944
+ /** Accepted file types (MIME types or extensions) */
945
+ accept?: string[];
946
+ /** Maximum file size in bytes */
947
+ maxSize?: number;
948
+ /** Allow multiple file selection */
949
+ multiple?: boolean;
950
+ }
951
+ /**
952
+ * SDK Event Map - All events emitted by the YellowChat SDK.
953
+ *
954
+ * Subscribe to events using `sdk.on(eventName, handler)`. The handler function
955
+ * signature is typed based on the event name.
956
+ *
957
+ * ## Event Categories
958
+ *
959
+ * **Connection Events** (`connection:*`)
960
+ * - Manage WebSocket connection lifecycle
961
+ * - `connection:connected` - Ready to send/receive messages
962
+ * - `connection:disconnected` - Connection closed
963
+ * - `connection:reconnecting` - Auto-reconnect in progress
964
+ *
965
+ * **Message Events** (`message:*`)
966
+ * - Handle incoming and outgoing messages
967
+ * - `message:received` - New message from bot/agent
968
+ * - `message:sent` - Message successfully sent
969
+ * - `message:failed` - Message send failed
970
+ *
971
+ * **Agent Events** (`agent:*`)
972
+ * - Live agent status updates
973
+ * - `agent:assigned` - Agent joined conversation
974
+ * - `agent:typing` - Agent typing indicator
975
+ *
976
+ * **UI Control Events** (`ui:*`)
977
+ * - SDK suggestions for UI updates
978
+ * - `ui:showQuickReplies` - Display quick reply buttons
979
+ * - `ui:showCards` - Display card carousel
980
+ *
981
+ * **File Events** (`file:*`)
982
+ * - File upload progress
983
+ * - `file:uploadStarted` - Upload began
984
+ * - `file:uploadCompleted` - Upload successful
985
+ *
986
+ * @example
987
+ * ```typescript
988
+ * // Connection events
989
+ * sdk.on('connection:connected', ({ userId }) => {
990
+ * console.log('Connected as:', userId);
991
+ * });
992
+ *
993
+ * // Message events
994
+ * sdk.on('message:received', (message) => {
995
+ * console.log('New message:', message.content.text);
996
+ * });
997
+ *
998
+ * // Agent events
999
+ * sdk.on('agent:assigned', (agent) => {
1000
+ * console.log('Agent joined:', agent.name);
1001
+ * });
1002
+ * ```
1003
+ */
1004
+ interface SDKEvents {
1005
+ /** Connection attempt started */
1006
+ 'connection:connecting': () => void;
1007
+ /** Successfully connected to server */
1008
+ 'connection:connected': (data: {
1009
+ userId: string;
1010
+ }) => void;
1011
+ /** Disconnected from server */
1012
+ 'connection:disconnected': (reason: DisconnectReason) => void;
1013
+ /** Attempting to reconnect after connection loss */
1014
+ 'connection:reconnecting': (data: {
1015
+ attempt: number;
1016
+ delay: number;
1017
+ }) => void;
1018
+ /** Successfully reconnected after connection loss */
1019
+ 'connection:reconnected': (data: {
1020
+ userId: string | null;
1021
+ }) => void;
1022
+ /** All reconnection attempts failed */
1023
+ 'connection:reconnectFailed': () => void;
1024
+ /** Connection error occurred */
1025
+ 'connection:error': (error: SDKError) => void;
1026
+ /** Connection state changed */
1027
+ 'connection:stateChange': (state: ConnectionState) => void;
1028
+ /** Server assigned a user ID (for anonymous users) */
1029
+ 'connection:uidAssigned': (uid: string) => void;
1030
+ /** New message received from bot or agent */
1031
+ 'message:received': (message: IncomingMessage) => void;
1032
+ /** Message successfully sent */
1033
+ 'message:sent': (data: {
1034
+ id: string;
1035
+ message: string;
1036
+ }) => void;
1037
+ /** Message acknowledged by server */
1038
+ 'message:acknowledged': (data: {
1039
+ messageId: string;
1040
+ }) => void;
1041
+ /** Message send failed */
1042
+ 'message:failed': (data: {
1043
+ messageId: string;
1044
+ error: SDKError;
1045
+ }) => void;
1046
+ /** User typing indicator state changed */
1047
+ 'message:typing': (isTyping: boolean) => void;
1048
+ /** Message delivery status updated */
1049
+ 'message:status': (data: {
1050
+ messageId: string;
1051
+ status: 'sent' | 'delivered' | 'read';
1052
+ }) => void;
1053
+ /** Bot details are being loaded */
1054
+ 'bot:loading': () => void;
1055
+ /** Bot details loaded successfully */
1056
+ 'bot:loaded': (botInfo: BotInfo) => void;
1057
+ /** Failed to load bot details */
1058
+ 'bot:loadFailed': (error: SDKError) => void;
1059
+ /** Welcome messages to display */
1060
+ 'bot:welcomeMessages': (messages: WelcomeMessage[]) => void;
1061
+ /** Bot is typing indicator */
1062
+ 'bot:typing': (isTyping: boolean) => void;
1063
+ /** Live agent assigned to conversation */
1064
+ 'agent:assigned': (agentProfile: AgentProfile) => void;
1065
+ /** Agent left the conversation */
1066
+ 'agent:left': () => void;
1067
+ /** Agent typing indicator */
1068
+ 'agent:typing': (isTyping: boolean) => void;
1069
+ /** Live agents are available */
1070
+ 'agent:available': () => void;
1071
+ /** No live agents available */
1072
+ 'agent:unavailable': () => void;
1073
+ /** Joined queue for live agent */
1074
+ 'queue:joined': (data: {
1075
+ position: number;
1076
+ estimatedWait?: number;
1077
+ }) => void;
1078
+ /** Queue position updated */
1079
+ 'queue:position': (data: {
1080
+ position: number;
1081
+ message?: string;
1082
+ }) => void;
1083
+ /** Left the queue */
1084
+ 'queue:left': () => void;
1085
+ /** History is being loaded */
1086
+ 'history:loading': () => void;
1087
+ /** History loaded successfully */
1088
+ 'history:loaded': (data: {
1089
+ messages: HistoryMessage[];
1090
+ hasMore: boolean;
1091
+ }) => void;
1092
+ /** Failed to load history */
1093
+ 'history:error': (error: SDKError) => void;
1094
+ /** Previous conversation messages received (from fetchPreviousConversation) */
1095
+ 'history:previousMessages': (messages: unknown[]) => void;
1096
+ /** Show/configure input field */
1097
+ 'ui:showInput': (options: InputOptions) => void;
1098
+ /** Hide input field */
1099
+ 'ui:hideInput': () => void;
1100
+ /** Show quick reply buttons */
1101
+ 'ui:showQuickReplies': (quickReplies: QuickReply[]) => void;
1102
+ /** Hide quick reply buttons */
1103
+ 'ui:hideQuickReplies': () => void;
1104
+ /** Show card carousel */
1105
+ 'ui:showCards': (cards: CardContent[]) => void;
1106
+ /** Show web view modal */
1107
+ 'ui:showWebView': (webView: WebViewContent) => void;
1108
+ /** Close web view modal */
1109
+ 'ui:closeWebView': () => void;
1110
+ /** Show file picker */
1111
+ 'ui:showFilePrompt': (options: FilePromptOptions) => void;
1112
+ /** Show rating prompt */
1113
+ 'ui:showRating': (options: RatingContent) => void;
1114
+ /** Show notification toast */
1115
+ 'ui:showNotification': (data: {
1116
+ title: string;
1117
+ message: string;
1118
+ }) => void;
1119
+ /** Authentication required to continue */
1120
+ 'auth:required': () => void;
1121
+ /** Authentication verified successfully */
1122
+ 'auth:verified': () => void;
1123
+ /** Authentication failed */
1124
+ 'auth:failed': (error: SDKError) => void;
1125
+ /** Auth token needs refresh */
1126
+ 'auth:tokenRefreshNeeded': () => void;
1127
+ /** Support ticket created */
1128
+ 'ticket:created': (data: {
1129
+ ticketId: string;
1130
+ }) => void;
1131
+ /** Ticket status updated */
1132
+ 'ticket:updated': (data: {
1133
+ ticketId: string;
1134
+ status: string;
1135
+ }) => void;
1136
+ /** Ticket closed */
1137
+ 'ticket:closed': () => void;
1138
+ /** Ticket resolved */
1139
+ 'ticket:resolved': () => void;
1140
+ /** Ticket transferred to new agent */
1141
+ 'ticket:transferred': (data: {
1142
+ newAgent: AgentProfile;
1143
+ }) => void;
1144
+ /** Ticket details received */
1145
+ 'ticket:details': (data: unknown) => void;
1146
+ /** Campaigns loaded from server */
1147
+ 'campaigns:loaded': (campaigns: unknown[]) => void;
1148
+ /** User info updated on server */
1149
+ 'user:infoUpdated': (data: unknown) => void;
1150
+ /** File upload started */
1151
+ 'file:uploadStarted': (data: {
1152
+ fileId: string;
1153
+ fileName: string;
1154
+ }) => void;
1155
+ /** File upload progress (0-100) */
1156
+ 'file:uploadProgress': (data: {
1157
+ fileId: string;
1158
+ progress: number;
1159
+ }) => void;
1160
+ /** File upload completed */
1161
+ 'file:uploadCompleted': (data: {
1162
+ fileId: string;
1163
+ file: FileContent;
1164
+ }) => void;
1165
+ /** File upload failed */
1166
+ 'file:uploadFailed': (data: {
1167
+ fileId: string;
1168
+ error: SDKError;
1169
+ }) => void;
1170
+ /** Device went online */
1171
+ 'network:online': () => void;
1172
+ /** Device went offline */
1173
+ 'network:offline': () => void;
1174
+ /** Debug log message (when debug mode enabled) */
1175
+ 'debug:log': (data: {
1176
+ level: 'info' | 'warn' | 'error';
1177
+ message: string;
1178
+ data?: unknown;
1179
+ }) => void;
1180
+ }
1181
+ /**
1182
+ * Type helper to get the handler function type for a specific event.
1183
+ *
1184
+ * @example
1185
+ * ```typescript
1186
+ * // Get the handler type for 'message:received'
1187
+ * type MessageHandler = SDKEventHandler<'message:received'>;
1188
+ * // Result: (message: IncomingMessage) => void
1189
+ *
1190
+ * const handler: MessageHandler = (message) => {
1191
+ * console.log(message.content.text);
1192
+ * };
1193
+ * ```
1194
+ */
1195
+ type SDKEventHandler<K extends keyof SDKEvents> = SDKEvents[K];
1196
+ /**
1197
+ * Union type of all valid event names.
1198
+ *
1199
+ * TypeScript will autocomplete event names when using `sdk.on()`.
1200
+ *
1201
+ * @example
1202
+ * ```typescript
1203
+ * const eventName: SDKEventName = 'message:received';
1204
+ * sdk.on(eventName, handler);
1205
+ * ```
1206
+ */
1207
+ type SDKEventName = keyof SDKEvents;
1208
+
1209
+ /**
1210
+ * YellowChat - Main SDK Class
1211
+ *
1212
+ * The primary interface for integrating Yellow Messenger chat functionality.
1213
+ * Provides event-based communication between the SDK and UI layer.
1214
+ */
1215
+
1216
+ /**
1217
+ * YellowChat - Main SDK class
1218
+ *
1219
+ * @example
1220
+ * ```typescript
1221
+ * import { YellowChat } from '@yellowdotai/yellow-true-sdk';
1222
+ *
1223
+ * const sdk = new YellowChat();
1224
+ *
1225
+ * // Subscribe to events
1226
+ * sdk.on('message:received', (message) => {
1227
+ * console.log('New message:', message);
1228
+ * });
1229
+ *
1230
+ * sdk.on('connection:connected', ({ userId }) => {
1231
+ * console.log('Connected as:', userId);
1232
+ * });
1233
+ *
1234
+ * // Initialize and connect
1235
+ * await sdk.init({ bot: 'your-bot-id' });
1236
+ * await sdk.connect();
1237
+ *
1238
+ * // Send a message
1239
+ * await sdk.sendMessage('Hello!');
1240
+ * ```
1241
+ */
1242
+ declare class YellowChat {
1243
+ private eventEmitter;
1244
+ private config;
1245
+ private connectionManager;
1246
+ private messageHandler;
1247
+ private restTransport;
1248
+ private botLoadAPI;
1249
+ private ticketAPI;
1250
+ private campaignAPI;
1251
+ private userAPI;
1252
+ private isInitialized;
1253
+ private botInfo;
1254
+ private storedUid;
1255
+ private authenticatedFeUID;
1256
+ private isReconnecting;
1257
+ private lastSeenMessageTimestamp;
1258
+ constructor();
1259
+ /**
1260
+ * Get UID from localStorage
1261
+ */
1262
+ private getStoredUid;
1263
+ /**
1264
+ * Store UID in localStorage
1265
+ */
1266
+ private storeUid;
1267
+ /**
1268
+ * Initialize the SDK with configuration.
1269
+ *
1270
+ * This must be called before any other SDK methods. It loads bot details
1271
+ * from the server and sets up internal components.
1272
+ *
1273
+ * @param config - SDK configuration options including bot ID and optional settings
1274
+ * @returns Promise that resolves when initialization is complete
1275
+ * @throws {YellowChatError} INVALID_CONFIG - If bot ID is missing
1276
+ * @throws {YellowChatError} BOT_LOAD_FAILED - If bot details cannot be loaded from server
1277
+ *
1278
+ * @example
1279
+ * ```typescript
1280
+ * const sdk = new YellowChat();
1281
+ *
1282
+ * // Basic initialization
1283
+ * await sdk.init({ bot: 'your-bot-id' });
1284
+ *
1285
+ * // With authentication token
1286
+ * await sdk.init({
1287
+ * bot: 'your-bot-id',
1288
+ * ymAuthenticationToken: 'user-auth-token',
1289
+ * debug: true
1290
+ * });
1291
+ * ```
1292
+ */
1293
+ init(config: SDKConfig): Promise<void>;
1294
+ /**
1295
+ * Connect to the messaging server.
1296
+ *
1297
+ * Establishes a WebSocket connection to the Yellow.ai messaging server.
1298
+ * Must be called after `init()` completes successfully.
1299
+ *
1300
+ * @param userId - Optional user ID for the connection. Behavior depends on mode:
1301
+ * - **Headless mode**: If `ymAuthenticationToken` was provided during init and server
1302
+ * returned a `feUID`, that takes priority and this parameter is ignored.
1303
+ * - **Hybrid mode** (`source: 'syncApi'`): This userId MUST match the sender ID
1304
+ * used in your REST API calls to ensure ticket continuity.
1305
+ * - If omitted, SDK uses stored UID from localStorage or server assigns one.
1306
+ * @returns Promise that resolves when connection is established
1307
+ * @throws {YellowChatError} INVALID_CONFIG - If SDK is not initialized
1308
+ * @throws {YellowChatError} CONNECTION_FAILED - If connection cannot be established
1309
+ *
1310
+ * @example
1311
+ * ```typescript
1312
+ * // Anonymous connection (server assigns user ID)
1313
+ * await sdk.connect();
1314
+ *
1315
+ * // With specific user ID
1316
+ * await sdk.connect('user-123');
1317
+ *
1318
+ * // Hybrid mode - match REST API sender
1319
+ * await sdk.connect(restApiSenderId);
1320
+ * ```
1321
+ */
1322
+ connect(userId?: string): Promise<void>;
1323
+ /**
1324
+ * Set up internal event handlers for reconnection etc.
1325
+ */
1326
+ private setupInternalListeners;
1327
+ /**
1328
+ * Get timestamp from a message object
1329
+ */
1330
+ private getMessageTimestamp;
1331
+ /**
1332
+ * Update the last seen message timestamp from a list of messages
1333
+ */
1334
+ private updateLastSeenTimestamp;
1335
+ /**
1336
+ * Fetch post-reconnection data:
1337
+ * 1. Active ticket details (to restore agent state)
1338
+ * 2. Fetch previous/dropped messages
1339
+ * 3. Update user info (to sync context with server)
1340
+ *
1341
+ * Unlike initial connection, does NOT call:
1342
+ * - campaigns (already loaded)
1343
+ */
1344
+ private fetchPostReconnectionData;
1345
+ /**
1346
+ * Fetch post-connection data in sequence:
1347
+ * 1. Active ticket + campaigns (parallel)
1348
+ * 2. Fetch previous conversation history (via REST, response via XMPP)
1349
+ * 3. Update user info
1350
+ */
1351
+ private fetchPostConnectionData;
1352
+ /**
1353
+ * Fetch previous conversation history.
1354
+ *
1355
+ * Requests conversation history from the server. Messages are delivered
1356
+ * via the `history:previousMessages` event, not as a direct return value.
1357
+ *
1358
+ * @param limit - Maximum number of messages to fetch (default: 50)
1359
+ * @param offset - Pagination offset for fetching older messages. Use the offset
1360
+ * from previous response to load more history.
1361
+ * @returns Promise that resolves when the request is sent (not when messages arrive)
1362
+ * @throws {YellowChatError} INVALID_CONFIG - If SDK is not initialized
1363
+ *
1364
+ * @example
1365
+ * ```typescript
1366
+ * // Listen for history messages
1367
+ * sdk.on('history:previousMessages', (messages) => {
1368
+ * console.log('Received history:', messages);
1369
+ * });
1370
+ *
1371
+ * // Fetch last 50 messages
1372
+ * await sdk.fetchPreviousConversation();
1373
+ *
1374
+ * // Fetch with custom limit
1375
+ * await sdk.fetchPreviousConversation(100);
1376
+ *
1377
+ * // Paginate through history
1378
+ * await sdk.fetchPreviousConversation(50, lastMessageOffset);
1379
+ * ```
1380
+ */
1381
+ fetchPreviousConversation(limit?: number, offset?: string): Promise<void>;
1382
+ /**
1383
+ * Disconnect from the messaging server.
1384
+ *
1385
+ * Gracefully closes the WebSocket connection and cleans up resources.
1386
+ * Safe to call even if not currently connected. After disconnecting,
1387
+ * you can call `connect()` again to reconnect.
1388
+ *
1389
+ * @returns void
1390
+ *
1391
+ * @example
1392
+ * ```typescript
1393
+ * // Disconnect when user closes chat
1394
+ * sdk.disconnect();
1395
+ *
1396
+ * // Reconnect later
1397
+ * await sdk.connect();
1398
+ * ```
1399
+ */
1400
+ disconnect(): void;
1401
+ /**
1402
+ * Send a text message to the bot or agent.
1403
+ *
1404
+ * Messages are sent via the WebSocket connection. The response includes
1405
+ * a message ID that can be used for tracking. Listen to `message:sent`
1406
+ * event for confirmation or `message:failed` for errors.
1407
+ *
1408
+ * @param message - The message text to send
1409
+ * @param options - Optional send options (e.g., quick reply data, metadata)
1410
+ * @returns Promise resolving to message response with message ID
1411
+ * @throws {YellowChatError} INVALID_CONFIG - If SDK is not initialized
1412
+ * @throws {YellowChatError} MESSAGE_SEND_FAILED - If message cannot be sent
1413
+ *
1414
+ * @example
1415
+ * ```typescript
1416
+ * // Send a simple text message
1417
+ * const response = await sdk.sendMessage('Hello!');
1418
+ * console.log('Message ID:', response.messageId);
1419
+ *
1420
+ * // Send with quick reply payload
1421
+ * await sdk.sendMessage('Option 1', {
1422
+ * payload: { selectedOption: 'option-1' }
1423
+ * });
1424
+ * ```
1425
+ */
1426
+ sendMessage(message: string, options?: SendMessageOptions): Promise<MessageResponse>;
1427
+ /**
1428
+ * Send an event to the bot (internal use)
1429
+ */
1430
+ private sendEventInternal;
1431
+ /**
1432
+ * Upload and send a file to the conversation.
1433
+ *
1434
+ * Files are first uploaded to the server, then a file message is sent.
1435
+ * Progress and completion events are emitted during the upload process:
1436
+ * - `file:uploadStarted` - Upload has begun
1437
+ * - `file:uploadProgress` - Upload progress update (if supported)
1438
+ * - `file:uploadCompleted` - Upload successful
1439
+ * - `file:uploadFailed` - Upload failed
1440
+ *
1441
+ * @param file - The File object to upload and send
1442
+ * @returns Promise resolving to file upload response with URL, name, and size
1443
+ * @throws {YellowChatError} INVALID_CONFIG - If SDK is not initialized
1444
+ * @throws {YellowChatError} FILE_UPLOAD_FAILED - If file upload fails
1445
+ * @throws {YellowChatError} FILE_TOO_LARGE - If file exceeds size limit
1446
+ * @throws {YellowChatError} FILE_TYPE_NOT_ALLOWED - If file type is not supported
1447
+ *
1448
+ * @example
1449
+ * ```typescript
1450
+ * // Handle file input
1451
+ * const fileInput = document.querySelector('input[type="file"]');
1452
+ * const file = fileInput.files[0];
1453
+ *
1454
+ * try {
1455
+ * const result = await sdk.sendFile(file);
1456
+ * console.log('File uploaded:', result.url);
1457
+ * } catch (error) {
1458
+ * console.error('Upload failed:', error.message);
1459
+ * }
1460
+ *
1461
+ * // Listen for upload events
1462
+ * sdk.on('file:uploadStarted', ({ fileId, fileName }) => {
1463
+ * console.log('Uploading:', fileName);
1464
+ * });
1465
+ * ```
1466
+ */
1467
+ sendFile(file: File): Promise<FileUploadResponse>;
1468
+ /**
1469
+ * Check if currently connected to the messaging server.
1470
+ *
1471
+ * @returns `true` if connected, `false` if disconnected or connecting
1472
+ *
1473
+ * @example
1474
+ * ```typescript
1475
+ * if (sdk.isConnected()) {
1476
+ * await sdk.sendMessage('Hello!');
1477
+ * } else {
1478
+ * console.log('Not connected, attempting to reconnect...');
1479
+ * await sdk.connect();
1480
+ * }
1481
+ * ```
1482
+ */
1483
+ isConnected(): boolean;
1484
+ /**
1485
+ * Get the current user ID for this session.
1486
+ *
1487
+ * The user ID depends on the connection mode:
1488
+ * - **Authenticated users**: Returns `feUID` from `ymAuthenticationToken` validation
1489
+ * - **Hybrid mode**: Returns the user ID passed to `connect()` (REST API sender)
1490
+ * - **Anonymous users**: Returns server-assigned user ID
1491
+ *
1492
+ * @returns The current user ID, or `null` if not connected
1493
+ *
1494
+ * @example
1495
+ * ```typescript
1496
+ * const userId = sdk.getUserId();
1497
+ * if (userId) {
1498
+ * console.log('Connected as:', userId);
1499
+ * }
1500
+ * ```
1501
+ */
1502
+ getUserId(): string | null;
1503
+ /**
1504
+ * Get bot information loaded during initialization.
1505
+ *
1506
+ * Returns bot configuration including name, welcome message, features,
1507
+ * and UI customization options. Available after `init()` completes.
1508
+ *
1509
+ * @returns Bot information object, or `null` if not initialized
1510
+ *
1511
+ * @example
1512
+ * ```typescript
1513
+ * const botInfo = sdk.getBotInfo();
1514
+ * if (botInfo) {
1515
+ * console.log('Bot name:', botInfo.name);
1516
+ * console.log('Welcome message:', botInfo.welcomeMessage);
1517
+ *
1518
+ * // Use bot skin for UI customization
1519
+ * if (botInfo.skin) {
1520
+ * document.body.style.setProperty('--primary-color', botInfo.skin.primaryColor);
1521
+ * }
1522
+ * }
1523
+ * ```
1524
+ */
1525
+ getBotInfo(): BotInfo | null;
1526
+ /**
1527
+ * Subscribe to an SDK event.
1528
+ *
1529
+ * The SDK uses an event-driven architecture. All events are typed,
1530
+ * so TypeScript will provide autocomplete for event names and handlers.
1531
+ *
1532
+ * **Common Events:**
1533
+ * - `connection:connected` - Successfully connected to server
1534
+ * - `connection:disconnected` - Disconnected from server
1535
+ * - `message:received` - New message from bot or agent
1536
+ * - `message:sent` - Message successfully sent
1537
+ * - `agent:assigned` - Live agent connected to chat
1538
+ * - `typing:start` / `typing:stop` - Typing indicators
1539
+ *
1540
+ * @param event - Event name (e.g., 'message:received', 'connection:connected')
1541
+ * @param handler - Event handler function. Parameters depend on event type.
1542
+ * @returns Unsubscribe function - call it to stop listening
1543
+ *
1544
+ * @example
1545
+ * ```typescript
1546
+ * // Subscribe to messages
1547
+ * const unsubscribe = sdk.on('message:received', (message) => {
1548
+ * console.log('New message:', message.text);
1549
+ * console.log('From:', message.sender);
1550
+ * });
1551
+ *
1552
+ * // Subscribe to connection events
1553
+ * sdk.on('connection:connected', ({ userId }) => {
1554
+ * console.log('Connected as:', userId);
1555
+ * });
1556
+ *
1557
+ * sdk.on('connection:disconnected', ({ reason }) => {
1558
+ * console.log('Disconnected:', reason);
1559
+ * });
1560
+ *
1561
+ * // Unsubscribe when done
1562
+ * unsubscribe();
1563
+ * ```
1564
+ */
1565
+ on<K extends SDKEventName>(event: K, handler: SDKEvents[K]): () => void;
1566
+ /**
1567
+ * Unsubscribe from an SDK event.
1568
+ *
1569
+ * Removes a previously registered event handler. You must pass the exact
1570
+ * same function reference that was used when calling `on()`.
1571
+ *
1572
+ * **Tip:** Prefer using the unsubscribe function returned by `on()` instead.
1573
+ *
1574
+ * @param event - Event name to unsubscribe from
1575
+ * @param handler - The exact same handler function that was passed to `on()`
1576
+ * @returns void
1577
+ *
1578
+ * @example
1579
+ * ```typescript
1580
+ * // Define handler as a named function
1581
+ * const messageHandler = (message) => {
1582
+ * console.log('Message:', message);
1583
+ * };
1584
+ *
1585
+ * // Subscribe
1586
+ * sdk.on('message:received', messageHandler);
1587
+ *
1588
+ * // Unsubscribe later
1589
+ * sdk.off('message:received', messageHandler);
1590
+ * ```
1591
+ */
1592
+ off<K extends SDKEventName>(event: K, handler: SDKEvents[K]): void;
1593
+ /**
1594
+ * Ensure SDK is initialized before operations
1595
+ */
1596
+ private ensureInitialized;
1597
+ }
1598
+ /**
1599
+ * Create a new YellowChat SDK instance.
1600
+ *
1601
+ * Factory function alternative to `new YellowChat()`. Use this when you
1602
+ * prefer functional-style instantiation or want to avoid the `new` keyword.
1603
+ *
1604
+ * @returns A new YellowChat instance ready for initialization
1605
+ *
1606
+ * @example
1607
+ * ```typescript
1608
+ * import { createYellowChat } from '@yellowdotai/yellow-chat-sdk';
1609
+ *
1610
+ * const sdk = createYellowChat();
1611
+ *
1612
+ * await sdk.init({ bot: 'your-bot-id' });
1613
+ * await sdk.connect();
1614
+ *
1615
+ * sdk.on('message:received', (message) => {
1616
+ * console.log('New message:', message);
1617
+ * });
1618
+ * ```
1619
+ */
1620
+ declare function createYellowChat(): YellowChat;
1621
+
1622
+ export { YellowChat, YellowChatError, createSDKError, createYellowChat, YellowChat as default };
1623
+ export type { AgentProfile, AudioContent, BannerConfig, BotFeatures, BotInfo, BotLoadResponse, BotSkin, CardAction, CardContent, ConnectionState, DateContent, DisconnectReason, FeedbackContent, FileContent, FilePromptOptions, FileUploadResponse, HistoryMessage, ImageContent, IncomingMessage, InputOptions, LocationContent, MessageContent, MessageResponse, MessageSender, MessageType, MultiSelectContent, MultiSelectOption, OutgoingMessage, QuickReply, QuickReplyContent, RatingContent, SDKConfig, SDKError, SDKErrorCode, SDKEventHandler, SDKEventName, SDKEvents, SendMessageOptions, VideoContent, WebViewContent, WelcomeMessage };