@data-netmonk/mona-chat-widget 2.1.36 → 2.2.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.
Files changed (4) hide show
  1. package/README.md +419 -9
  2. package/dist/index.cjs +61 -60
  3. package/dist/index.js +21617 -11642
  4. package/package.json +6 -4
package/README.md CHANGED
@@ -10,7 +10,7 @@ Chat widget package developed by Netmonk data & solution team to be imported in
10
10
 
11
11
  1. Install dependencies
12
12
  ```
13
- npm install
13
+ npm install --legacy-peer-deps
14
14
  ```
15
15
  2. Copy .env.example
16
16
  ```
@@ -99,6 +99,45 @@ For responses with buttons:
99
99
 
100
100
  ---
101
101
 
102
+ ### Recent Updates & Breaking Changes
103
+
104
+ ---
105
+
106
+ **Latest Version Changes:**
107
+
108
+ ⚠️ **Breaking Changes:**
109
+ 1. **Removed `type` and `agentType` props** - These parameters are no longer used and have been removed from all components
110
+ 2. **Renamed `botServerUrl` to `webhookUrl`** - For better clarity and consistency
111
+ 3. **`webhookUrl` is now required** - Must be provided as a prop (falls back to env vars if not provided)
112
+
113
+ ✨ **New Features:**
114
+ 1. **Authentication support** - Automatic token management with refresh on 401 errors
115
+ - Pass `authUrl` in the `data` prop
116
+ - Widget handles token lifecycle automatically
117
+ 2. **Enhanced data prop** - Support for custom variables passed to backend via `data` prop
118
+ 3. **Improved error handling** - Better fallback mechanisms and error messages
119
+
120
+ 📝 **Migration Guide:**
121
+ ```jsx
122
+ // Old usage (deprecated)
123
+ <ChatWidget
124
+ userId="user123"
125
+ sourceId="source456"
126
+ type="prime"
127
+ botServerUrl="https://api.example.com"
128
+ />
129
+
130
+ // New usage (current)
131
+ <ChatWidget
132
+ userId="user123"
133
+ sourceId="source456"
134
+ webhookUrl="https://api.example.com/webhook"
135
+ data="authUrl=https://api.example.com/login/chatwidget~username=John"
136
+ />
137
+ ```
138
+
139
+ ---
140
+
102
141
  ### Library (how to update and publish)
103
142
 
104
143
  ---
@@ -146,26 +185,397 @@ For responses with buttons:
146
185
 
147
186
  ---
148
187
 
149
- 1. Install package
150
- ```
151
- npm install @aaiiccaa/mona-chat-widget
188
+ 1. **Install package**
189
+ ```bash
190
+ npm install @data-netmonk/mona-chat-widget
152
191
  ```
153
- 2. Import styles on your `App.jsx` or `index.jsx`
192
+
193
+ 2. **Import styles on your `App.jsx` or `index.jsx`**
154
194
 
155
195
  ```jsx
156
- import "@aaiiccaa/mona-chat-widget/dist/style.css";
196
+ import "@data-netmonk/mona-chat-widget/dist/style.css";
157
197
  ```
158
198
 
159
- 3. Import & use component
199
+ 3. **Import & use component**
160
200
 
161
201
  ```jsx
162
- import { ChatWidget } from "@aaiiccaa/mona-chat-widget";
202
+ import { ChatWidget } from "@data-netmonk/mona-chat-widget";
163
203
 
164
- <ChatWidget type={"prime"} userId={"1234"} sourceId={"1"}/>;
204
+ function App() {
205
+ return (
206
+ <ChatWidget
207
+ userId="user123"
208
+ sourceId="691e1b5952068ff7aaeccffc9"
209
+ webhookUrl="https://your-backend-url.com"
210
+ />
211
+ );
212
+ }
165
213
  ```
166
214
 
167
215
  ---
168
216
 
