npm package: @social.dev/server-sdk
Description: Server SDK for Social.dev - A comprehensive NestJS-based framework for building scalable social media server applications.
Latest version: 0.0.1-alpha.84

# @social.dev/server-sdk

Server SDK for Social.dev - A comprehensive NestJS-based framework for building scalable social media server applications.

## Overview

The `@social.dev/server-sdk` package provides:

- 🏗️ **NestJS Framework** - Built on top of NestJS 11 for enterprise-grade applications
- 🔐 **Authentication System** - Multiple auth methods including OIDC, JWT, and cookie-based sessions
- 💾 **Database Integration** - TypeORM with PostgreSQL support and migration tools
- 🔌 **Plugin Architecture** - Extensible plugin system for custom functionality
- 💬 **Chat System** - Real-time messaging with conversation management
- 👥 **Community Features** - Sub-communities with member management
- 📝 **Post Management** - Content creation and interaction system
- 🔔 **Notifications** - Push notification support with device management
- 📁 **File Storage** - S3-compatible file storage integration
- 📊 **API Documentation** - Auto-generated Swagger/OpenAPI documentation
- 🌐 **Multi-Network Support** - Domain-based network isolation

## Installation

```bash
# Using pnpm (recommended)
pnpm add @social.dev/server-sdk

# Using npm
npm install @social.dev/server-sdk

# Using yarn
yarn add @social.dev/server-sdk
```

### Prerequisites

- Node.js 18 or higher
- PostgreSQL 14 or higher
- Redis (optional, for caching)
- S3-compatible storage (optional, for file uploads)

## Quick Start

### Basic Setup

Create a new file `index.ts` in your server application:

```typescript
import { bootstrap } from '@social.dev/server-sdk/bootstrap';

// Initialize the server with minimal configuration
bootstrap({
  auth: {
    methods: ['password'], // Enable password authentication
  },
});
```

### Advanced Setup with OIDC and Plugins

```typescript
import { bootstrap } from '@social.dev/server-sdk/bootstrap';
import { AuthMethodEnum } from '@social.dev/server-sdk/auth/enums/auth-method.enum';
import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';
import SocialDevAiPlugin from '@social.dev/plugin-ai';

// Register plugins before bootstrap
PluginFactory.addPlugin(
  SocialDevAiPlugin.forRoot({
    userIds: [3], // User IDs that can access AI features
  }),
);

// Bootstrap the server with comprehensive configuration
bootstrap({
  auth: {
    methods: [AuthMethodEnum.Oidc, AuthMethodEnum.Password],
    oidc: {
      providers: [
        {
          id: 'keycloak',
          name: 'Company Keycloak',
          issuer: 'https://keycloak.example.com/auth/realms/company',
          clientId: 'social-dev-app',
          clientSecret: process.env.OIDC_CLIENT_SECRET,
        },
      ],
    },
  },
  network: {
    domainAliasMap: {
      localhost: 1,
      'dev.example.com': 2,
      'staging.example.com': 3,
    },
  },
});
```

## Configuration

### Environment Variables

Create a `.env` file in your project root:

```env
# Server Configuration
SOCIAL_DEV_SERVER_PORT=3000
NODE_ENV=development

# Database Configuration
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=socialdev
POSTGRES_PASSWORD=yourpassword
POSTGRES_DB=socialdev_db

# Authentication
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=7d

# OIDC Configuration (optional)
OIDC_CLIENT_SECRET=your-oidc-secret

# S3 Storage (optional)
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_REGION=us-east-1
S3_BUCKET_NAME=socialdev-uploads

# Push Notifications (optional)
FCM_SERVER_KEY=your-fcm-server-key
APNS_KEY_ID=your-apns-key-id
APNS_TEAM_ID=your-apns-team-id
```

### Bootstrap Configuration Options

```typescript
interface BootstrapConfig {
  auth?: {
    // Available authentication methods
    methods: AuthMethodEnum[];

    // OIDC provider configuration
    oidc?: {
      providers: OidcProvider[];
    };

    // JWT configuration
    jwt?: {
      secret?: string;
      expiresIn?: string;
    };
  };

  network?: {
    // Map domains to network IDs for multi-tenant support
    domainAliasMap: { [domain: string]: number };
  };

  database?: {
    // Override default database configuration
    host?: string;
    port?: number;
    username?: string;
    password?: string;
    database?: string;
    synchronize?: boolean; // Auto-sync schema (dev only!)
  };

  storage?: {
    // S3 configuration
    accessKeyId?: string;
    secretAccessKey?: string;
    region?: string;
    bucket?: string;
  };
}
```

## Core Modules

### Authentication Module

The SDK supports multiple authentication methods:

```typescript
// Available authentication methods
enum AuthMethodEnum {
  Password = 'password',
  Oidc = 'oidc',
  Magic = 'magic', // Magic link via email
}

// OIDC Provider configuration
interface OidcProvider {
  id: string; // Unique identifier
  name: string; // Display name
  issuer: string; // OIDC issuer URL
  clientId: string; // OAuth client ID
  clientSecret: string; // OAuth client secret
  scope?: string; // OAuth scopes (default: 'openid profile email')
}
```

