Skip to content

shariarfaisal/chatvault-js-sdk

Repository files navigation

ChatVault JavaScript SDK

Official JavaScript/TypeScript SDK for the ChatVault API. Zero dependencies, full TypeScript support, works in both Node.js and browsers.

Features

  • πŸš€ Zero Dependencies - Lightweight and fast
  • πŸ“ Full TypeScript Support - Complete type definitions included
  • 🌐 Universal - Works in Node.js and browsers
  • πŸ”„ Automatic Retries - Built-in exponential backoff
  • 🎯 Simple API - Intuitive and easy to use
  • πŸ“Š Streaming Support - Real-time message updates
  • πŸ›‘οΈ Error Handling - Comprehensive error management

Installation

npm install @chatvault/sdk
# or
yarn add @chatvault/sdk
# or
pnpm add @chatvault/sdk

Quick Start

import ChatVault from '@chatvault/sdk';

// Initialize the client
const vault = new ChatVault({
  baseURL: 'http://localhost:7734',
  userId: 'user_123'
});

// Create a session
const session = await vault.sessions.create({
  type: 'chat',
  title: 'Support Chat'
});

// Add messages
await vault.messages.sendText(
  session.id,
  'Hello, I need help!',
  'user'
);

// Get session with all messages
const fullSession = await vault.sessions.get(session.id, true);
console.log(fullSession.messages);

Configuration

const vault = new ChatVault({
  baseURL: 'https://api.chatvault.io',  // Required
  userId: 'user_123',                   // Required
  apiKey: 'your-api-key',              // Optional
  timeout: 30000,                       // Optional (default: 30000ms)
  retries: 3,                          // Optional (default: 3)
  headers: {                           // Optional custom headers
    'X-Custom-Header': 'value'
  },
  onRequest: (config) => {             // Optional request interceptor
    console.log('Request:', config);
  },
  onResponse: (response) => {          // Optional response interceptor
    console.log('Response:', response);
  },
  onError: (error) => {                // Optional error handler
    console.error('Error:', error);
  }
});

API Reference

Sessions

Create Session

const session = await vault.sessions.create({
  type: 'chat',              // Required: 'chat' | 'collection' | 'summary' | 'document' | 'analysis'
  title: 'Session Title',    // Optional
  metadata: {                // Optional
    tags: ['important'],
    customField: 'value'
  }
});

Get Session

// Get session without messages
const session = await vault.sessions.get('session_id');

// Get session with messages
const sessionWithMessages = await vault.sessions.get('session_id', true);

List Sessions

const sessions = await vault.sessions.list({
  type: 'chat',      // Optional: filter by type
  limit: 50,         // Optional: default 50
  offset: 0,         // Optional: for pagination
  order: 'desc'      // Optional: 'asc' or 'desc'
});

Update Session

const updated = await vault.sessions.update('session_id', {
  title: 'New Title',
  metadata: {
    status: 'resolved'
  }
});

Delete Session

await vault.sessions.delete('session_id');

Export Session

// Export as JSON
const json = await vault.sessions.export('session_id', 'json');

// Export as Markdown
const markdown = await vault.sessions.export('session_id', 'markdown');

// Export as plain text
const text = await vault.sessions.export('session_id', 'txt');

Messages

Create Message

const message = await vault.messages.create({
  sessionId: 'session_id',
  role: 'user',           // 'user' | 'assistant' | 'system' | 'function' | 'tool'
  contentType: 'text',    // Optional: defaults to 'text'
  content: {
    type: 'text',
    text: 'Hello!'
  },
  metadata: {             // Optional
    timestamp: Date.now()
  }
});

Helper Methods

// Send text message
await vault.messages.sendText('session_id', 'Hello!', 'user');

// Send JSON data
await vault.messages.sendJSON('session_id', { key: 'value' }, 'assistant');

// Send code
await vault.messages.sendCode('session_id', 'console.log("Hi")', 'javascript', 'assistant');

// Send mixed content
await vault.messages.sendMixed('session_id', [
  { type: 'text', text: 'Here is the result:' },
  { type: 'json', data: { result: 'success' } }
], 'assistant');

