JavaScript SDK

Complete JavaScript/TypeScript SDK for Archivus API.


Installation

npm install @archivus/client
# or
yarn add @archivus/client

Quick Start

import { ArchivusClient } from '@archivus/client';

// Initialize client
const client = new ArchivusClient({
  apiKey: 'YOUR_API_KEY',
  tenant: 'your-tenant'
});

// List documents
const documents = await client.documents.list({ limit: 10 });

// Upload document
const document = await client.documents.upload(
  file,
  { folderId: 'folder_xyz', enableAI: true }
);

// Search documents
const results = await client.search.search(
  'contracts expiring soon',
  { mode: 'semantic' }
);

// Chat with document
const session = await client.chat.createSession(document.id, 'Analysis');
const response = await client.chat.ask(session.id, 'What are the key terms?');
console.log(response.content);

Client Initialization

API Key Authentication

import { ArchivusClient } from '@archivus/client';

const client = new ArchivusClient({
  apiKey: 'ak_live_YOUR_API_KEY',
  tenant: 'your-tenant'
});

JWT Token Authentication

const client = new ArchivusClient({
  jwtToken: 'YOUR_JWT_TOKEN',
  tenant: 'your-tenant'
});

TypeScript Types

The SDK includes full TypeScript type definitions:

import { ArchivusClient, Document, ChatSession, SearchResult } from '@archivus/client';

const client = new ArchivusClient({
  apiKey: 'YOUR_API_KEY',
  tenant: 'your-tenant'
});

// Types are automatically inferred
const document: Document = await client.documents.get('doc_abc123');
const session: ChatSession = await client.chat.createSession('doc_abc123');
const results: SearchResult[] = await client.search.search('query');

Documents

List Documents

// Basic list
const documents = await client.documents.list();

// With filters
const documents = await client.documents.list({
  folderId: 'folder_xyz',
  tagId: 'tag_legal',
  limit: 20,
  page: 1
});

Get Document

const document = await client.documents.get('doc_abc123');

Upload Document

// From file input
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

const document = await client.documents.upload(file, {
  folderId: 'folder_xyz',
  enableAI: true,
  tags: ['contract', 'legal']
});

// Batch upload
const files = Array.from(fileInput.files);
const results = await client.documents.uploadBatch(files, {
  folderId: 'folder_xyz'
});

Update Document

const document = await client.documents.update('doc_abc123', {
  filename: 'Updated Name.pdf',
  tags: ['updated', 'important']
});

Delete Document

await client.documents.delete('doc_abc123');

Download Document

const blob = await client.documents.download('doc_abc123');
const url = URL.createObjectURL(blob);
// Use URL for download or display

// Semantic search
const results = await client.search.search('contracts expiring soon', {
  mode: 'semantic',
  limit: 20
});

// Keyword search
const results = await client.search.search('contract', {
  mode: 'text'
});
const results = await client.search.enhancedSearch(
  'Find all contracts expiring in Q4',
  {
    tags: ['contract'],
    date_range: {
      start: '2025-10-01',
      end: '2025-12-31'
    }
  },
  0.7  // min_score
);
const results = await client.search.hybridSearch('contract renewal', {
  semanticWeight: 0.7,
  textWeight: 0.3
});

Chat

Create Session

// Single document
const session = await client.chat.createSession('doc_abc123', 'Contract Analysis');

// Multiple documents
const session = await client.chat.createSession(
  ['doc_abc123', 'doc_def456'],
  'Multi-Doc Analysis'
);

Ask Question

const response = await client.chat.ask(
  session.id,
  'What are the key terms of this contract?'
);

console.log(response.content);
console.log(`Confidence: ${response.confidence}`);
console.log(`Sources: ${response.sources}`);

RAG Query

const response = await client.chat.askRAG(
  session.id,
  'Find all contracts expiring in Q4 2025'
);

Get History

const history = await client.chat.getHistory(session.id, { limit: 50 });
history.messages.forEach(message => {
  console.log(`${message.role}: ${message.content}`);
});

Folders

List Folders

const folders = await client.folders.list();

Create Folder

const folder = await client.folders.create({
  name: 'Contracts',
  parentId: null,
  color: '#3B82F6',
  icon: 'folder'
});

Update Folder

const folder = await client.folders.update('folder_abc123', {
  name: 'Updated Name',
  color: '#EF4444'
});

Delete Folder

await client.folders.delete('folder_abc123', { force: true });

Workspaces

Create Workspace