### User Module

User management with profiles and authentication:

```typescript
// User entity structure
interface User {
  id: number;
  username: string;
  email: string;
  name?: string;
  bio?: string;
  avatar?: string;
  verified: boolean;
  createdAt: Date;
  updatedAt: Date;
}
```

### Post Module

Content creation and management:

```typescript
// Post entity structure
interface Post {
  id: number;
  content: string;
  authorId: number;
  parentId?: number; // For replies
  attachments?: MediaAsset[];
  likes: number;
  comments: number;
  shares: number;
  createdAt: Date;
  updatedAt: Date;
}
```

### Chat Module

Real-time messaging system:

```typescript
// Conversation management
interface Conversation {
  id: number;
  participants: User[];
  lastMessage?: Message;
  unreadCount: number;
  createdAt: Date;
  updatedAt: Date;
}

// Message structure
interface Message {
  id: number;
  conversationId: number;
  senderId: number;
  content: string;
  attachments?: MediaAsset[];
  readBy: number[];
  createdAt: Date;
}
```

### Community Module

Sub-communities (subs) management:

```typescript
// Sub entity structure
interface Sub {
  id: number;
  name: string;
  description?: string;
  avatar?: string;
  banner?: string;
  memberCount: number;
  postCount: number;
  createdAt: Date;
}

// Member management
interface SubMember {
  subId: number;
  userId: number;
  role: 'owner' | 'moderator' | 'member';
  joinedAt: Date;
}
```

### Notification Module

Push notification management:

```typescript
// Device registration
interface NotificationDevice {
  id: number;
  userId: number;
  token: string;
  platform: 'ios' | 'android' | 'web';
  active: boolean;
}

// Notification sending
interface Notification {
  userId: number;
  title: string;
  body: string;
  data?: Record<string, any>;
  priority?: 'high' | 'normal';
}
```

## Plugin System

The SDK supports a powerful plugin architecture for extending functionality:

### Creating a Custom Plugin

```typescript
// plugins/my-plugin/index.ts
import { Injectable, Module } from '@nestjs/common';
import { PluginInterface } from '@social.dev/server-sdk/core/plugin/plugin.interface';

@Injectable()
class MyPluginService {
  async processContent(content: string): Promise<string> {
    // Your plugin logic here
    return content.toUpperCase();
  }
}

@Module({
  providers: [MyPluginService],
  exports: [MyPluginService],
})
export class MyPlugin implements PluginInterface {
  static forRoot(options?: { enabled?: boolean }) {
    return {
      module: MyPlugin,
      providers: [
        {
          provide: 'MY_PLUGIN_OPTIONS',
          useValue: options || {},
        },
      ],
    };
  }
}
```

### Registering Plugins

```typescript
import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';
import { MyPlugin } from './plugins/my-plugin';

// Register plugin before bootstrap
PluginFactory.addPlugin(
  MyPlugin.forRoot({
    enabled: true,
  }),
);

// Then bootstrap the server
bootstrap({
  /* ... */
});
```

## Database Migrations

### Generating Migrations

```bash
# Build the SDK first
pnpm build

# Generate a new migration based on entity changes
npx typeorm migration:generate \
  -d ./dist/manage-db.js \
  ./src/migrations/NewMigration
```

### Running Migrations

```bash
# Run all pending migrations
npx typeorm migration:run \
  -d ./node_modules/@social.dev/server-sdk/dist/manage-db.js

# Revert the last migration
npx typeorm migration:revert \
  -d ./node_modules/@social.dev/server-sdk/dist/manage-db.js
```

### Creating Custom Migrations

```typescript
// migrations/1234567890-CustomMigration.ts
import { MigrationInterface, QueryRunner, Table } from 'typeorm';

export class CustomMigration1234567890 implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        name: 'custom_table',
        columns: [
          {
            name: 'id',
            type: 'int',
            isPrimary: true,
            isGenerated: true,
            generationStrategy: 'increment',
          },
          {
            name: 'name',
            type: 'varchar',
          },
        ],
      }),
      true,
    );
  }

  async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropTable('custom_table');
  }
}
```

## API Documentation

The SDK automatically generates Swagger/OpenAPI documentation:

```bash
# Start your server
pnpm dev

# Access the documentation
open http://localhost:3000/schema
```

### Custom API Endpoints

You can add custom endpoints by creating NestJS controllers:

```typescript
// src/custom/custom.controller.ts
import { Controller, Get, Post, Body, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@social.dev/server-sdk/auth/auth.guard';

@ApiTags('custom')
@Controller('custom')
export class CustomController {
  @Get('public')
  getPublicData() {
    return { message: 'This is public' };
  }

  @Post('protected')
  @UseGuards(AuthGuard)
  @ApiBearerAuth()
  createProtectedResource(@Body() data: any) {
    return { success: true, data };
  }
}

// Register in a module
@Module({
  controllers: [CustomController],
})
export class CustomModule {}
```

## Development Scripts

```bash
# Install dependencies
pnpm install

# Development mode with hot reload
pnpm dev

# Build for production
pnpm build

# Start production server
pnpm start:prod

# Run tests
pnpm test

# Run tests with coverage
pnpm test:cov

# Lint code
pnpm lint

# Format code
pnpm format
```

## Production Deployment

### Using PM2

```javascript
// ecosystem.config.js
module.exports = {
  apps: [
    {
      name: 'social-dev-server',
      script: './dist/index.js',
      instances: 'max',
      exec_mode: 'cluster',
      env: {
        NODE_ENV: 'production',
        SOCIAL_DEV_SERVER_PORT: 3000,
      },
    },
  ],
};
```

```bash
# Build and start with PM2
pnpm build
pm2 start ecosystem.config.js
```

### Using Docker

```dockerfile
# Dockerfile
FROM node:18-alpine AS builder

WORKDIR /app
COPY package*.json pnpm-lock.yaml ./
RUN npm install -g pnpm
RUN pnpm install --frozen-lockfile

COPY . .
RUN pnpm build

FROM node:18-alpine

WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./

EXPOSE 3000
CMD ["node", "dist/index.js"]
```

### Using Vercel

```json
// vercel.json
{
  "version": 2,
  "builds": [
    {
      "src": "api/index.ts",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/api"
    }
  ]
}
```

```typescript
// api/index.ts
import { bootstrap } from '@social.dev/server-sdk/bootstrap';

export default async function handler(req, res) {
  const app = await bootstrap({
    // Your configuration
  });
  return app.getHttpAdapter().getInstance()(req, res);
}
```

## Multi-Network Support

The SDK supports running multiple isolated networks on a single server instance:

```typescript
bootstrap({
  network: {
    domainAliasMap: {
      'network1.example.com': 1,
      'network2.example.com': 2,
      'api.company.com': 3,
    },
  },
});

// Each domain will have isolated:
// - Users and authentication
// - Posts and content
// - Communities
// - Chat conversations
// - Notifications
```

## Security Best Practices

1. **Environment Variables**: Never commit `.env` files to version control
2. **Database**: Always disable `synchronize` in production
3. **CORS**: Configure allowed origins in production
4. **Rate Limiting**: Implement rate limiting for API endpoints
5. **Input Validation**: Use DTOs with class-validator for all inputs
6. **Authentication**: Use strong JWT secrets and appropriate expiration times
7. **HTTPS**: Always use HTTPS in production

## TypeScript Support

The SDK is written in TypeScript and provides full type definitions:

```typescript
import type {
  User,
  Post,
  Sub,
  Message,
  Conversation,
  AuthMethodEnum,
  OidcProvider,
  Configs,
} from '@social.dev/server-sdk';
```

## Examples

Check out the [apps/server](../../apps/server) directory for a complete implementation example using the SDK.

### Example Server Implementation

```typescript
// apps/server/index.ts
import SocialDevAiPlugin from '@social.dev/plugin-ai';
import { AuthMethodEnum } from '@social.dev/server-sdk/auth/enums/auth-method.enum';
import { PluginFactory } from '@social.dev/server-sdk/core/plugin/plugin.factory';

// Initialize plugins
PluginFactory.addPlugin(
  SocialDevAiPlugin.forRoot({
    userIds: [3],
  }),
);

// Initialize the server
import('@social.dev/server-sdk/bootstrap').then(({ bootstrap }) => {
  bootstrap({
    auth: {
      methods: [AuthMethodEnum.Oidc],
      oidc: {
        providers: [
          {
            id: 'minds-inc',
            name: 'Minds Keycloak',
            issuer: 'https://keycloak.minds.com/auth/realms/minds-inc',
            clientId: 'demo-social-dev',
            clientSecret: process.env.SOCIAL_DEV_OIDC_SECRET,
          },
        ],
      },
    },
    network: {
      domainAliasMap: {
        localhost: 2,
      },
    },
  });
});
```

## Troubleshooting

### Common Issues

1. **Database Connection Failed**
   - Check PostgreSQL is running
   - Verify database credentials in `.env`
   - Ensure database exists

2. **Port Already in Use**
   - Change `SOCIAL_DEV_SERVER_PORT` in `.env`
   - Kill existing process: `lsof -i :3000`

3. **Migration Errors**
   - Build the SDK first: `pnpm build`
   - Check database permissions
   - Review migration SQL for conflicts

4. **OIDC Authentication Failed**
   - Verify issuer URL is accessible
   - Check client ID and secret
   - Ensure redirect URIs are configured

## Contributing

Contributions are welcome! Please read our contributing guidelines before submitting PRs.

## License

MIT

## Support

- [Documentation](https://docs.social.dev)
- [GitHub Issues](https://github.com/socialdotdev/social.dev/issues)
- [Discord Community](https://discord.gg/socialdev)