npm package: @lidia.poet/sdk
Description: TypeScript SDK for Lidia API
Author: Lidia Team
Latest version: 0.2.1

# Lidia TypeScript SDK

A comprehensive TypeScript SDK for the Lidia API, providing type-safe access to all Lidia services including cases, documents, conversations, messages, workflows, users, organizations, folders, tags, and more.

## Installation

```bash
npm install @lidia/sdk
```

## Quick Start

```typescript
import { LidiaSDK } from '@lidia/sdk';

const sdk = new LidiaSDK({
  baseUrl: 'https://api.lidiatech.ai',
  cognito: {
    region: 'eu-central-1',
    clientId: 'your-cognito-client-id',
  },
});

// Login with username and password
await sdk.login({
  username: 'your-email@example.com',
  password: 'your-password',
});

// Get all cases
const cases = await sdk.cases.find();

// Get conversations
const conversations = await sdk.conversations.find();

// Get current user
const user = await sdk.users.me();
```

## Configuration

The SDK supports multiple ways to provide configuration:

### 1. Explicit Configuration

```typescript
import { LidiaSDK, LidiaConfig } from '@lidia/sdk';

const config: LidiaConfig = {
  baseUrl: 'https://api.lidiatech.ai',
  cognito: {
    region: 'eu-central-1',
    clientId: 'your-cognito-client-id',
  },
  timeout: 30000,
  debug: false,
  retry: {
    attempts: 3,
    delay: 1000,
    backoff: 2,
  },
  headers: {
    'Custom-Header': 'value',
  },
};

const sdk = new LidiaSDK(config);
```

### 2. Environment Variables

The SDK can automatically read configuration from environment variables:

```bash
# Required for Cognito authentication
AWS_REGION=eu-central-1
COGNITO_CLIENT_ID=your-cognito-client-id

# Optional
LIDIA_BASE_URL=https://api.lidiatech.ai
COGNITO_USER_POOL_ID=your-user-pool-id

# Auto-login credentials (optional)
LIDIA_USERNAME=your-email@example.com
LIDIA_PASSWORD=your-password
```

```typescript
// Minimal configuration - SDK reads the rest from environment
const sdk = new LidiaSDK({
  baseUrl: 'https://api.lidiatech.ai',
});
```

**Note**: Environment variables are only read in Node.js environments. In browser environments, you must provide configuration explicitly.

## Authentication

The SDK uses AWS Cognito for authentication with the USER_PASSWORD_AUTH flow.

### Login Flow

```typescript
// Initialize SDK
const sdk = new LidiaSDK({
  baseUrl: 'https://api.lidiatech.ai',
  cognito: {
    region: 'eu-central-1',
    clientId: 'your-cognito-client-id',
  },
});

// Login
const tokens = await sdk.login({
  username: 'your-email@example.com',
  password: 'your-password',
});

// Check authentication status
console.log('Authenticated:', sdk.isAuthenticated());

// Get current tokens
const authTokens = sdk.getAuthTokens();

// Refresh tokens when needed
await sdk.refreshTokens();

// Logout
sdk.logout();
```

### Auto-Login

If you provide username and password in the config or environment variables, the SDK will automatically login:

```typescript
const sdk = new LidiaSDK({
  baseUrl: 'https://api.lidiatech.ai',
  cognito: {
    region: 'eu-central-1',
    clientId: 'your-cognito-client-id',
  },
  username: 'your-email@example.com',
  password: 'your-password',
});

// Wait for auto-login to complete
await sdk.waitForAuthentication();
```

## Services

### Cases

```typescript
// Get paginated cases
const cases = await sdk.cases.find({
  page: 1,
  pageSize: 10,
  search: ['important'],
  onlyMine: true,
});

// Create a case
const newCase = await sdk.cases.create({
  title: 'New Case',
});

// Get a specific case
const caseDetails = await sdk.cases.findOne('case-id');

// Update a case
await sdk.cases.update('case-id', { title: 'Updated Title' });

// Delete a case
await sdk.cases.delete('case-id');

// Get case participations
const participations = await sdk.cases.getParticipations('case-id');

// Replace participations
await sdk.cases.replaceParticipations('case-id', [
  {
    participantId: 'user-id',
    CaseParticipationType: 'USER',
    CaseRole: 'ADMIN',
  },
]);
```

