SDK Reference

TypeScript SDK for Vident observability. Distributed tracing, custom metrics, structured events, and cron monitoring.

Installation

npm install vident-sdk

Quick Start

import { Vident } from 'vident-sdk';

const vident = new Vident({
  apiKey: 'vd_...',
  serviceName: 'my-api',
});

// Record a metric
vident.counter('orders.processed', 1, { region: 'eu' });

// Log a structured event
vident.info('order.completed', 'Order processed successfully', { orderId: '123' });

// Create a trace span
const span = vident.startSpan('process-order');
// ... do work
span.end();

Configuration

const vident = new Vident({
  apiKey: 'vd_...',
  serviceName: 'my-api',
  baseUrl: 'https://api.vident.dev', // optional
  timeout: 30000,                    // optional, default 30s
});

Custom Metrics

Record application metrics for dashboards and alerting. Metrics are batched and sent automatically.

Counter

Increments a value. Use for counting events, requests, errors.

// Increment by 1
vident.counter('api.requests');

// Increment by custom value
vident.counter('orders.processed', 5, { region: 'eu', tier: 'premium' });

Gauge

Point-in-time value. Use for queue depth, connections, temperature.

vident.gauge('queue.depth', 42);
vident.gauge('db.connections', 15, { pool: 'primary' });

Histogram

Distribution of values. Use for latency, sizes, durations.

vident.histogram('request.duration', 150);
vident.histogram('file.size', 1024, { type: 'upload' });

Simple Metric Helper

Defaults to gauge. Convenient for simple use cases.

vident.metric('temperature', 72.5);

Flush Metrics

Force send pending metrics immediately (useful before shutdown).

await vident.flushMetrics();

Structured Events

Log structured events with levels and attributes. Events are automatically correlated with the active trace.

// Info-level event (default)
vident.event('user.login', 'User logged in', { userId: '123' });

// All log levels
vident.debug('cache.hit', 'Cache hit for key', { key: 'user:123' });
vident.info('order.created', 'New order received', { orderId: 'abc' });
vident.warn('rate.limit', 'Approaching rate limit', { current: 95, max: 100 });
vident.errorEvent('payment.failed', 'Card declined', { reason: 'insufficient_funds' });

Flush Events

await vident.flushEvents();

Distributed Tracing

Create spans to trace requests across services.

// Start a span
const span = vident.startSpan('process-order', {
  attributes: { orderId: '123' },
});

try {
  // Do work...
  span.setAttribute('items', 5);
} catch (error) {
  span.recordException(error);
  throw error;
} finally {
  span.end();
}

// Or use withSpan for automatic lifecycle management
await vident.withSpan('fetch-user', async (span) => {
  const user = await fetchUser(id);
  span.setAttribute('userId', user.id);
  return user;
});

Cron Pinging

Notify Vident when your cron job runs.

await vident.ping('cron-job-id');                              // Success
await vident.ping('cron-job-id', { type: 'start' });           // Job started
await vident.ping('cron-job-id', { type: 'fail' });            // Job failed
await vident.ping('cron-job-id', { type: 'fail', body: 'Error details' });

Cron Jobs

// List all cron jobs in an environment
const cronJobs = await vident.cronJobs.list('environment-id');

// Get a single cron job
const cronJob = await vident.cronJobs.get('cron-job-id');

// Create a cron job
const cronJob = await vident.cronJobs.create('environment-id', {
  name: 'DB Backup',
  scheduleType: 'PERIOD',
  scheduleValue: '3600', // every hour
});

// Update a cron job
await vident.cronJobs.update('cron-job-id', { name: 'New Name' });

// Pause/resume
await vident.cronJobs.pause('cron-job-id');
await vident.cronJobs.resume('cron-job-id');

// Delete
await vident.cronJobs.delete('cron-job-id');

// Uptime stats (last 90 days)
const stats = await vident.cronJobs.stats('cron-job-id', 90);

Channels (Notifications)

// List channels
const channels = await vident.channels.list('environment-id');

// Create a Slack channel
const channel = await vident.channels.create('environment-id', {
  type: 'SLACK_WEBHOOK',
  name: 'Slack Alerts',
  config: { webhookUrl: 'https://hooks.slack.com/...' },
});

// Update
await vident.channels.update('environment-id', 'channel-id', { name: 'New Name' });

// Test notification
await vident.channels.test('environment-id', 'channel-id');

// Delete
await vident.channels.delete('environment-id', 'channel-id');

Organizations

const orgs = await vident.organizations.list();
const org = await vident.organizations.get('org-id');
const org = await vident.organizations.create({ name: 'My Org', slug: 'my-org' });
await vident.organizations.update('org-id', { name: 'New Name' });
await vident.organizations.delete('org-id');

API Keys

const keys = await vident.apiKeys.list('environment-id');
const newKey = await vident.apiKeys.create('environment-id', { name: 'CI/CD' });
console.log(newKey.key); // Full key shown only once
await vident.apiKeys.delete('environment-id', 'key-id');

Error Handling

import { VidentError, NotFoundError, UnauthorizedError } from 'vident-sdk';

try {
  await vident.cronJobs.get('invalid-id');
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log('Cron job not found');
  } else if (error instanceof UnauthorizedError) {
    console.log('Invalid API key');
  } else if (error instanceof VidentError) {
    console.log(`Error: ${error.message} (${error.code})`);
  }
}

TypeScript Types

All types are exported for TypeScript users:

import type {
  MetricType,    // 'counter' | 'gauge' | 'histogram'
  EventLevel,    // 'debug' | 'info' | 'warn' | 'error'
  CronJob,
  MonitorStatus,
  Channel,
  ChannelType,
  Organization,
  Environment,
} from 'vident-sdk';

Graceful Shutdown

Flush all pending data before your application exits:

process.on('SIGTERM', async () => {
  await Promise.all([
    vident.flushMetrics(),
    vident.flushEvents(),
  ]);
  vident.destroy();
  process.exit(0);
});