List Messages

const messages = await vault.messages.list('session_id', {
  role: 'user',    // Optional: filter by role
  limit: 100,      // Optional
  offset: 0        // Optional
});

Update Message

const updated = await vault.messages.update(messageId, {
  content: {
    type: 'text',
    text: 'Updated text'
  }
});

Delete Message

await vault.messages.delete(messageId);

Streaming

Stream messages in real-time:

const stream = vault.messages.stream('session_id', (message) => {
  console.log('New message:', message);
});

// Listen to events
stream.on('error', (error) => {
  console.error('Stream error:', error);
});

stream.on('close', () => {
  console.log('Stream closed');
});

// Close the stream when done
stream.close();

User Statistics

const stats = await vault.getStats();
console.log(stats);
// {
//   userId: 'user_123',
//   totalSessions: 42,
//   sessionsByType: { chat: 30, collection: 12 },
//   totalMessages: 1250,
//   messagesByRole: { user: 625, assistant: 625 },
//   storageUsedBytes: 524288,
//   lastActivity: '2024-01-15T10:30:00Z'
// }

Batch Operations

Execute multiple operations in a single call:

const results = await vault.batch([
  {
    type: 'create',
    resource: 'session',
    data: { type: 'chat', title: 'Batch Session' }
  },
  {
    type: 'create',
    resource: 'message',
    data: {
      sessionId: 'session_id',
      role: 'user',
      content: { type: 'text', text: 'Batch message' }
    }
  }
]);

Search

Search across sessions and messages:

const results = await vault.search({
  query: 'important keyword',
  sessionTypes: ['chat', 'collection'],
  dateRange: {
    from: '2024-01-01',
    to: '2024-12-31'
  }
});

Export Data

Export all user data:

// Export as JSON
const jsonData = await vault.exportData('json');

// Export as Markdown
const markdownData = await vault.exportData('markdown');

TypeScript Support

The SDK includes comprehensive TypeScript definitions:

import ChatVault, {
  Session,
  Message,
  SessionType,
  MessageRole,
  ChatVaultConfig,
  ChatVaultError
} from '@chatvault/sdk';

// Full type safety and IntelliSense support
const config: ChatVaultConfig = {
  baseURL: 'http://localhost:7734',
  userId: 'user_123'
};

const vault = new ChatVault(config);

// Type-safe operations
const session: Session = await vault.sessions.create({
  type: 'chat' as SessionType,
  title: 'Typed Session'
});

Error Handling

import { ChatVaultError } from '@chatvault/sdk';

try {
  await vault.sessions.get('invalid_id');
} catch (error) {
  if (error instanceof ChatVaultError) {
    console.error('Status:', error.statusCode);
    console.error('Message:', error.message);
    console.error('Response:', error.response);
  } else {
    console.error('Unexpected error:', error);
  }
}

Browser Usage

Via CDN

<script src="https://unpkg.com/@chatvault/sdk/dist/chatvault.min.js"></script>
<script>
  const vault = new ChatVault({
    baseURL: 'https://api.chatvault.io',
    userId: 'user_123'
  });

  vault.sessions.create({ type: 'chat' })
    .then(session => console.log(session));
</script>

Via ES Modules

import ChatVault from 'https://unpkg.com/@chatvault/sdk/dist/index.esm.js';

const vault = new ChatVault({
  baseURL: 'https://api.chatvault.io',
  userId: 'user_123'
});

Examples

See the examples directory for more detailed examples:

Development

Setup

# Clone the repository
git clone https://github.com/chatvault/sdk-js.git
cd sdk-js

# Install dependencies
npm install

# Build the SDK
npm run build

# Run in development mode
npm run dev

Testing

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

Building

# Build all formats
npm run build

# Build and watch for changes
npm run dev

API Compatibility

This SDK is compatible with ChatVault API v1.0.0 and above.

Support

License

MIT License - see LICENSE file for details

About

Perfect for building chat applications, customer support systems, conversation analytics tools, AI assistant interfaces, and any application requiring structured conversation storage and retrieval.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors