@skywu/virtual-chat-sdk 1.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Virtual Chat Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,465 @@
1
+ # @virtual-chat/sdk
2
+
3
+ [![npm version](https://badge.fury.io/js/%40virtual-chat%2Fsdk.svg)](https://badge.fury.io/js/%40virtual-chat%2Fsdk)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+
6
+ A modern JavaScript/TypeScript SDK for embedding floating chat widgets into web applications. Features real-time messaging, virtual chat simulations, and seamless integration.
7
+
8
+ ## ✨ Features
9
+
10
+ - 🎈 **Floating Button Mode** - Non-intrusive chat widget with smooth expand/collapse animations
11
+ - 🎨 **Multiple UI Templates** - WhatsApp and Telegram-style themes with dark mode support
12
+ - ⚡ **Real-time Communication** - WebSocket-based messaging with automatic reconnection
13
+ - 📱 **Responsive Design** - Optimized for desktop, tablet, and mobile devices
14
+ - 🔧 **Highly Customizable** - Configurable positioning, colors, and behavior
15
+ - 📦 **TypeScript Support** - Full type definitions and IntelliSense support
16
+ - 🚀 **Zero Config** - Works out of the box with minimal setup
17
+ - 🔒 **Secure** - Built-in XSS protection and Shadow DOM isolation
18
+
19
+ ## 📦 Installation
20
+
21
+ ### npm/yarn (Recommended)
22
+
23
+ ```bash
24
+ # npm
25
+ npm install @virtual-chat/sdk
26
+
27
+ # yarn
28
+ yarn add @virtual-chat/sdk
29
+
30
+ # pnpm
31
+ pnpm add @virtual-chat/sdk
32
+ ```
33
+
34
+ ### CDN (Browser)
35
+
36
+ ### Option A: UMD (script tag) - Floating Button Mode
37
+
38
+ ```html
39
+ <!-- 1) Include SDK from your server -->
40
+ <script src="https://YOUR_SERVER_DOMAIN/sdk/chat-sdk.umd.js"></script>
41
+
42
+ <!-- 2) Create a container (optional for floating mode) -->
43
+ <div id="chat-container"></div>
44
+
45
+ <!-- 3) Initialize with floating button mode -->
46
+ <script>
47
+ const chat = ChatSDK.init({
48
+ container: '#chat-container',
49
+ projectId: 'YOUR_PROJECT_ID',
50
+ username: 'Visitor',
51
+ language: 'zh',
52
+ uiTemplate: 'whatsapp',
53
+ autoJoin: true,
54
+ // point SDK API to your server
55
+ apiBaseUrl: 'https://YOUR_SERVER_DOMAIN',
56
+ socketUrl: 'https://YOUR_SERVER_DOMAIN',
57
+
58
+ // Floating button mode (recommended for third-party sites)
59
+ mode: 'floating',
60
+ floatingButton: {
61
+ position: 'bottom-right',
62
+ offset: { bottom: 20, right: 20 },
63
+ icon: 'chat'
64
+ }
65
+ })
66
+ // No need to call chat.open() in floating mode - button handles it
67
+ </script>
68
+ ```
69
+
70
+ ### Option B: ESM (module) - Floating Button Mode
71
+
72
+ ```html
73
+ <script type="module">
74
+ import { ChatSDK } from 'https://YOUR_SERVER_DOMAIN/sdk/chat-sdk.esm.js'
75
+ const chat = ChatSDK.init({
76
+ container: '#chat-container',
77
+ projectId: 'YOUR_PROJECT_ID',
78
+ username: 'Visitor',
79
+ language: 'en',
80
+ autoJoin: true,
81
+ apiBaseUrl: 'https://YOUR_SERVER_DOMAIN',
82
+ socketUrl: 'https://YOUR_SERVER_DOMAIN',
83
+
84
+ // Floating button mode (recommended for third-party sites)
85
+ mode: 'floating',
86
+ floatingButton: {
87
+ position: 'bottom-right',
88
+ offset: { bottom: 20, right: 20 }
89
+ }
90
+ })
91
+ // No need to call chat.open() in floating mode - button handles it
92
+ </script>
93
+ ```
94
+
95
+ ## Display Modes
96
+
97
+ ### Floating Button Mode (Recommended for Third-Party Sites)
98
+ - **Default behavior**: Shows a floating button, expands to full-screen chat when clicked
99
+ - **Configuration**: `mode: 'floating'` with `floatingButton` options
100
+ - **Best for**: Third-party website integration, non-intrusive user experience
101
+
102
+ ### Full-Screen Mode (Traditional)
103
+ - **Behavior**: Directly shows the chat interface
104
+ - **Configuration**: `mode: 'fullscreen'` or omit the mode property
105
+ - **Best for**: Dedicated chat pages, internal applications
106
+
107
+ ## Notes:
108
+ - No API key is required on the client.
109
+ - Replace `YOUR_SERVER_DOMAIN` with your actual server domain where this app is hosted.
110
+ - `projectId` can be found in the Admin panel (Projects list).
111
+ - CORS: ensure your server allows the third‑party origin if needed.
112
+ - Optional UI customization: `primaryColor`, `backgroundColor`, `width`, `height`.
113
+ - **Floating button positioning**: `position` ('bottom-right', 'bottom-left', 'top-right', 'top-left'), `offset` (pixels from edges), `zIndex`
114
+
115
+
116
+ ### 1. Include the SDK
117
+ ## Floating Button Configuration Examples
118
+
119
+ ### Basic Floating Button
120
+ ```javascript
121
+ const chat = ChatSDK.init({
122
+ container: document.body,
123
+ projectId: 'YOUR_PROJECT_ID',
124
+ mode: 'floating',
125
+ apiBaseUrl: 'https://YOUR_SERVER_DOMAIN',
126
+ socketUrl: 'https://YOUR_SERVER_DOMAIN'
127
+ })
128
+ ```
129
+
130
+ ### Custom Positioned Floating Button
131
+ ```javascript
132
+ const chat = ChatSDK.init({
133
+ container: document.body,
134
+ projectId: 'YOUR_PROJECT_ID',
135
+ mode: 'floating',
136
+ floatingButton: {
137
+ position: 'bottom-left', // 'bottom-right', 'bottom-left', 'top-right', 'top-left'
138
+ offset: { bottom: 24, left: 24 }, // Distance from edges in pixels
139
+ icon: 'chat', // Button icon type
140
+ zIndex: 2147483000 // CSS z-index for layering
141
+ },
142
+ apiBaseUrl: 'https://YOUR_SERVER_DOMAIN',
143
+ socketUrl: 'https://YOUR_SERVER_DOMAIN'
144
+ })
145
+ ```
146
+
147
+ ### Full-Screen Mode (Traditional)
148
+ ```javascript
149
+ const chat = ChatSDK.init({
150
+ container: '#chat-container',
151
+ projectId: 'YOUR_PROJECT_ID',
152
+ mode: 'fullscreen', // or omit this line for default behavior
153
+ apiBaseUrl: 'https://YOUR_SERVER_DOMAIN',
154
+ socketUrl: 'https://YOUR_SERVER_DOMAIN'
155
+ })
156
+ chat.open() // Required for full-screen mode
157
+ ```
158
+
159
+ ```html
160
+ <!-- Via CDN -->
161
+ <script src="https://cdn.example.com/chat-sdk.umd.js"></script>
162
+
163
+ <!-- Or download and host locally -->
164
+ <script src="path/to/chat-sdk.umd.js"></script>
165
+ ```
166
+
167
+ ### 2. Create a Container
168
+
169
+ ```html
170
+ <div id="chat-container"></div>
171
+ ```
172
+
173
+ ### 3. Initialize the Chat
174
+
175
+ ```javascript
176
+ const chat = ChatSDK.init({
177
+ container: '#chat-container',
178
+ projectId: 'your-project-id',
179
+ username: 'John Doe',
180
+ language: 'en',
181
+ theme: 'light',
182
+ onReady: () => console.log('Chat ready!'),
183
+ onMessage: (message) => console.log('New message:', message)
184
+ });
185
+ ```
186
+
187
+ ## Configuration Options
188
+
189
+ ### Required Options
190
+
191
+ | Option | Type | Description |
192
+ |--------|------|-------------|
193
+ | `container` | `string \| HTMLElement` | CSS selector or DOM element for the chat widget |
194
+ | `projectId` | `string` | Unique identifier for your chat project |
195
+
196
+ ### Optional Options
197
+
198
+ | Option | Type | Default | Description |
199
+ |--------|------|---------|-------------|
200
+ | `templateId` | `string` | `undefined` | Specific template to load (uses project default if not specified) |
201
+ | `userId` | `string` | Auto-generated | Unique user identifier |
202
+ | `username` | `string` | Auto-generated | Display name for the user |
203
+ | `language` | `string` | `'en'` | Language code (en, zh, es, fr, de, ja, ko, etc.) |
204
+ | `theme` | `'light' \| 'dark' \| 'auto'` | `'light'` | UI theme |
205
+ | `uiTemplate` | `'whatsapp' \| 'telegram' \| 'discord' \| 'slack'` | `'whatsapp'` | Chat UI style |
206
+ | `width` | `string \| number` | `'400px'` | Widget width |
207
+ | `height` | `string \| number` | `'600px'` | Widget height |
208
+ | `autoJoin` | `boolean` | `false` | Automatically join chat on initialization |
209
+ | `showAvatars` | `boolean` | `true` | Show user avatars |
210
+ | `showUsernames` | `boolean` | `true` | Show usernames |
211
+ | `allowInput` | `boolean` | `true` | Allow user to send messages |
212
+
213
+ ### API Configuration
214
+
215
+ | Option | Type | Default | Description |
216
+ |--------|------|---------|-------------|
217
+ | `apiBaseUrl` | `string` | Current origin | Base URL for API requests |
218
+ | `socketUrl` | `string` | Current origin | WebSocket server URL |
219
+ | `token` | `string` | `undefined` | Authentication token |
220
+
221
+ ### Event Callbacks
222
+
223
+ | Callback | Parameters | Description |
224
+ |----------|------------|-------------|
225
+ | `onReady` | `()` | Called when SDK is initialized |
226
+ | `onOpen` | `()` | Called when chat widget opens |
227
+ | `onClose` | `()` | Called when chat widget closes |
228
+ | `onJoin` | `({ userId, username })` | Called when user joins chat |
229
+ | `onMessage` | `(message)` | Called when any message is received |
230
+ | `onUserMessage` | `(message)` | Called when user sends a message |
231
+ | `onError` | `(error)` | Called when an error occurs |
232
+ | `onLanguageChange` | `(language)` | Called when language changes |
233
+ | `onThemeChange` | `(theme)` | Called when theme changes |
234
+
235
+ ## API Methods
236
+
237
+ ### Core Methods
238
+
239
+ ```javascript
240
+ // Open/close the chat widget
241
+ chat.open();
242
+ chat.close();
243
+
244
+ // Join/leave the chat
245
+ chat.joinChat();
246
+ chat.leaveChat();
247
+
248
+ // Send a message programmatically
249
+ chat.sendMessage('Hello world!', 'text');
250
+
251
+ // Destroy the widget
252
+ chat.destroy();
253
+ ```
254
+
255
+ ### Configuration Methods
256
+
257
+ ```javascript
258
+ // Change language
259
+ chat.setLanguage('zh');
260
+
261
+ // Change theme
262
+ chat.setTheme('dark');
263
+
264
+ // Switch template
265
+ chat.setTemplate('template-id');
266
+ ```
267
+
268
+ ### State Methods
269
+
270
+ ```javascript
271
+ // Check widget state
272
+ const isOpen = chat.isOpen();
273
+ const isJoined = chat.isJoined();
274
+
275
+ // Get configuration
276
+ const config = chat.getConfig();
277
+
278
+ // Get message history
279
+ const messages = chat.getMessages();
280
+ ```
281
+
282
+ ### Event Methods
283
+
284
+ ```javascript
285
+ // Listen to events
286
+ chat.on('message', (message) => {
287
+ console.log('New message:', message);
288
+ });
289
+
290
+ // Remove event listeners
291
+ chat.off('message');
292
+
293
+ // Emit custom events
294
+ chat.emit('custom-event', data);
295
+ ```
296
+
297
+ ## Examples
298
+
299
+ ### Basic Chat Widget
300
+
301
+ ```javascript
302
+ const chat = ChatSDK.init({
303
+ container: '#chat',
304
+ projectId: 'demo-project',
305
+ username: 'Visitor',
306
+ autoJoin: true
307
+ });
308
+ ```
309
+
310
+ ### Customized Widget
311
+
312
+ ```javascript
313
+ const chat = ChatSDK.init({
314
+ container: document.getElementById('chat-container'),
315
+ projectId: 'my-project',
316
+ templateId: 'customer-support',
317
+ username: 'Customer',
318
+ language: 'zh',
319
+ theme: 'dark',
320
+ width: '100%',
321
+ height: '500px',
322
+ uiTemplate: 'telegram',
323
+
324
+ onReady: () => {
325
+ console.log('Chat is ready!');
326
+ chat.open();
327
+ },
328
+
329
+ onMessage: (message) => {
330
+ // Track messages in analytics
331
+ analytics.track('chat_message_received', {
332
+ content: message.content,
333
+ type: message.messageType
334
+ });
335
+ },
336
+
337
+ onUserMessage: (message) => {
338
+ // Track user messages
339
+ analytics.track('chat_message_sent', {
340
+ content: message.content
341
+ });
342
+ }
343
+ });
344
+ ```
345
+
346
+ ### Multi-language Support
347
+
348
+ ```javascript
349
+ const chat = ChatSDK.init({
350
+ container: '#chat',
351
+ projectId: 'support-chat',
352
+ language: 'en' // Start with English
353
+ });
354
+
355
+ // Language switcher
356
+ document.getElementById('lang-zh').addEventListener('click', () => {
357
+ chat.setLanguage('zh');
358
+ });
359
+
360
+ document.getElementById('lang-es').addEventListener('click', () => {
361
+ chat.setLanguage('es');
362
+ });
363
+ ```
364
+
365
+ ### Event-driven Integration
366
+
367
+ ```javascript
368
+ const chat = ChatSDK.init({
369
+ container: '#chat',
370
+ projectId: 'sales-demo',
371
+
372
+ onJoin: ({ userId, username }) => {
373
+ // Notify your backend
374
+ fetch('/api/chat-joined', {
375
+ method: 'POST',
376
+ body: JSON.stringify({ userId, username })
377
+ });
378
+ },
379
+
380
+ onUserMessage: (message) => {
381
+ // Process user messages
382
+ if (message.content.includes('pricing')) {
383
+ // Show pricing modal
384
+ showPricingModal();
385
+ }
386
+ },
387
+
388
+ onError: (error) => {
389
+ // Handle errors gracefully
390
+ console.error('Chat error:', error);
391
+ showErrorNotification('Chat temporarily unavailable');
392
+ }
393
+ });
394
+ ```
395
+
396
+ ## Browser Support
397
+
398
+ - Chrome 60+
399
+ - Firefox 55+
400
+ - Safari 12+
401
+ - Edge 79+
402
+ - Mobile browsers (iOS Safari, Chrome Mobile)
403
+
404
+ ## TypeScript Support
405
+
406
+ The SDK includes full TypeScript definitions:
407
+
408
+ ```typescript
409
+ import { ChatSDK, ChatSDKConfig, ChatMessage } from '@virtual-chat/sdk';
410
+
411
+ const config: ChatSDKConfig = {
412
+ container: '#chat',
413
+ projectId: 'my-project',
414
+ onMessage: (message: ChatMessage) => {
415
+ console.log(message.content);
416
+ }
417
+ };
418
+
419
+ const chat = ChatSDK.init(config);
420
+ ```
421
+
422
+ ## Error Handling
423
+
424
+ ```javascript
425
+ const chat = ChatSDK.init({
426
+ container: '#chat',
427
+ projectId: 'my-project',
428
+
429
+ onError: (error) => {
430
+ switch (error.code) {
431
+ case 'CONTAINER_NOT_FOUND':
432
+ console.error('Chat container not found');
433
+ break;
434
+ case 'PROJECT_LOAD_ERROR':
435
+ console.error('Failed to load project');
436
+ break;
437
+ case 'SOCKET_CONNECTION_ERROR':
438
+ console.error('Connection failed');
439
+ break;
440
+ default:
441
+ console.error('Unknown error:', error.message);
442
+ }
443
+ }
444
+ });
445
+ ```
446
+
447
+ ## Building from Source
448
+
449
+ ```bash
450
+ # Install dependencies
451
+ npm install
452
+
453
+ # Build for production
454
+ npm run build
455
+
456
+ # Build and watch for development
457
+ npm run dev
458
+
459
+ # Type checking
460
+ npm run type-check
461
+ ```
462
+
463
+ ## License
464
+
465
+ MIT License - see LICENSE file for details.