const workspace = await client.workspaces.create({
  name: 'Legal Team',
  description: 'Legal documents and contracts'
});

Add Member

await client.workspaces.addMember(workspace.id, {
  userId: 'user_xyz789',
  role: 'member',
  permission: 'edit'
});

List Members

const members = await client.workspaces.listMembers(workspace.id);

Error Handling

import { ArchivusError, RateLimitError } from '@archivus/client';

try {
  const document = await client.documents.get('doc_abc123');
} catch (error) {
  if (error instanceof ArchivusError) {
    if (error.code === 'NOT_FOUND') {
      console.log('Document not found');
    } else if (error.code === 'RATE_LIMIT_EXCEEDED') {
      console.log(`Rate limit exceeded. Reset at: ${error.resetAt}`);
    } else {
      console.log(`Error: ${error.message}`);
    }
  }
}

Rate Limiting

The SDK automatically handles rate limits:

// SDK automatically waits when rate limited
const documents = await client.documents.list();  // May wait if rate limited

You can also check rate limit status:

// Check remaining requests
const { remaining, limit, resetAt } = client.rateLimit;

if (remaining < 10) {
  console.log(`Approaching rate limit. Reset at: ${resetAt}`);
}

React Example

import React, { useState, useEffect } from 'react';
import { ArchivusClient } from '@archivus/client';

function DocumentList() {
  const [documents, setDocuments] = useState([]);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    const client = new ArchivusClient({
      apiKey: 'YOUR_API_KEY',
      tenant: 'your-tenant'
    });
    
    client.documents.list({ limit: 20 })
      .then(data => {
        setDocuments(data.data);
        setLoading(false);
      })
      .catch(error => {
        console.error('Error:', error);
        setLoading(false);
      });
  }, []);
  
  if (loading) return <div>Loading...</div>;
  
  return (
    <div>
      <h2>Documents</h2>
      <ul>
        {documents.map(doc => (
          <li key={doc.id}>{doc.filename}</li>
        ))}
      </ul>
    </div>
  );
}

Complete Example

import { ArchivusClient } from '@archivus/client';

async function main() {
  // Initialize client
  const client = new ArchivusClient({
    apiKey: 'YOUR_API_KEY',
    tenant: 'your-tenant'
  });
  
  // Upload document
  console.log('Uploading document...');
  const fileInput = document.querySelector('input[type="file"]');
  const file = fileInput.files[0];
  
  const document = await client.documents.upload(file, {
    folderId: 'folder_legal',
    enableAI: true
  });
  
  // Wait for processing
  console.log('Waiting for processing...');
  const processedDoc = await client.documents.waitForProcessing(document.id);
  
  // Search for similar documents
  console.log('Searching for similar documents...');
  const results = await client.search.search(
    'contracts similar to this one',
    { mode: 'semantic' }
  );
  
  // Chat with document
  console.log('Analyzing document...');
  const session = await client.chat.createSession(document.id, 'Analysis');
  const response = await client.chat.ask(
    session.id,
    'What are the key terms and risks?'
  );
  
  console.log(`\nAnalysis: ${response.content}`);
  console.log(`Confidence: ${response.confidence.toFixed(2)}`);
}

main();

API Reference

Documents

  • list(options?) - List documents
  • get(id) - Get document
  • upload(file, options?) - Upload document
  • uploadBatch(files, options?) - Batch upload
  • update(id, updates) - Update document
  • delete(id) - Delete document
  • download(id) - Download document
  • waitForProcessing(id, timeout?) - Wait for processing

Search

  • search(query, options?) - Basic search
  • enhancedSearch(query, filters?, minScore?) - Enhanced search
  • hybridSearch(query, options?) - Hybrid search

Chat

  • createSession(documentIds, name?) - Create session
  • ask(sessionId, message) - Ask question
  • askRAG(sessionId, message) - RAG query
  • getHistory(sessionId, options?) - Get history
  • deleteSession(sessionId) - Delete session

Folders

  • list(options?) - List folders
  • get(id) - Get folder
  • create(options) - Create folder
  • update(id, updates) - Update folder
  • delete(id, options?) - Delete folder

Workspaces

  • list() - List workspaces
  • get(id) - Get workspace
  • create(options) - Create workspace
  • addMember(workspaceId, options) - Add member
  • listMembers(workspaceId) - List members
  • removeMember(workspaceId, userId) - Remove member

Next Steps


Questions? Check the FAQ or contact support@ubiship.com