@social.dev/server-sdk 0.0.1-alpha.33 → 0.0.1-alpha.35

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/README.md CHANGED
@@ -1,15 +1,724 @@
1
- ## Social.Dev server
1
+ # @social.dev/server-sdk
2
2
 
3
- ## Generating migrations
3
+ Server SDK for Social.dev - A comprehensive NestJS-based framework for building scalable social media server applications.
4
4
 
5
- ```sh
6
- typeorm migration:generate -d ./dist/db.js src/migrations --dryrun
5
+ ## Overview
6
+
7
+ The `@social.dev/server-sdk` package provides:
8
+ - 🏗️ **NestJS Framework** - Built on top of NestJS 11 for enterprise-grade applications
9
+ - 🔐 **Authentication System** - Multiple auth methods including OIDC, JWT, and cookie-based sessions
10
+ - 💾 **Database Integration** - TypeORM with PostgreSQL support and migration tools
11
+ - 🔌 **Plugin Architecture** - Extensible plugin system for custom functionality
12
+ - 💬 **Chat System** - Real-time messaging with conversation management
13
+ - 👥 **Community Features** - Sub-communities with member management
14
+ - 📝 **Post Management** - Content creation and interaction system
15
+ - 🔔 **Notifications** - Push notification support with device management
16
+ - 📁 **File Storage** - S3-compatible file storage integration
17
+ - 📊 **API Documentation** - Auto-generated Swagger/OpenAPI documentation
18
+ - 🌐 **Multi-Network Support** - Domain-based network isolation
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ # Using pnpm (recommended)
24
+ pnpm add @social.dev/server-sdk
25
+
26
+ # Using npm
27
+ npm install @social.dev/server-sdk
28
+
29
+ # Using yarn
30
+ yarn add @social.dev/server-sdk
31
+ ```
32
+
33
+ ### Prerequisites
34
+
35
+ - Node.js 18 or higher
36
+ - PostgreSQL 14 or higher
37
+ - Redis (optional, for caching)
38
+ - S3-compatible storage (optional, for file uploads)
39
+
40
+ ## Quick Start
41
+
42
+ ### Basic Setup
43
+
44
+ Create a new file `index.ts` in your server application:
45
+
46
+ ```typescript
47
+ import { bootstrap } from '@social.dev/server-sdk/bootstrap';
48
+
49
+ // Initialize the server with minimal configuration
50
+ bootstrap({
51
+ auth: {
52
+ methods: ['password'], // Enable password authentication
53
+ },
54
+ });
55
+ ```
56
+
57
+ ### Advanced Setup with OIDC and Plugins
58
+
59
+ ```typescript
60
+ import { bootstrap } from '@social.dev/server-sdk/bootstrap';
61
+ import { AuthMethodEnum } from '@social.dev/server-sdk/auth/enums/auth-method.enum';
62
+ import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';
63
+ import SocialDevAiPlugin from '@social.dev/plugin-ai';
64
+
65
+ // Register plugins before bootstrap
66
+ PluginFactory.addPlugin(
67
+ SocialDevAiPlugin.forRoot({
68
+ userIds: [3], // User IDs that can access AI features
69
+ })
70
+ );
71
+
72
+ // Bootstrap the server with comprehensive configuration
73
+ bootstrap({
74
+ auth: {
75
+ methods: [AuthMethodEnum.Oidc, AuthMethodEnum.Password],
76
+ oidc: {
77
+ providers: [
78
+ {
79
+ id: 'keycloak',
80
+ name: 'Company Keycloak',
81
+ issuer: 'https://keycloak.example.com/auth/realms/company',
82
+ clientId: 'social-dev-app',
83
+ clientSecret: process.env.OIDC_CLIENT_SECRET,
84
+ },
85
+ ],
86
+ },
87
+ },
88
+ network: {
89
+ domainAliasMap: {
90
+ 'localhost': 1,
91
+ 'dev.example.com': 2,
92
+ 'staging.example.com': 3,
93
+ },
94
+ },
95
+ });
96
+ ```
97
+
98
+ ## Configuration
99
+
100
+ ### Environment Variables
101
+
102
+ Create a `.env` file in your project root:
103
+
104
+ ```env
105
+ # Server Configuration
106
+ SOCIAL_DEV_SERVER_PORT=3000
107
+ NODE_ENV=development
108
+
109
+ # Database Configuration
110
+ POSTGRES_HOST=localhost
111
+ POSTGRES_PORT=5432
112
+ POSTGRES_USER=socialdev
113
+ POSTGRES_PASSWORD=yourpassword
114
+ POSTGRES_DB=socialdev_db
115
+
116
+ # Authentication
117
+ JWT_SECRET=your-super-secret-jwt-key
118
+ JWT_EXPIRES_IN=7d
119
+
120
+ # OIDC Configuration (optional)
121
+ OIDC_CLIENT_SECRET=your-oidc-secret
122
+
123
+ # S3 Storage (optional)
124
+ AWS_ACCESS_KEY_ID=your-access-key
125
+ AWS_SECRET_ACCESS_KEY=your-secret-key
126
+ AWS_REGION=us-east-1
127
+ S3_BUCKET_NAME=socialdev-uploads
128
+
129
+ # Push Notifications (optional)
130
+ FCM_SERVER_KEY=your-fcm-server-key
131
+ APNS_KEY_ID=your-apns-key-id
132
+ APNS_TEAM_ID=your-apns-team-id
133
+ ```
134
+
135
+ ### Bootstrap Configuration Options
136
+
137
+ ```typescript
138
+ interface BootstrapConfig {
139
+ auth?: {
140
+ // Available authentication methods
141
+ methods: AuthMethodEnum[];
142
+
143
+ // OIDC provider configuration
144
+ oidc?: {
145
+ providers: OidcProvider[];
146
+ };
147
+
148
+ // JWT configuration
149
+ jwt?: {
150
+ secret?: string;
151
+ expiresIn?: string;
152
+ };
153
+ };
154
+
155
+ network?: {
156
+ // Map domains to network IDs for multi-tenant support
157
+ domainAliasMap: { [domain: string]: number };
158
+ };
159
+
160
+ database?: {
161
+ // Override default database configuration
162
+ host?: string;
163
+ port?: number;
164
+ username?: string;
165
+ password?: string;
166
+ database?: string;
167
+ synchronize?: boolean; // Auto-sync schema (dev only!)
168
+ };
169
+
170
+ storage?: {
171
+ // S3 configuration
172
+ accessKeyId?: string;
173
+ secretAccessKey?: string;
174
+ region?: string;
175
+ bucket?: string;
176
+ };
177
+ }
178
+ ```
179
+
180
+ ## Core Modules
181
+
182
+ ### Authentication Module
183
+
184
+ The SDK supports multiple authentication methods:
185
+
186
+ ```typescript
187
+ // Available authentication methods
188
+ enum AuthMethodEnum {
189
+ Password = 'password',
190
+ Oidc = 'oidc',
191
+ Magic = 'magic', // Magic link via email
192
+ }
193
+
194
+ // OIDC Provider configuration
195
+ interface OidcProvider {
196
+ id: string; // Unique identifier
197
+ name: string; // Display name
198
+ issuer: string; // OIDC issuer URL
199
+ clientId: string; // OAuth client ID
200
+ clientSecret: string; // OAuth client secret
201
+ scope?: string; // OAuth scopes (default: 'openid profile email')
202
+ }
203
+ ```
204
+
205
+ ### User Module
206
+
207
+ User management with profiles and authentication:
208
+
209
+ ```typescript
210
+ // User entity structure
211
+ interface User {
212
+ id: number;
213
+ username: string;
214
+ email: string;
215
+ name?: string;
216
+ bio?: string;
217
+ avatar?: string;
218
+ verified: boolean;
219
+ createdAt: Date;
220
+ updatedAt: Date;
221
+ }
222
+ ```
223
+
224
+ ### Post Module
225
+
226
+ Content creation and management:
227
+
228
+ ```typescript
229
+ // Post entity structure
230
+ interface Post {
231
+ id: number;
232
+ content: string;
233
+ authorId: number;
234
+ parentId?: number; // For replies
235
+ attachments?: MediaAsset[];
236
+ likes: number;
237
+ comments: number;
238
+ shares: number;
239
+ createdAt: Date;
240
+ updatedAt: Date;
241
+ }
242
+ ```
243
+
244
+ ### Chat Module
245
+
246
+ Real-time messaging system:
247
+
248
+ ```typescript
249
+ // Conversation management
250
+ interface Conversation {
251
+ id: number;
252
+ participants: User[];
253
+ lastMessage?: Message;
254
+ unreadCount: number;
255
+ createdAt: Date;
256
+ updatedAt: Date;
257
+ }
258
+
259
+ // Message structure
260
+ interface Message {
261
+ id: number;
262
+ conversationId: number;
263
+ senderId: number;
264
+ content: string;
265
+ attachments?: MediaAsset[];
266
+ readBy: number[];
267
+ createdAt: Date;
268
+ }
269
+ ```
270
+
271
+ ### Community Module
272
+
273
+ Sub-communities (subs) management:
274
+
275
+ ```typescript
276
+ // Sub entity structure
277
+ interface Sub {
278
+ id: number;
279
+ name: string;
280
+ description?: string;
281
+ avatar?: string;
282
+ banner?: string;
283
+ memberCount: number;
284
+ postCount: number;
285
+ createdAt: Date;
286
+ }
287
+
288
+ // Member management
289
+ interface SubMember {
290
+ subId: number;
291
+ userId: number;
292
+ role: 'owner' | 'moderator' | 'member';
293
+ joinedAt: Date;
294
+ }
295
+ ```
296
+
297
+ ### Notification Module
298
+
299
+ Push notification management:
300
+
301
+ ```typescript
302
+ // Device registration
303
+ interface NotificationDevice {
304
+ id: number;
305
+ userId: number;
306
+ token: string;
307
+ platform: 'ios' | 'android' | 'web';
308
+ active: boolean;
309
+ }
310
+
311
+ // Notification sending
312
+ interface Notification {
313
+ userId: number;
314
+ title: string;
315
+ body: string;
316
+ data?: Record<string, any>;
317
+ priority?: 'high' | 'normal';
318
+ }
319
+ ```
320
+
321
+ ## Plugin System
322
+
323
+ The SDK supports a powerful plugin architecture for extending functionality:
324
+
325
+ ### Creating a Custom Plugin
326
+
327
+ ```typescript
328
+ // plugins/my-plugin/index.ts
329
+ import { Injectable, Module } from '@nestjs/common';
330
+ import { PluginInterface } from '@social.dev/server-sdk/core/plugin/plugin.interface';
331
+
332
+ @Injectable()
333
+ class MyPluginService {
334
+ async processContent(content: string): Promise<string> {
335
+ // Your plugin logic here
336
+ return content.toUpperCase();
337
+ }
338
+ }
339
+
340
+ @Module({
341
+ providers: [MyPluginService],
342
+ exports: [MyPluginService],
343
+ })
344
+ export class MyPlugin implements PluginInterface {
345
+ static forRoot(options?: { enabled?: boolean }) {
346
+ return {
347
+ module: MyPlugin,
348
+ providers: [
349
+ {
350
+ provide: 'MY_PLUGIN_OPTIONS',
351
+ useValue: options || {},
352
+ },
353
+ ],
354
+ };
355
+ }
356
+ }
357
+ ```
358
+
359
+ ### Registering Plugins
360
+
361
+ ```typescript
362
+ import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';
363
+ import { MyPlugin } from './plugins/my-plugin';
364
+
365
+ // Register plugin before bootstrap
366
+ PluginFactory.addPlugin(
367
+ MyPlugin.forRoot({
368
+ enabled: true,
369
+ })
370
+ );
371
+
372
+ // Then bootstrap the server
373
+ bootstrap({ /* ... */ });
374
+ ```
375
+
376
+ ## Database Migrations
377
+
378
+ ### Generating Migrations
379
+
380
+ ```bash
381
+ # Build the SDK first
382
+ pnpm build
383
+
384
+ # Generate a new migration based on entity changes
385
+ npx typeorm migration:generate \
386
+ -d ./node_modules/@social.dev/server-sdk/dist/db.js \
387
+ ./migrations/AddUserBio
7
388
  ```
8
389
 
9
- ## Running migrations
390
+ ### Running Migrations
10
391
 
11
- From your server implementation
392
+ ```bash
393
+ # Run all pending migrations
394
+ npx typeorm migration:run \
395
+ -d ./node_modules/@social.dev/server-sdk/dist/db.js
12
396
 
13
- ```sh
14
- typeorm migration:run -d node_modules/@social.dev/server-sdk/dist/db.js
397
+ # Revert the last migration
398
+ npx typeorm migration:revert \
399
+ -d ./node_modules/@social.dev/server-sdk/dist/db.js
15
400
  ```
401
+
402
+ ### Creating Custom Migrations
403
+
404
+ ```typescript
405
+ // migrations/1234567890-CustomMigration.ts
406
+ import { MigrationInterface, QueryRunner, Table } from 'typeorm';
407
+
408
+ export class CustomMigration1234567890 implements MigrationInterface {
409
+ async up(queryRunner: QueryRunner): Promise<void> {
410
+ await queryRunner.createTable(
411
+ new Table({
412
+ name: 'custom_table',
413
+ columns: [
414
+ {
415
+ name: 'id',
416
+ type: 'int',
417
+ isPrimary: true,
418
+ isGenerated: true,
419
+ generationStrategy: 'increment',
420
+ },
421
+ {
422
+ name: 'name',
423
+ type: 'varchar',
424
+ },
425
+ ],
426
+ }),
427
+ true
428
+ );
429
+ }
430
+
431
+ async down(queryRunner: QueryRunner): Promise<void> {
432
+ await queryRunner.dropTable('custom_table');
433
+ }
434
+ }
435
+ ```
436
+
437
+ ## API Documentation
438
+
439
+ The SDK automatically generates Swagger/OpenAPI documentation:
440
+
441
+ ```bash
442
+ # Start your server
443
+ pnpm dev
444
+
445
+ # Access the documentation
446
+ open http://localhost:3000/schema
447
+ ```
448
+
449
+ ### Custom API Endpoints
450
+
451
+ You can add custom endpoints by creating NestJS controllers:
452
+
453
+ ```typescript
454
+ // src/custom/custom.controller.ts
455
+ import { Controller, Get, Post, Body, UseGuards } from '@nestjs/common';
456
+ import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
457
+ import { AuthGuard } from '@social.dev/server-sdk/auth/auth.guard';
458
+
459
+ @ApiTags('custom')
460
+ @Controller('custom')
461
+ export class CustomController {
462
+ @Get('public')
463
+ getPublicData() {
464
+ return { message: 'This is public' };
465
+ }
466
+
467
+ @Post('protected')
468
+ @UseGuards(AuthGuard)
469
+ @ApiBearerAuth()
470
+ createProtectedResource(@Body() data: any) {
471
+ return { success: true, data };
472
+ }
473
+ }
474
+
475
+ // Register in a module
476
+ @Module({
477
+ controllers: [CustomController],
478
+ })
479
+ export class CustomModule {}
480
+ ```
481
+
482
+ ## Development Scripts
483
+
484
+ ```bash
485
+ # Install dependencies
486
+ pnpm install
487
+
488
+ # Development mode with hot reload
489
+ pnpm dev
490
+
491
+ # Build for production
492
+ pnpm build
493
+
494
+ # Start production server
495
+ pnpm start:prod
496
+
497
+ # Run tests
498
+ pnpm test
499
+
500
+ # Run tests with coverage
501
+ pnpm test:cov
502
+
503
+ # Lint code
504
+ pnpm lint
505
+
506
+ # Format code
507
+ pnpm format
508
+ ```
509
+
510
+ ## Production Deployment
511
+
512
+ ### Using PM2
513
+
514
+ ```javascript
515
+ // ecosystem.config.js
516
+ module.exports = {
517
+ apps: [{
518
+ name: 'social-dev-server',
519
+ script: './dist/index.js',
520
+ instances: 'max',
521
+ exec_mode: 'cluster',
522
+ env: {
523
+ NODE_ENV: 'production',
524
+ SOCIAL_DEV_SERVER_PORT: 3000,
525
+ },
526
+ }],
527
+ };
528
+ ```
529
+
530
+ ```bash
531
+ # Build and start with PM2
532
+ pnpm build
533
+ pm2 start ecosystem.config.js
534
+ ```
535
+
536
+ ### Using Docker
537
+
538
+ ```dockerfile
539
+ # Dockerfile
540
+ FROM node:18-alpine AS builder
541
+
542
+ WORKDIR /app
543
+ COPY package*.json pnpm-lock.yaml ./
544
+ RUN npm install -g pnpm
545
+ RUN pnpm install --frozen-lockfile
546
+
547
+ COPY . .
548
+ RUN pnpm build
549
+
550
+ FROM node:18-alpine
551
+
552
+ WORKDIR /app
553
+ COPY --from=builder /app/dist ./dist
554
+ COPY --from=builder /app/node_modules ./node_modules
555
+ COPY --from=builder /app/package.json ./
556
+
557
+ EXPOSE 3000
558
+ CMD ["node", "dist/index.js"]
559
+ ```
560
+
561
+ ### Using Vercel
562
+
563
+ ```json
564
+ // vercel.json
565
+ {
566
+ "version": 2,
567
+ "builds": [
568
+ {
569
+ "src": "api/index.ts",
570
+ "use": "@vercel/node"
571
+ }
572
+ ],
573
+ "routes": [
574
+ {
575
+ "src": "/(.*)",
576
+ "dest": "/api"
577
+ }
578
+ ]
579
+ }
580
+ ```
581
+
582
+ ```typescript
583
+ // api/index.ts
584
+ import { bootstrap } from '@social.dev/server-sdk/bootstrap';
585
+
586
+ export default async function handler(req, res) {
587
+ const app = await bootstrap({
588
+ // Your configuration
589
+ });
590
+ return app.getHttpAdapter().getInstance()(req, res);
591
+ }
592
+ ```
593
+
594
+ ## Multi-Network Support
595
+
596
+ The SDK supports running multiple isolated networks on a single server instance:
597
+
598
+ ```typescript
599
+ bootstrap({
600
+ network: {
601
+ domainAliasMap: {
602
+ 'network1.example.com': 1,
603
+ 'network2.example.com': 2,
604
+ 'api.company.com': 3,
605
+ },
606
+ },
607
+ });
608
+
609
+ // Each domain will have isolated:
610
+ // - Users and authentication
611
+ // - Posts and content
612
+ // - Communities
613
+ // - Chat conversations
614
+ // - Notifications
615
+ ```
616
+
617
+ ## Security Best Practices
618
+
619
+ 1. **Environment Variables**: Never commit `.env` files to version control
620
+ 2. **Database**: Always disable `synchronize` in production
621
+ 3. **CORS**: Configure allowed origins in production
622
+ 4. **Rate Limiting**: Implement rate limiting for API endpoints
623
+ 5. **Input Validation**: Use DTOs with class-validator for all inputs
624
+ 6. **Authentication**: Use strong JWT secrets and appropriate expiration times
625
+ 7. **HTTPS**: Always use HTTPS in production
626
+
627
+ ## TypeScript Support
628
+
629
+ The SDK is written in TypeScript and provides full type definitions:
630
+
631
+ ```typescript
632
+ import type {
633
+ User,
634
+ Post,
635
+ Sub,
636
+ Message,
637
+ Conversation,
638
+ AuthMethodEnum,
639
+ OidcProvider,
640
+ Configs,
641
+ } from '@social.dev/server-sdk';
642
+ ```
643
+
644
+ ## Examples
645
+
646
+ Check out the [apps/server](../../apps/server) directory for a complete implementation example using the SDK.
647
+
648
+ ### Example Server Implementation
649
+
650
+ ```typescript
651
+ // apps/server/index.ts
652
+ import SocialDevAiPlugin from '@social.dev/plugin-ai';
653
+ import { AuthMethodEnum } from '@social.dev/server-sdk/auth/enums/auth-method.enum';
654
+ import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';
655
+
656
+ // Initialize plugins
657
+ PluginFactory.addPlugin(
658
+ SocialDevAiPlugin.forRoot({
659
+ userIds: [3],
660
+ })
661
+ );
662
+
663
+ // Initialize the server
664
+ import('@social.dev/server-sdk/bootstrap').then(({ bootstrap }) => {
665
+ bootstrap({
666
+ auth: {
667
+ methods: [AuthMethodEnum.Oidc],
668
+ oidc: {
669
+ providers: [
670
+ {
671
+ id: 'minds-inc',
672
+ name: 'Minds Keycloak',
673
+ issuer: 'https://keycloak.minds.com/auth/realms/minds-inc',
674
+ clientId: 'demo-social-dev',
675
+ clientSecret: process.env.SOCIAL_DEV_OIDC_SECRET,
676
+ },
677
+ ],
678
+ },
679
+ },
680
+ network: {
681
+ domainAliasMap: {
682
+ localhost: 2,
683
+ },
684
+ },
685
+ });
686
+ });
687
+ ```
688
+
689
+ ## Troubleshooting
690
+
691
+ ### Common Issues
692
+
693
+ 1. **Database Connection Failed**
694
+ - Check PostgreSQL is running
695
+ - Verify database credentials in `.env`
696
+ - Ensure database exists
697
+
698
+ 2. **Port Already in Use**
699
+ - Change `SOCIAL_DEV_SERVER_PORT` in `.env`
700
+ - Kill existing process: `lsof -i :3000`
701
+
702
+ 3. **Migration Errors**
703
+ - Build the SDK first: `pnpm build`
704
+ - Check database permissions
705
+ - Review migration SQL for conflicts
706
+
707
+ 4. **OIDC Authentication Failed**
708
+ - Verify issuer URL is accessible
709
+ - Check client ID and secret
710
+ - Ensure redirect URIs are configured
711
+
712
+ ## Contributing
713
+
714
+ Contributions are welcome! Please read our contributing guidelines before submitting PRs.
715
+
716
+ ## License
717
+
718
+ MIT
719
+
720
+ ## Support
721
+
722
+ - [Documentation](https://docs.social.dev)
723
+ - [GitHub Issues](https://github.com/socialdotdev/social.dev/issues)
724
+ - [Discord Community](https://discord.gg/socialdev)