chatly-sdk 0.0.5 → 0.0.7

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 (56) hide show
  1. package/CONTRIBUTING.md +658 -0
  2. package/IMPROVEMENTS.md +402 -0
  3. package/README.md +1538 -164
  4. package/dist/index.d.ts +430 -9
  5. package/dist/index.js +1420 -63
  6. package/examples/01-basic-chat/README.md +61 -0
  7. package/examples/01-basic-chat/index.js +58 -0
  8. package/examples/01-basic-chat/package.json +13 -0
  9. package/examples/02-group-chat/README.md +78 -0
  10. package/examples/02-group-chat/index.js +76 -0
  11. package/examples/02-group-chat/package.json +13 -0
  12. package/examples/03-offline-messaging/README.md +73 -0
  13. package/examples/03-offline-messaging/index.js +80 -0
  14. package/examples/03-offline-messaging/package.json +13 -0
  15. package/examples/04-live-chat/README.md +80 -0
  16. package/examples/04-live-chat/index.js +114 -0
  17. package/examples/04-live-chat/package.json +13 -0
  18. package/examples/05-hybrid-messaging/README.md +71 -0
  19. package/examples/05-hybrid-messaging/index.js +106 -0
  20. package/examples/05-hybrid-messaging/package.json +13 -0
  21. package/examples/06-postgresql-integration/README.md +101 -0
  22. package/examples/06-postgresql-integration/adapters/groupStore.js +73 -0
  23. package/examples/06-postgresql-integration/adapters/messageStore.js +47 -0
  24. package/examples/06-postgresql-integration/adapters/userStore.js +40 -0
  25. package/examples/06-postgresql-integration/index.js +92 -0
  26. package/examples/06-postgresql-integration/package.json +14 -0
  27. package/examples/06-postgresql-integration/schema.sql +58 -0
  28. package/examples/08-customer-support/README.md +70 -0
  29. package/examples/08-customer-support/index.js +104 -0
  30. package/examples/08-customer-support/package.json +13 -0
  31. package/examples/README.md +105 -0
  32. package/jest.config.cjs +28 -0
  33. package/package.json +12 -8
  34. package/src/chat/ChatSession.ts +81 -0
  35. package/src/chat/GroupSession.ts +79 -0
  36. package/src/constants.ts +61 -0
  37. package/src/crypto/e2e.ts +0 -20
  38. package/src/index.ts +525 -63
  39. package/src/models/mediaTypes.ts +58 -0
  40. package/src/models/message.ts +4 -1
  41. package/src/transport/adapters.ts +51 -1
  42. package/src/transport/memoryTransport.ts +75 -13
  43. package/src/transport/websocketClient.ts +269 -21
  44. package/src/transport/websocketServer.ts +26 -26
  45. package/src/utils/errors.ts +97 -0
  46. package/src/utils/logger.ts +96 -0
  47. package/src/utils/mediaUtils.ts +235 -0
  48. package/src/utils/messageQueue.ts +162 -0
  49. package/src/utils/validation.ts +99 -0
  50. package/test/crypto.test.ts +122 -35
  51. package/test/sdk.test.ts +276 -0
  52. package/test/validation.test.ts +64 -0
  53. package/tsconfig.json +11 -10
  54. package/tsconfig.test.json +11 -0
  55. package/src/ChatManager.ts +0 -103
  56. package/src/crypto/keyManager.ts +0 -28