### Conversations

```typescript
// Get conversations
const conversations = await sdk.conversations.find({
  page: 1,
  pageSize: 20,
  search: ['query'],
  caseId: 'case-id',
  starred: true,
});

// Create a conversation
const conversation = await sdk.conversations.create({
  caseId: 'case-id',
  title: 'New Conversation',
  type: 'CHAT',
});

// Get a specific conversation
const conv = await sdk.conversations.findOne('conversation-id');

// Update conversation
await sdk.conversations.update('conversation-id', {
  title: 'Updated Title',
});

// Delete conversation
await sdk.conversations.delete('conversation-id');

// Star/unstar a conversation
await sdk.conversations.star('conversation-id');
await sdk.conversations.unstar('conversation-id');

// Manage assignments
await sdk.conversations.assign('conversation-id', ['user-id-1', 'user-id-2']);
await sdk.conversations.unassign('conversation-id', ['user-id-1']);

// Add/remove documents
await sdk.conversations.addDocuments('conversation-id', ['doc-id-1', 'doc-id-2']);
await sdk.conversations.removeDocuments('conversation-id', ['doc-id-1']);

// Move conversation to another case
await sdk.conversations.move('conversation-id', 'new-case-id');

// Create from template
const fromTemplate = await sdk.conversations.createFromTemplate({
  caseId: 'case-id',
  templateId: 'template-id',
});

// Export conversation
const exportData = await sdk.conversations.export('conversation-id');
```

### Messages

```typescript
// Get messages for a conversation
const messages = await sdk.messages.find({
  conversationId: 'conversation-id',
  page: 1,
  pageSize: 50,
});

// Create a message
const message = await sdk.messages.create({
  conversationId: 'conversation-id',
  content: 'Hello!',
  role: 'USER',
});

// Get a specific message
const msg = await sdk.messages.findOne('message-id');

// Delete a message
await sdk.messages.delete('message-id');

// Add reaction to a message
await sdk.messages.addReaction('message-id', { emoji: 'thumbsup' });

// Request AI completion
const completion = await sdk.messages.complete('conversation-id', {
  content: 'Generate a summary',
});
```

### Documents

```typescript
// Get documents
const documents = await sdk.documents.findAll({
  caseId: 'case-id',
  type: 'DOCUMENT',
  visibility: 'PRIVATE',
  search: ['report'],
});

// Create a document
const document = await sdk.documents.create({
  name: 'Important Document',
  type: 'DOCUMENT',
  visibility: 'PRIVATE',
  folderId: null,
  tagIds: ['tag-id'],
  path: '/documents/report.pdf',
});

// Get a specific document
const doc = await sdk.documents.findOne('document-id');

// Update a document
await sdk.documents.update('document-id', { name: 'New Name' });

// Delete a document
await sdk.documents.delete('document-id');

// Download a document
const blob = await sdk.documents.download('document-id');
```

### Folders

```typescript
// Get folders
const folders = await sdk.folders.find({
  parentFolderId: 'parent-id',
});

// Create a folder
const folder = await sdk.folders.create({
  name: 'New Folder',
  parentFolderId: null,
});

// Get folder details
const folderDetails = await sdk.folders.findOne('folder-id');

// Delete a folder
await sdk.folders.delete('folder-id');
```

### Tags

```typescript
// Get all available tags
const tags = await sdk.tags.find();
```

### Conversation Templates

```typescript
// Get templates
const templates = await sdk.conversationTemplates.find({
  search: ['template'],
  caseId: 'case-id',
});

// Create a template
const template = await sdk.conversationTemplates.create({
  name: 'Support Template',
  description: 'Template for support conversations',
  messages: [
    { role: 'SYSTEM', content: 'You are a helpful assistant.' },
  ],
});

// Get a specific template
const tmpl = await sdk.conversationTemplates.findOne('template-id');

// Update a template
await sdk.conversationTemplates.update('template-id', {
  name: 'Updated Template',
});

// Delete a template
await sdk.conversationTemplates.delete('template-id');
```

### Smart Answers

```typescript
// Create a smart answer session
const smartAnswer = await sdk.smartAnswers.create({
  conversationId: 'conversation-id',
  query: 'What is the policy?',
});

// Get smart answer details
const sa = await sdk.smartAnswers.findOne('smart-answer-id');

// Update (rename) a smart answer
await sdk.smartAnswers.update('smart-answer-id', {
  name: 'Policy Question',
});
```

### Users

```typescript
// Get current user
const me = await sdk.users.me();

// Get all users
const users = await sdk.users.findAll({
  organizationId: 'org-id',
});

// Get a specific user
const user = await sdk.users.findOne('user-id');

// Create a user
const newUser = await sdk.users.create({
  email: 'user@example.com',
  firstName: 'John',
  lastName: 'Doe',
});

// Update a user
await sdk.users.update('user-id', { firstName: 'Jane' });

// Delete a user
await sdk.users.delete('user-id');
```

### Organizations

```typescript
// Get organizations
const orgs = await sdk.organizations.findAll();

// Get a specific organization
const org = await sdk.organizations.findOne('org-id');

// Create an organization
const newOrg = await sdk.organizations.create({
  name: 'My Organization',
});

// Update an organization
await sdk.organizations.update('org-id', { name: 'Updated Name' });

// Delete an organization
await sdk.organizations.delete('org-id');
```

### Workflows

```typescript
// Get workflows
const workflows = await sdk.workflows.findAll({
  caseId: 'case-id',
});

// Create a workflow
const workflow = await sdk.workflows.create({
  name: 'Document Review',
  caseId: 'case-id',
});

// Get a specific workflow
const wf = await sdk.workflows.findOne('workflow-id');

// Execute a workflow
const result = await sdk.workflows.execute('workflow-id', {
  documentId: 'doc-id',
});
```

### Favorites

```typescript
// Get favorites
const favorites = await sdk.favorites.findAll({
  resourceType: 'CASE',
});

// Add a favorite
await sdk.favorites.create({
  resourceType: 'CASE',
  resourceId: 'case-id',
});

// Remove a favorite
await sdk.favorites.delete('CASE', 'case-id');
```

## Error Handling

The SDK provides comprehensive error handling with specific error types:

```typescript
import { LidiaError, NetworkError, ValidationError } from '@lidia/sdk';

try {
  await sdk.cases.create({ title: '' });
} catch (error) {
  if (error instanceof ValidationError) {
    console.log('Validation errors:', error.details);
  } else if (error instanceof NetworkError) {
    console.log('Network error:', error.getUserMessage());
  } else if (error instanceof LidiaError) {
    console.log('API error:', error.code, error.message);
  }
}
```

## TypeScript Support

The SDK is fully typed with TypeScript definitions:

```typescript
import {
  // DTOs
  CaseDto,
  ConversationDto,
  MessageDto,
  DocumentDto,
  FolderDto,
  UserDto,

  // Create/Update DTOs
  CreateCaseDto,
  CreateConversationDto,
  CreateMessageDto,

  // Enums
  CaseRole,
  CaseParticipationType,
  ConversationType,
  MessageRole,
  MessageStatus,
  ResourceType,
  DocumentVisibility,
} from '@lidia/sdk';
```

## Advanced Usage

### Access the HTTP Client

```typescript
// Get the underlying client for custom requests
const client = sdk.getClient();

// Make custom requests
const response = await client.get<CustomType>('/custom-endpoint');
const data = await client.post<ResponseType>('/endpoint', { body: 'data' });
```

### Configuration Updates

```typescript
// Update configuration at runtime
sdk.updateConfig({
  timeout: 60000,
  debug: true,
});
```

### Retry Logic

The SDK includes built-in retry logic for failed requests:

```typescript
const sdk = new LidiaSDK({
  baseUrl: 'https://api.lidiatech.ai',
  cognito: {
    region: 'eu-central-1',
    clientId: 'your-cognito-client-id',
  },
  retry: {
    attempts: 5,
    delay: 2000,
    backoff: 1.5,
  },
});
```

## Development

### Building

```bash
npm run build
```

### Testing

```bash
npm test
npm run test:watch
npm run test:coverage
```

### Linting

```bash
npm run lint
npm run lint:fix
```

### Formatting

```bash
npm run format
```

## License

MIT

## Support

For support and questions, please contact the Lidia team or open an issue in the repository.