217
+ ### Component Props
218
+
219
+ ---
220
+
221
+ #### Required Props
222
+
223
+ | Prop | Type | Description |
224
+ |------|------|-------------|
225
+ | `userId` | `string` | **Required.** Unique identifier for the user |
226
+ | `sourceId` | `string` | **Required.** Source/channel identifier for the chat |
227
+ | `webhookUrl` | `string` | **Required.** Backend webhook URL (falls back to env vars if not provided) |
228
+
229
+ #### Optional Props
230
+
231
+ | Prop | Type | Default | Description |
232
+ |------|------|---------|-------------|
233
+ | `data` | `string` | - | Custom variables and auth URL in format `key1=value1~key2=value2~authUrl=https://...` |
234
+ | `width` | `string` | `"25vw"` | Widget width (CSS value) |
235
+ | `height` | `string` | `"90vh"` | Widget height (CSS value) |
236
+ | `right` | `string` | `"1.25rem"` | Distance from right edge |
237
+ | `bottom` | `string` | `"1.25rem"` | Distance from bottom edge |
238
+ | `zIndex` | `number` | `2000` | CSS z-index for widget positioning |
239
+ | `position` | `string` | `"fixed"` | CSS position (`"fixed"` or `"relative"`) |
240
+ | `onToggle` | `function` | - | Callback when widget opens/closes: `(isOpen: boolean) => void` |
241
+
242
+ ---
243
+
244
+ ### Usage Examples
245
+
246
+ ---
247
+
248
+ #### Basic Usage
249
+
250
+ ```jsx
251
+ import { ChatWidget } from "@data-netmonk/mona-chat-widget";
252
+ import "@data-netmonk/mona-chat-widget/dist/style.css";
253
+
254
+ function App() {
255
+ return (
256
+ <ChatWidget
257
+ userId="user123"
258
+ sourceId="691e1b5952068ff7aaeccffc9"
259
+ webhookUrl="https://api.example.com/webhook"
260
+ />
261
+ );
262
+ }
263
+ ```
264
+
265
+ #### With Custom Variables
266
+
267
+ Pass custom user data like username, phone number, etc. to the backend:
268
+
269
+ ```jsx
270
+ <ChatWidget
271
+ userId="user123"
272
+ sourceId="691e1b5952068ff7aaeccffc9"
273
+ webhookUrl="https://api.example.com/webhook"
274
+ data="username=John Doe~telephone_number=+628123456789~email=john@example.com"
275
+ />
276
+ ```
277
+
278
+ **Variables sent to backend:**
279
+ ```json
280
+ {
281
+ "chat_id": "...",
282
+ "session_id": "...",
283
+ "user_id": "user123",
284
+ "message": "Hello",
285
+ "type": "text",
286
+ "variables": {
287
+ "username": "John Doe",
288
+ "telephone_number": "+628123456789",
289
+ "email": "john@example.com"
290
+ }
291
+ }
292
+ ```
293
+
294
+ #### With Authentication (NEW!)
295
+
296
+ The widget supports automatic authentication with token refresh on expiry:
297
+
298
+ ```jsx
299
+ <ChatWidget
300
+ userId="user123"
301
+ sourceId="691e1b5952068ff7aaeccffc9"
302
+ webhookUrl="https://api.example.com/webhook"
303
+ data="authUrl=https://api.example.com/login/chatwidget~username=John Doe"
304
+ />
305
+ ```
306
+
307
+ **How authentication works:**
308
+
309
+ 1. **Initial Authentication**: When the widget loads (on Launcher mount), if `authUrl` is provided in the `data` prop, it automatically calls the auth API:
310
+ ```
311
+ POST {authUrl}
312
+ Body: { "user_id": "user123" }
313
+ Response: { "token": "eyJ..." }
314
+ ```
315
+
316
+ 2. **Token Usage**: The received token is automatically included in all webhook API calls as `authToken` in the `variables` object:
317
+ ```json
318
+ {
319
+ "chat_id": "...",
320
+ "user_id": "user123",
321
+ "message": "Hello",
322
+ "variables": {
323
+ "authToken": "eyJ...",
324
+ "username": "John Doe"
325
+ }
326
+ }
327
+ ```
328
+
329
+ 3. **Automatic Token Refresh**: If the webhook returns **401 Unauthorized** (token expired/revoked), the widget automatically:
330
+ - Calls the `authUrl` again to get a fresh token
331
+ - Updates the `authToken` in variables
332
+ - Retries the failed request with the new token
333
+ - This happens transparently without user interaction
334
+
335
+ **Combined example with auth and custom variables:**
336
+ ```jsx
337
+ <ChatWidget
338
+ userId="user123"
339
+ sourceId="691e1b5952068ff7aaeccffc9"
340
+ webhookUrl="https://api.example.com/webhook"
341
+ data="authUrl=https://api.example.com/login/chatwidget~username=John~email=john@example.com~phone=+628123456789"
342
+ />
343
+ ```
344
+
345
+ **Note:** The `data` prop is for optional parameters only (custom variables and `authUrl`). Required parameters (`userId`, `sourceId`, `webhookUrl`) must be passed as direct props.
346
+
347
+ #### Custom Styling
348
+
349
+ ```jsx
350
+ <ChatWidget
351
+ userId="user123"
352
+ sourceId="691e1b5952068ff7aaeccffc9"
353
+ width="400px"
354
+ height="600px"
355
+ right="20px"
356
+ bottom="20px"
357
+ zIndex={9999}
358
+ />
359
+ ```
360
+
361
+ #### Embedded in Layout (Relative Positioning)
362
+
363
+ ```jsx
364
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 400px' }}>
365
+ <div>Main content</div>
366
+ <ChatWidget
367
+ userId="user123"
368
+ sourceId="691e1b5952068ff7aaeccffc9"
369
+ position="relative"
370
+ width="100%"
371
+ height="100vh"
372
+ />
373
+ </div>
374
+ ```
375
+
376
+ #### With Toggle Callback
377
+
378
+ ```jsx
379
+ function App() {
380
+ const handleToggle = (isOpen) => {
381
+ console.log('Chat widget is', isOpen ? 'open' : 'closed');
382
+ // Track analytics, update UI, etc.
383
+ };
384
+
385
+ return (
386
+ <ChatWidget
387
+ userId="user123"
388
+ sourceId="691e1b5952068ff7aaeccffc9"
389
+ onToggle={handleToggle}
390
+ />
391
+ );
392
+ }
393
+ ```
394
+
395
+ #### Full-Screen Widget
396
+
397
+ ```jsx
398
+ <ChatWidget
399
+ userId="user123"
400
+ sourceId="691e1b5952068ff7aaeccffc9"
401
+ width="100vw"
402
+ height="100vh"
403
+ right="0"
404
+ bottom="0"
405
+ />
406
+ ```
407
+
408
+ ---
409
+
410
+ ### Data Prop Format & Helper Function
411
+
412
+ ---
413
+
414
+ The `data` prop allows you to pass custom variables and authentication URL via a single string. This is especially useful when you need to dynamically pass user-specific data or pass it through URL parameters.
415
+
416
+ **Format:** `key=value` pairs separated by `~`
417
+
418
+ **Example data string:**
419
+ ```
420
+ username=John Doe~phone=+1234567890~email=john@example.com
421
+ ```
422
+
423
+ **With authentication:**
424
+ ```
425
+ authUrl=https://api.example.com/login/chatwidget~username=John Doe~email=john@example.com
426
+ ```
427
+
428
+ **Special keys:**
429
+ - `authUrl`: Authentication endpoint URL (see "With Authentication" section above)
430
+ - All other keys: Custom variables passed to webhook in `variables` object
431
+
432
+ #### Building Data String Programmatically
433
+
434
+ Instead of manually constructing the data string, you can create a helper function to build it dynamically. This approach is recommended for production applications as it:
435
+ - Prevents syntax errors in the data string format
436
+ - Makes the code more maintainable and readable
437
+ - Allows for conditional inclusion of parameters
438
+ - Handles URL encoding automatically if needed
439
+
440
+ **Create a helper function** (`src/helpers/chatWidget.js` or similar):
441
+
442
+ ```jsx
443
+ /**
444
+ * Builds the data string for ChatWidget component
445
+ * @param {Object} params - Object containing all parameters
446
+ * @param {string} params.authUrl - Optional: Authentication endpoint URL
447
+ * @param {string} params.username - Optional: User's display name
448
+ * @param {string} params.email - Optional: User's email address
449
+ * @param {string} params.phone - Optional: User's phone number
450
+ * @param {Object} params.customFields - Optional: Any additional custom fields as key-value pairs
451
+ * @returns {string} Formatted data string for ChatWidget (always returns a string)
452
+ *
453
+ * @example
454
+ * // Returns: "authUrl=https://api.com~username=John~email=john@example.com"
455
+ * buildChatWidgetData({
456
+ * authUrl: "https://api.com",
457
+ * username: "John",
458
+ * email: "john@example.com"
459
+ * });
460
+ */
461
+ export const buildChatWidgetData = ({
462
+ authUrl,
463
+ username,
464
+ email,
465
+ phone,
466
+ customFields = {}
467
+ }) => {
468
+ const parts = [];
469
+
470
+ // Add authUrl first if provided (for authentication)
471
+ if (authUrl) {
472
+ parts.push(`authUrl=${authUrl}`);
473
+ }
474
+
475
+ // Add standard fields
476
+ if (username) {
477
+ parts.push(`username=${encodeURIComponent(username)}`);
478
+ }
479
+
480
+ if (email) {
481
+ parts.push(`email=${encodeURIComponent(email)}`);
482
+ }
483
+
484
+ if (phone) {
485
+ parts.push(`phone=${encodeURIComponent(phone)}`);
486
+ }
487
+
488
+ // Add any custom fields dynamically
489
+ // Note: customFields is just a convenience parameter for the helper function
490
+ // Each field will be flattened into the string format: key=value~key2=value2
491
+ Object.entries(customFields).forEach(([key, value]) => {
492
+ if (value) {
493
+ parts.push(`${key}=${encodeURIComponent(String(value))}`);
494
+ }
495
+ });
496
+
497
+ // Returns a string like: "authUrl=...~username=John~email=john@example.com~department=Engineering"
498
+ return parts.join("~");
499
+ };
500
+ ```
501
+
502
+ **Important:** The `customFields` parameter is **NOT** passed as an object to the widget. It's just a convenient way to pass multiple additional fields to the helper function. The function flattens everything into a single string format.
503
+
504
+ **Usage in your application:**
505
+
506
+ ```jsx
507
+ import { ChatWidget } from "@data-netmonk/mona-chat-widget";
508
+ import "@data-netmonk/mona-chat-widget/dist/style.css";
509
+ import { buildChatWidgetData } from "./helpers/chatWidget";
510
+
511
+ function App() {
512
+ // Get user data from your auth system, state, or props
513
+ const user = {
514
+ id: "user123",
515
+ name: "John Doe",
516
+ email: "john@example.com",
517
+ phone: "+628123456789"
518
+ };
519
+
520
+ // Build the data string
521
+ const customData = buildChatWidgetData({
522
+ authUrl: "https://api.example.com/login/chatwidget",
523
+ username: user.name,
524
+ email: user.email,
525
+ phone: user.phone,
526
+ customFields: {
527
+ department: "Engineering",
528
+ role: "Developer",
529
+ company: "Acme Corp"
530
+ }
531
+ });
532
+
533
+ // customData is now a STRING like:
534
+ // "authUrl=https://api.example.com/login/chatwidget~username=John%20Doe~email=john@example.com~phone=%2B628123456789~department=Engineering~role=Developer~company=Acme%20Corp"
535
+
536
+ return (
537
+ <ChatWidget
538
+ userId={user.id}
539
+ sourceId="691e1b5952068ff7aaeccffc9"
540
+ webhookUrl="https://api.example.com/webhook"
541
+ data={customData} // Pass the STRING to data prop
542
+ />
543
+ );
544
+ }
545
+ ```
546
+
547
+ **With conditional authentication:**
548
+
549
+ ```jsx
550
+ function App() {
551
+ const authUrl = import.meta.env.VITE_CHAT_AUTH_ENABLED === "true"
552
+ ? import.meta.env.VITE_CHAT_AUTH_URL
553
+ : null;
554
+
555
+ const customData = buildChatWidgetData({
556
+ authUrl: authUrl, // Only included if authentication is enabled
557
+ username: getCurrentUser().name,
558
+ email: getCurrentUser().email
559
+ });
560
+
561
+ return (
562
+ <ChatWidget
563
+ userId={getCurrentUser().id}
564
+ sourceId="691e1b5952068ff7aaeccffc9"
565
+ webhookUrl={import.meta.env.VITE_WEBHOOK_URL}
566
+ data={customData}
567
+ />
568
+ );
569
+ }
570
+ ```
571
+
572
+ **The helper function handles:**
573
+ - ✅ Proper formatting with `~` separators
574
+ - ✅ URL encoding for special characters
575
+ - ✅ Conditional parameter inclusion (only adds if value exists)
576
+ - ✅ Support for dynamic custom fields
577
+ - ✅ Type safety and documentation via JSDoc comments
578
+
169
579
  ### Standalone app (for demonstration)
170
580
 
171
581
  1. **How to run locally** (access at `http://localhost:${PORT}/${APP_PREFIX}`)