@@ -0,0 +1,658 @@
1
+ # Contributing to Chatly SDK
2
+
3
+ Thank you for your interest in contributing to Chatly SDK! This document provides guidelines and instructions for contributing to the project.
4
+
5
+ ## 📋 Table of Contents
6
+
7
+ - [Code of Conduct](#code-of-conduct)
8
+ - [Getting Started](#getting-started)
9
+ - [Development Setup](#development-setup)
10
+ - [Project Structure](#project-structure)
11
+ - [Development Workflow](#development-workflow)
12
+ - [Coding Standards](#coding-standards)
13
+ - [Testing Guidelines](#testing-guidelines)
14
+ - [Commit Guidelines](#commit-guidelines)
15
+ - [Pull Request Process](#pull-request-process)
16
+ - [Release Process](#release-process)
17
+
18
+ ---
19
+
20
+ ## 📜 Code of Conduct
21
+
22
+ ### Our Pledge
23
+
24
+ We are committed to providing a welcoming and inclusive environment for all contributors. We expect all participants to:
25
+
26
+ - Use welcoming and inclusive language
27
+ - Be respectful of differing viewpoints and experiences
28
+ - Gracefully accept constructive criticism
29
+ - Focus on what is best for the community
30
+ - Show empathy towards other community members
31
+
32
+ ### Unacceptable Behavior
33
+
34
+ - Harassment, trolling, or discriminatory comments
35
+ - Publishing others' private information without permission
36
+ - Other conduct which could reasonably be considered inappropriate
37
+
38
+ ---
39
+
40
+ ## 🚀 Getting Started
41
+
42
+ ### Prerequisites
43
+
44
+ - **Node.js**: >= 16.x
45
+ - **npm**: >= 8.x
46
+ - **Git**: Latest version
47
+ - **TypeScript**: 5.x (installed as dev dependency)
48
+
49
+ ### Fork and Clone
50
+
51
+ 1. Fork the repository on GitHub
52
+ 2. Clone your fork locally:
53
+
54
+ ```bash
55
+ git clone https://github.com/YOUR_USERNAME/chatly-sdk.git
56
+ cd chatly-sdk
57
+ ```
58
+
59
+ 3. Add the upstream repository:
60
+
61
+ ```bash
62
+ git remote add upstream https://github.com/bharath-arch/chatly-sdk.git
63
+ ```
64
+
65
+ ---
66
+
67
+ ## 💻 Development Setup
68
+
69
+ ### Install Dependencies
70
+
71
+ ```bash
72
+ npm install
73
+ ```
74
+
75
+ ### Build the Project
76
+
77
+ ```bash
78
+ npm run build
79
+ ```
80
+
81
+ ### Run Tests
82
+
83
+ ```bash
84
+ # Run all tests
85
+ npm test
86
+
87
+ # Run tests in watch mode
88
+ npm run test:watch
89
+
90
+ # Run tests with coverage
91
+ npm run test:coverage
92
+ ```
93
+
94
+ ### Development Commands
95
+
96
+ ```bash
97
+ # Build the SDK
98
+ npm run build
99
+
100
+ # Run TypeScript compiler
101
+ npx tsc --noEmit
102
+
103
+ # Format code (if prettier is configured)
104
+ npm run format
105
+
106
+ # Lint code (if eslint is configured)
107
+ npm run lint
108
+ ```
109
+
110
+ ---
111
+
112
+ ## 📁 Project Structure
113
+
114
+ ```
115
+ e2e-chat-sdk/
116
+ ├── src/
117
+ │ ├── chat/ # Chat session implementations
118
+ │ │ ├── chatSession.ts
119
+ │ │ └── groupSession.ts
120
+ │ ├── crypto/ # Cryptography implementations
121
+ │ │ ├── e2e.ts # End-to-end encryption
122
+ │ │ └── keys.ts # Key generation
123
+ │ ├── models/ # Data models
124
+ │ │ ├── user.ts
125
+ │ │ ├── message.ts
126
+ │ │ └── group.ts
127
+ │ ├── stores/ # Storage adapters
128
+ │ │ ├── adapters.ts # Store interfaces
129
+ │ │ └── memory/ # In-memory implementations
130
+ │ ├── transport/ # Network layer
131
+ │ │ ├── adapters.ts # Transport interface
132
+ │ │ ├── websocketClient.ts
133
+ │ │ └── memoryTransport.ts
134
+ │ ├── utils/ # Utility functions
135
+ │ │ ├── errors.ts # Error classes
136
+ │ │ ├── logger.ts # Logging system
137
+ │ │ ├── validation.ts # Input validation
138
+ │ │ └── messageQueue.ts
139
+ │ ├── constants.ts # Constants and enums
140
+ │ └── index.ts # Main SDK export
141
+ ├── test/ # Test files
142
+ │ ├── crypto.test.ts
143
+ │ ├── sdk.test.ts
144
+ │ └── validation.test.ts
145
+ ├── dist/ # Build output (generated)
146
+ ├── jest.config.js # Jest configuration
147
+ ├── tsconfig.json # TypeScript configuration
148
+ └── package.json
149
+ ```
150
+
151
+ ---
152
+
153
+ ## 🔄 Development Workflow
154
+
155
+ ### 1. Create a Branch
156
+
157
+ Always create a new branch for your work:
158
+
159
+ ```bash
160
+ # Update your local main branch
161
+ git checkout main
162
+ git pull upstream main
163
+
164
+ # Create a feature branch
165
+ git checkout -b feature/your-feature-name
166
+
167
+ # Or for bug fixes
168
+ git checkout -b fix/bug-description
169
+ ```
170
+
171
+ ### 2. Make Your Changes
172
+
173
+ - Write clean, readable code
174
+ - Follow the coding standards (see below)
175
+ - Add tests for new functionality
176
+ - Update documentation as needed
177
+
178
+ ### 3. Test Your Changes
179
+
180
+ ```bash
181
+ # Run tests
182
+ npm test
183
+
184
+ # Check test coverage
185
+ npm run test:coverage
186
+
187
+ # Build to ensure no errors
188
+ npm run build
189
+ ```
190
+
191
+ ### 4. Commit Your Changes
192
+
193
+ Follow the commit message guidelines (see below):
194
+
195
+ ```bash
196
+ git add .
197
+ git commit -m "feat: add message queue retry logic"
198
+ ```
199
+
200
+ ### 5. Push and Create PR
201
+
202
+ ```bash
203
+ git push origin feature/your-feature-name
204
+ ```
205
+
206
+ Then create a Pull Request on GitHub.
207
+
208
+ ---
209
+
210
+ ## 📝 Coding Standards
211
+
212
+ ### TypeScript Style Guide
213
+
214
+ #### 1. Use TypeScript Features
215
+
216
+ ```typescript
217
+ // ✅ DO: Use interfaces for object shapes
218
+ interface User {
219
+ id: string;
220
+ username: string;
221
+ publicKey: string;
222
+ }
223
+
224
+ // ✅ DO: Use type annotations
225
+ function createUser(username: string): Promise<User> {
226
+ // ...
227
+ }
228
+
229
+ // ❌ DON'T: Use 'any' type
230
+ function processData(data: any) { // Bad
231
+ // ...
232
+ }
233
+ ```
234
+
235
+ #### 2. Naming Conventions
236
+
237
+ ```typescript
238
+ // Classes: PascalCase
239
+ class ChatSDK { }
240
+ class WebSocketClient { }
241
+
242
+ // Interfaces: PascalCase
243
+ interface TransportAdapter { }
244
+ interface UserStoreAdapter { }
245
+
246
+ // Functions/Methods: camelCase
247
+ function sendMessage() { }
248
+ async function createUser() { }
249
+
250
+ // Constants: UPPER_SNAKE_CASE
251
+ const MAX_RETRY_ATTEMPTS = 5;
252
+ const HEARTBEAT_INTERVAL = 30000;
253
+
254
+ // Enums: PascalCase for enum, UPPER_CASE for values
255
+ enum ConnectionState {
256
+ DISCONNECTED = 'disconnected',
257
+ CONNECTED = 'connected',
258
+ }
259
+ ```
260
+
261
+ #### 3. Error Handling
262
+
263
+ ```typescript
264
+ // ✅ DO: Use custom error classes
265
+ throw new ValidationError('Username must be 3-20 characters');
266
+
267
+ // ✅ DO: Provide error context
268
+ throw new NetworkError('Connection failed', 'CONN_FAILED', true, {
269
+ url: wsUrl,
270
+ attempt: reconnectAttempts,
271
+ });
272
+
273
+ // ❌ DON'T: Throw generic errors
274
+ throw new Error('Something went wrong'); // Bad
275
+ ```
276
+
277
+ #### 4. Async/Await
278
+
279
+ ```typescript
280
+ // ✅ DO: Use async/await
281
+ async function sendMessage(text: string): Promise<Message> {
282
+ const encrypted = await encryptMessage(text, sharedSecret);
283
+ return await transport.send(encrypted);
284
+ }
285
+
286
+ // ❌ DON'T: Mix promises and callbacks
287
+ function sendMessage(text: string, callback: Function) { // Bad
288
+ encryptMessage(text).then(encrypted => {
289
+ callback(null, encrypted);
290
+ });
291
+ }
292
+ ```
293
+
294
+ #### 5. Documentation
295
+
296
+ ```typescript
297
+ // ✅ DO: Add JSDoc comments for public APIs
298
+ /**
299
+ * Sends an encrypted message through the specified session.
300
+ *
301
+ * @param session - The chat or group session
302
+ * @param text - The plaintext message to send
303
+ * @returns Promise resolving to the sent message
304
+ * @throws {ValidationError} If message is invalid
305
+ * @throws {SessionError} If no current user is set
306
+ * @throws {NetworkError} If send fails
307
+ */
308
+ async function sendMessage(
309
+ session: ChatSession | GroupSession,
310
+ text: string
311
+ ): Promise<Message> {
312
+ // ...
313
+ }
314
+ ```
315
+
316
+ ### Code Organization
317
+
318
+ #### 1. Imports
319
+
320
+ ```typescript
321
+ // Order: external, internal, types
322
+ import { EventEmitter } from 'events';
323
+ import { ChatSession } from './chat/chatSession.js';
324
+ import type { User } from './models/user.js';
325
+ ```
326
+
327
+ #### 2. File Extensions
328
+
329
+ ```typescript
330
+ // ✅ DO: Use .js extensions for imports (for ESM compatibility)
331
+ import { User } from './models/user.js';
332
+
333
+ // ❌ DON'T: Omit extensions
334
+ import { User } from './models/user'; // Bad
335
+ ```
336
+
337
+ #### 3. Exports
338
+
339
+ ```typescript
340
+ // ✅ DO: Use named exports
341
+ export class ChatSDK { }
342
+ export interface User { }
343
+
344
+ // ✅ DO: Group exports at the end
345
+ export { ChatSDK, User, Message };
346
+ ```
347
+
348
+ ---
349
+
350
+ ## 🧪 Testing Guidelines
351
+
352
+ ### Test Structure
353
+
354
+ ```typescript
355
+ describe('ComponentName', () => {
356
+ describe('methodName', () => {
357
+ it('should do something specific', async () => {
358
+ // Arrange
359
+ const sdk = new ChatSDK({ /* config */ });
360
+
361
+ // Act
362
+ const result = await sdk.someMethod();
363
+
364
+ // Assert
365
+ expect(result).toBeDefined();
366
+ expect(result.property).toBe(expectedValue);
367
+ });
368
+ });
369
+ });
370
+ ```
371
+
372
+ ### Test Coverage Requirements
373
+
374
+ - **Minimum Coverage**: 70% for all metrics (branches, functions, lines, statements)
375
+ - **New Features**: Must have 80%+ coverage
376
+ - **Bug Fixes**: Must include regression tests
377
+
378
+ ### What to Test
379
+
380
+ #### 1. Happy Paths
381
+
382
+ ```typescript
383
+ it('should create a user with valid username', async () => {
384
+ const user = await sdk.createUser('alice');
385
+ expect(user.username).toBe('alice');
386
+ });
387
+ ```
388
+
389
+ #### 2. Error Cases
390
+
391
+ ```typescript
392
+ it('should reject invalid usernames', async () => {
393
+ await expect(sdk.createUser('')).rejects.toThrow(ValidationError);
394
+ await expect(sdk.createUser('ab')).rejects.toThrow(ValidationError);
395
+ });
396
+ ```
397
+
398
+ #### 3. Edge Cases
399
+
400
+ ```typescript
401
+ it('should handle empty messages', async () => {
402
+ const encrypted = await encryptMessage('', sharedSecret);
403
+ const decrypted = await decryptMessage(encrypted.ciphertext, encrypted.iv, sharedSecret);
404
+ expect(decrypted).toBe('');
405
+ });
406
+ ```
407
+
408
+ #### 4. Integration Tests
409
+
410
+ ```typescript
411
+ it('should send and decrypt messages end-to-end', async () => {
412
+ const alice = await sdk.createUser('alice');
413
+ const bob = await sdk.createUser('bob');
414
+ const session = await sdk.startSession(alice, bob);
415
+
416
+ sdk.setCurrentUser(alice);
417
+ const message = await sdk.sendMessage(session, 'Hello!');
418
+
419
+ const decrypted = await sdk.decryptMessage(message, bob);
420
+ expect(decrypted).toBe('Hello!');
421
+ });
422
+ ```
423
+
424
+ ---
425
+
426
+ ## 📝 Commit Guidelines
427
+
428
+ We follow the [Conventional Commits](https://www.conventionalcommits.org/) specification.
429
+
430
+ ### Commit Message Format
431
+
432
+ ```
433
+ <type>(<scope>): <subject>
434
+
435
+ <body>
436
+
437
+ <footer>
438
+ ```
439
+
440
+ ### Types
441
+
442
+ - **feat**: New feature
443
+ - **fix**: Bug fix
444
+ - **docs**: Documentation changes
445
+ - **style**: Code style changes (formatting, semicolons, etc.)
446
+ - **refactor**: Code refactoring
447
+ - **perf**: Performance improvements
448
+ - **test**: Adding or updating tests
449
+ - **chore**: Build process or auxiliary tool changes
450
+
451
+ ### Examples
452
+
453
+ ```bash
454
+ # Feature
455
+ git commit -m "feat(transport): add automatic reconnection with exponential backoff"
456
+
457
+ # Bug fix
458
+ git commit -m "fix(crypto): handle empty messages in encryption"
459
+
460
+ # Documentation
461
+ git commit -m "docs(readme): add React integration examples"
462
+
463
+ # Breaking change
464
+ git commit -m "feat(sdk)!: change sendMessage to return Promise<Message>
465
+
466
+ BREAKING CHANGE: sendMessage now returns a Promise instead of void"
467
+ ```
468
+
469
+ ### Scope
470
+
471
+ Use the component/module name:
472
+ - `sdk` - Core SDK
473
+ - `crypto` - Cryptography
474
+ - `transport` - Network layer
475
+ - `stores` - Storage adapters
476
+ - `validation` - Input validation
477
+ - `errors` - Error handling
478
+ - `queue` - Message queue
479
+ - `tests` - Test files
480
+ - `docs` - Documentation
481
+
482
+ ---
483
+
484
+ ## 🔀 Pull Request Process
485
+
486
+ ### Before Submitting
487
+
488
+ - [ ] Tests pass: `npm test`
489
+ - [ ] Build succeeds: `npm run build`
490
+ - [ ] Code follows style guidelines
491
+ - [ ] Documentation is updated
492
+ - [ ] Commit messages follow conventions
493
+ - [ ] Branch is up to date with main
494
+
495
+ ### PR Title
496
+
497
+ Follow the same format as commit messages:
498
+
499
+ ```
500
+ feat(transport): add WebSocket reconnection logic
501
+ fix(crypto): handle edge case in key derivation
502
+ docs(readme): improve installation instructions
503
+ ```
504
+
505
+ ### PR Description Template
506
+
507
+ ```markdown
508
+ ## Description
509
+ Brief description of the changes.
510
+
511
+ ## Type of Change
512
+ - [ ] Bug fix (non-breaking change which fixes an issue)
513
+ - [ ] New feature (non-breaking change which adds functionality)
514
+ - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
515
+ - [ ] Documentation update
516
+
517
+ ## Changes Made
518
+ - Change 1
519
+ - Change 2
520
+ - Change 3
521
+
522
+ ## Testing
523
+ Describe the tests you ran and how to reproduce them.
524
+
525
+ ## Checklist
526
+ - [ ] My code follows the style guidelines
527
+ - [ ] I have performed a self-review
528
+ - [ ] I have commented my code, particularly in hard-to-understand areas
529
+ - [ ] I have updated the documentation
530
+ - [ ] My changes generate no new warnings
531
+ - [ ] I have added tests that prove my fix is effective or that my feature works
532
+ - [ ] New and existing unit tests pass locally
533
+ - [ ] Any dependent changes have been merged and published
534
+ ```
535
+
536
+ ### Review Process
537
+
538
+ 1. **Automated Checks**: CI/CD runs tests and builds
539
+ 2. **Code Review**: At least one maintainer reviews the code
540
+ 3. **Feedback**: Address review comments
541
+ 4. **Approval**: Maintainer approves the PR
542
+ 5. **Merge**: Maintainer merges the PR
543
+
544
+ ---
545
+
546
+ ## 🚢 Release Process
547
+
548
+ ### Versioning
549
+
550
+ We follow [Semantic Versioning](https://semver.org/):
551
+
552
+ - **MAJOR**: Breaking changes (e.g., 1.0.0 → 2.0.0)
553
+ - **MINOR**: New features, backward compatible (e.g., 1.0.0 → 1.1.0)
554
+ - **PATCH**: Bug fixes, backward compatible (e.g., 1.0.0 → 1.0.1)
555
+
556
+ ### Release Steps (Maintainers Only)
557
+
558
+ 1. Update version in `package.json`
559
+ 2. Update CHANGELOG.md
560
+ 3. Create a git tag: `git tag v1.2.3`
561
+ 4. Push tag: `git push origin v1.2.3`
562
+ 5. Publish to npm: `npm publish`
563
+ 6. Create GitHub release with notes
564
+
565
+ ---
566
+
567
+ ## 🐛 Reporting Bugs
568
+
569
+ ### Before Reporting
570
+
571
+ - Check if the bug has already been reported
572
+ - Try to reproduce with the latest version
573
+ - Gather relevant information (OS, Node version, etc.)
574
+
575
+ ### Bug Report Template
576
+
577
+ ```markdown
578
+ **Describe the bug**
579
+ A clear and concise description of what the bug is.
580
+
581
+ **To Reproduce**
582
+ Steps to reproduce the behavior:
583
+ 1. Initialize SDK with '...'
584
+ 2. Call method '...'
585
+ 3. See error
586
+
587
+ **Expected behavior**
588
+ What you expected to happen.
589
+
590
+ **Actual behavior**
591
+ What actually happened.
592
+
593
+ **Code Sample**
594
+ ```typescript
595
+ // Minimal code to reproduce
596
+ const sdk = new ChatSDK({ /* ... */ });
597
+ await sdk.someMethod(); // Error occurs here
598
+ ```
599
+
600
+ **Environment**
601
+ - OS: [e.g., macOS 13.0]
602
+ - Node.js version: [e.g., 18.12.0]
603
+ - SDK version: [e.g., 0.0.5]
604
+
605
+ **Additional context**
606
+ Any other context about the problem.
607
+ ```
608
+
609
+ ---
610
+
611
+ ## 💡 Feature Requests
612
+
613
+ ### Before Requesting
614
+
615
+ - Check if the feature has already been requested
616
+ - Consider if it fits the project scope
617
+ - Think about backward compatibility
618
+
619
+ ### Feature Request Template
620
+
621
+ ```markdown
622
+ **Is your feature request related to a problem?**
623
+ A clear description of the problem.
624
+
625
+ **Describe the solution you'd like**
626
+ What you want to happen.
627
+
628
+ **Describe alternatives you've considered**
629
+ Other solutions you've thought about.
630
+
631
+ **API Design (if applicable)**
632
+ ```typescript
633
+ // Proposed API
634
+ sdk.newMethod(params);
635
+ ```
636
+
637
+ **Additional context**
638
+ Any other context or screenshots.
639
+ ```
640
+
641
+ ---
642
+
643
+ ## 📞 Getting Help
644
+
645
+ - **Documentation**: Check the [README](./README.md)
646
+ - **Issues**: Search [existing issues](https://github.com/bharath-arch/chatly-sdk/issues)
647
+ - **Discussions**: Use [GitHub Discussions](https://github.com/bharath-arch/chatly-sdk/discussions)
648
+
649
+ ---
650
+
651
+ ## 🙏 Recognition
652
+
653
+ Contributors will be recognized in:
654
+ - README.md contributors section
655
+ - Release notes
656
+ - GitHub contributors page
657
+
658
+ Thank you for contributing to Chatly SDK! 🎉