npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nikvector-js

v1.0.0

Published

Production-ready TypeScript SDK for Vector Context DB - Multi-tenant vector database with AI pattern recognition

Readme

nikvector-js

Production-ready TypeScript SDK for Vector Context DB - A multi-tenant vector database platform with built-in AI pattern recognition.

npm version License: MIT

Features

  • 🔐 Complete Authentication - Sign up, sign in, password management
  • 🏢 Multi-Tenant Support - Manage multiple projects with isolated data
  • 🔑 API Key Management - Create, rotate, and revoke API keys with role-based scopes
  • 🔍 Vector Search - Semantic search with pgvector
  • 🤖 AI Operations - Query suggestions and template execution
  • 📊 GraphQL API - Flexible data queries with Apollo Client
  • 🔄 Retry Logic - Automatic retry with exponential backoff
  • ⏱️ Request Timeout - Configurable timeouts with AbortController
  • 🐛 Debug Mode - Detailed logging for development
  • 📦 Batch Operations - Efficient bulk indexing and deletion
  • 💪 TypeScript - Full type safety with TypeScript

Installation

npm install nikvector-js
# or
yarn add nikvector-js
# or
pnpm add nikvector-js

Quick Start

import { createClient } from 'nikvector-js';

// Create client
const client = createClient({
  url: 'https://your-instance.vercel.app',
  anonKey: process.env.VECTOR_DB_ANON_KEY, // Optional
  tenantId: 'your-tenant-id', // Optional
  debug: true, // Enable debug logging
  maxRetries: 3, // Retry failed requests
  timeout: 30000, // 30 second timeout
});

// Sign up
const session = await client.auth.signUp('[email protected]', 'password', 'John Doe');

// Sign in
const { user, access_token } = await client.auth.signIn('[email protected]', 'password');

// Create a project
const project = await client.tenants.create('My Project', 'my-project');

// Select tenant for operations
client.tenants.select(project.id);

// Index content
const doc = await client.vector.index({
  text: 'Vector databases are essential for AI applications',
  source: 'document.pdf',
  metadata: { category: 'AI', tags: ['vector', 'database'] },
});

// Search vectors
const results = await client.vector.query({
  query: 'What are vector databases?',
  threshold: 0.7,
  limit: 10,
});

console.log(results);

Authentication

Sign Up

const session = await client.auth.signUp(
  '[email protected]',
  'secure-password',
  'Display Name' // Optional
);

console.log('User:', session.user);
console.log('Access Token:', session.access_token);

Sign In

const session = await client.auth.signIn('[email protected]', 'password');

Get Current User

const user = await client.auth.getUser();
if (user) {
  console.log('Logged in as:', user.email);
}

Change Password

await client.auth.changePassword('old-password', 'new-password');

Sign Out

client.auth.signOut();

Multi-Tenant Operations

List Projects

const projects = await client.tenants.list();
projects.forEach(project => {
  console.log(`${project.name} (${project.slug})`);
});

Create Project

const project = await client.tenants.create('My New Project', 'my-new-project');
console.log('Created:', project.id);

Get Project Details

const project = await client.tenants.get('project-id');
console.log(project.name, project.databaseUrl);

Select Tenant

// All vector operations will use this tenant
client.tenants.select('project-id');

// Get current tenant
const currentTenantId = client.tenants.getCurrent();

API Key Management

Create API Key

// With default scopes based on role
const key = await client.apiKeys.create({
  tenantId: 'project-id',
  name: 'Production Key',
  role: 'SERVICE', // ANON, SERVICE, or ADMIN
});

console.log('API Key:', key.raw); // Save this securely!
console.log('Prefix:', key.prefix);
console.log('Scopes:', key.scopes);

Custom Scopes

const key = await client.apiKeys.create({
  tenantId: 'project-id',
  name: 'Custom Key',
  role: 'SERVICE',
  scopes: ['graphql.read', 'vector.read', 'vector.write'],
});

Default Scopes by Role

  • ANON: ['graphql.read', 'vector.read']
  • SERVICE: ['graphql.read', 'graphql.write', 'vector.read', 'vector.write', 'graphql.execute']
  • ADMIN: All scopes including 'admin'

List API Keys

// List all keys
const keys = await client.apiKeys.list();

// List keys for specific tenant
const tenantKeys = await client.apiKeys.list('tenant-id');

keys.forEach(key => {
  console.log(`${key.name}: ${key.prefix}...${key.lastFour}`);
});

Revoke API Key

await client.apiKeys.revoke('key-id');

Rotate API Key

const newKey = await client.apiKeys.rotate('old-key-id');
console.log('New key:', newKey.raw);

Vector Operations

Index Document

const doc = await client.vector.index({
  text: 'Your document content here',
  source: 'document.pdf',
  metadata: {
    category: 'technical',
    author: 'John Doe',
    tags: ['ai', 'ml'],
  },
});

Batch Indexing

const documents = [
  { text: 'First document', metadata: { id: 1 } },
  { text: 'Second document', metadata: { id: 2 } },
  { text: 'Third document', metadata: { id: 3 } },
];

const results = await client.vector.indexBatch(documents);
console.log(`Indexed ${results.length} documents`);

Search Vectors

const results = await client.vector.query({
  query: 'machine learning applications',
  threshold: 0.7, // Minimum similarity (0-1)
  limit: 10, // Max results
});

results.forEach(result => {
  console.log(`Similarity: ${result.similarity}`);
  console.log(`Content: ${result.content}`);
  console.log(`Metadata:`, result.metadata);
});

Delete Document

const success = await client.vector.delete('document-id');

Batch Delete

const ids = ['doc-1', 'doc-2', 'doc-3'];
const success = await client.vector.deleteBatch(ids);

GraphQL Operations

Direct GraphQL Query

const data = await client.db.graphql(`
  query {
    documents {
      id
      source
      metadata
      createdAt
    }
  }
`);

With Variables

const data = await client.db.query(
  `
  query GetDocument($id: ID!) {
    document(id: $id) {
      id
      source
      chunks {
        content
      }
    }
  }
`,
  { id: 'document-id' }
);

GraphQL Mutation

const data = await client.db.mutate(
  `
  mutation CreateDocument($input: IndexTextInput!) {
    indexText(input: $input) {
      id
      source
    }
  }
`,
  {
    input: {
      text: 'Document content',
      source: 'file.txt',
    },
  }
);

AI Operations

Query Suggestions

const suggestions = await client.ai.suggestQuery('how to use the API', 5);

suggestions.forEach(template => {
  console.log(`${template.name}: ${template.description}`);
  console.log(`Similarity: ${template.similarity}`);
});

Run Template

const result = await client.ai.runTemplate('template-id', {
  category: 'technical',
  limit: 10,
});

console.log('Query:', result.finalQuery);
console.log('Results:', result.result);
console.log('Latency:', result.latencyMs, 'ms');

Error Handling

The SDK provides a comprehensive error handling system:

import { VectorDBError } from 'nikvector-js';

try {
  await client.vector.query({ query: 'test' });
} catch (error) {
  if (error instanceof VectorDBError) {
    console.error('Error code:', error.code);
    console.error('Status:', error.statusCode);
    console.error('Message:', error.message);
    console.error('Details:', error.details);

    // Handle specific errors
    switch (error.code) {
      case 'UNAUTHORIZED':
        // Refresh token or redirect to login
        break;
      case 'RATE_LIMITED':
        // Wait and retry
        break;
      case 'NOT_FOUND':
        // Resource doesn't exist
        break;
      default:
        // Handle other errors
    }
  }
}

Error Codes

  • UNAUTHORIZED (401): Invalid or expired credentials
  • FORBIDDEN (403): Insufficient permissions
  • NOT_FOUND (404): Resource not found
  • CONFLICT (409): Resource already exists
  • RATE_LIMITED (429): Rate limit exceeded
  • SERVER_ERROR (500+): Server-side error
  • TIMEOUT (408): Request timeout
  • NETWORK_ERROR: Network connectivity issue
  • GRAPHQL_ERROR: GraphQL query/mutation error

Retry Logic

The SDK automatically retries failed requests:

const client = createClient({
  url: 'https://your-instance.vercel.app',
  maxRetries: 3, // Number of retry attempts (default: 3)
  retryDelay: 1000, // Initial delay in ms (default: 1000)
});
  • Automatic retry for 429 (rate limit) and 5xx errors
  • Exponential backoff: delay * (2 ^ attempt)
  • Respects Retry-After header for rate limits
  • Network errors are also retried

Request Timeout

Configure request timeouts to prevent hanging:

const client = createClient({
  url: 'https://your-instance.vercel.app',
  timeout: 30000, // 30 seconds (default)
});

Requests are automatically cancelled after the timeout using AbortController.

Debug Mode

Enable debug logging for development:

const client = createClient({
  url: 'https://your-instance.vercel.app',
  debug: true,
});

Debug mode logs:

  • All HTTP requests and responses
  • Request/response timing
  • Retry attempts
  • GraphQL operations

Advanced Usage

Custom Apollo Client Configuration

The SDK uses Apollo Client for GraphQL operations with optimized defaults:

  • fetchPolicy: network-only (always fetch fresh data)
  • errorPolicy: all (return partial data with errors)
  • Automatic authentication headers
  • Request/response caching

Working with Multiple Tenants

// Create client
const client = createClient({ url: 'https://your-instance.vercel.app' });

// Sign in
await client.auth.signIn('[email protected]', 'password');

// List projects
const projects = await client.tenants.list();

// Switch between projects
for (const project of projects) {
  client.tenants.select(project.id);

  // Perform operations on this project
  const results = await client.vector.query({
    query: 'search query',
    limit: 5,
  });

  console.log(`Results for ${project.name}:`, results.length);
}

Using with API Keys

// Create client with API key (no authentication needed)
const client = createClient({
  url: 'https://your-instance.vercel.app',
  anonKey: 'your-service-api-key',
  tenantId: 'your-tenant-id',
});

// Direct access to vector operations
const results = await client.vector.query({
  query: 'search query',
});

Best Practices

  1. Store API Keys Securely: Never commit API keys to version control
  2. Use Environment Variables: Store configuration in environment variables
  3. Enable Debug Mode: Use debug mode during development
  4. Handle Errors: Always handle errors gracefully
  5. Batch Operations: Use batch operations for multiple documents
  6. Select Tenant: Always select a tenant before vector operations
  7. Retry Configuration: Adjust retry settings based on your use case
  8. Monitor Usage: Track API usage and implement rate limiting on your side

TypeScript Support

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

import {
  VectorNikVectorsClient,
  VectorNikVectorsClientOptions,
  VectorDBError,
  User,
  Tenant,
  ApiKey,
  Document,
  SearchResult,
  QueryTemplate,
} from 'nikvector-js';

Examples

See the /examples directory for complete examples:

  • RAG Application
  • Chatbot with Vector Search
  • Multi-Tenant SaaS
  • API Key Management
  • Batch Processing

API Reference

Full API documentation is available at https://docs.vectorcontextdb.com

Building from Source

# Install dependencies
npm install

# Build
npm run build

# Output: dist/index.js and dist/index.d.ts

Publishing

# Update version in package.json
npm version 1.0.0

# Build
npm run build

# Publish to npm
npm publish --access public

Contributing

Contributions are welcome! Please read our Contributing Guide for details.

License

MIT

Support