JavaScript/TypeScript SDK

The official NEXXUS JavaScript SDK provides a TypeScript-first interface for AI trust and safety evaluation, with support for Node.js, browsers, and React.

Requirements

Node.js 18+ or modern browser with Fetch API

Installation

npmbash
npm install @trustscan/sdk
yarnbash
yarn add @trustscan/sdk
pnpmbash
pnpm add @trustscan/sdk

Quick Start

Get started with a simple evaluation in just a few lines of code:

Basic Usagetypescript
import { NEXXUSClient } from '@trustscan/sdk';

// Initialize the client
const client = new NEXXUSClient({
  apiKey: 'ts_live_your_api_key'
});

// Run an evaluation
const result = await client.evaluate({
  content: 'The recommended dosage is 500mg every 6 hours.',
  context: 'User asked about medication dosage',
  mode: 'STANDARD'
});

// Access results
console.log(`Trust Score: ${result.trustScore}/100`);
console.log(`Verdict: ${result.verdict}`);
console.log(`Certification: ${result.certificationTier}`);

// Check for issues
if (result.blockers.length > 0) {
  console.log('\nBlockers found:');
  for (const blocker of result.blockers) {
    console.log(`  - ${blocker.message} (${blocker.severity})`);
  }
}

// Review evaluator results
for (const evaluator of result.evaluatorResults) {
  console.log(`\n${evaluator.name}: ${evaluator.verdict} (${evaluator.score}/100)`);
  for (const issue of evaluator.issues) {
    console.log(`  - ${issue.message}`);
  }
}

Authentication

Configure authentication using one of these methods:

Option 1: Direct API Key

import { NEXXUSClient } from '@trustscan/sdk';

const client = new NEXXUSClient({
  apiKey: 'ts_live_your_api_key'
});

Option 2: Environment Variable (Node.js)

export TRUSTSCAN_API_KEY="ts_live_your_api_key"
import { NEXXUSClient } from '@trustscan/sdk';

// Automatically uses TRUSTSCAN_API_KEY
const client = new NEXXUSClient({
  apiKey: process.env.TRUSTSCAN_API_KEY!
});

Option 3: With Organization

const client = new NEXXUSClient({
  apiKey: 'ts_live_your_api_key',
  organizationId: 'org_abc123'
});

Evaluation Modes

Choose the evaluation mode based on your needs:

ModeSpeedDepthUse Case
INSTANT<100msBasicReal-time filtering
STANDARD1-3sComprehensiveProduction evaluation
DEEP5-30sExhaustiveCompliance audits
Mode Examplestypescript
// Quick check for content moderation
const instant = await client.evaluate({ content: '...', mode: 'INSTANT' });

// Standard production evaluation
const standard = await client.evaluate({ content: '...', mode: 'STANDARD' });

// Deep analysis for compliance
const deep = await client.evaluate({ content: '...', mode: 'DEEP' });

React Integration

Use the built-in React hooks for seamless integration:

Provider Setup

import { NEXXUSProvider } from '@trustscan/sdk/react';

function App() {
  return (
    <NEXXUSProvider apiKey="ts_live_xxx">
      <MyComponent />
    </NEXXUSProvider>
  );
}

useEvaluation Hook

import { useEvaluation } from '@trustscan/sdk/react';

function ContentValidator() {
  const { evaluate, result, loading, error } = useEvaluation();

  const handleSubmit = async (content: string) => {
    await evaluate({
      content,
      mode: 'STANDARD'
    });
  };

  if (loading) return <div>Evaluating...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      {result && (
        <div>
          <p>Trust Score: {result.trustScore}</p>
          <p>Verdict: {result.verdict}</p>
        </div>
      )}
      <button onClick={() => handleSubmit('AI response text')}>
        Evaluate
      </button>
    </div>
  );
}

useNEXXUS Hook

import { useNEXXUS } from '@trustscan/sdk/react';

function SystemDashboard() {
  const client = useNEXXUS();
  const [systems, setSystems] = useState([]);

  useEffect(() => {
    async function loadSystems() {
      const response = await client.listSystems();
      setSystems(response.systems);
    }
    loadSystems();
  }, [client]);

  return (
    <ul>
      {systems.map(system => (
        <li key={system.systemId}>
          {system.name}: {system.trustScore}
        </li>
      ))}
    </ul>
  );
}

Async Evaluations

For large content or DEEP mode, use async evaluations with polling:

Async Evaluation with Pollingtypescript
// Start async evaluation
const asyncResult = await client.evaluateAsync({
  content: largeDocument,
  mode: 'DEEP'
});

console.log(`Evaluation ID: ${asyncResult.evaluationId}`);
console.log(`Status: ${asyncResult.status}`);

// Wait for completion with polling
const result = await client.waitForEvaluation(asyncResult.evaluationId, {
  pollIntervalMs: 2000,  // Poll every 2 seconds
  maxWaitMs: 300000      // 5 minutes timeout
});

console.log(`Completed! Trust Score: ${result.trustScore}`);
With Webhooktypescript
// Start evaluation with webhook callback
const asyncResult = await client.evaluateAsync({
  content: largeDocument,
  mode: 'DEEP',
  webhookUrl: 'https://your-app.com/webhooks/trustscan'
});

// Your webhook will receive the result when complete

Systems Management

Track AI systems and their evaluation history:

Create and Evaluate Systemtypescript
// Create a system
const system = await client.createSystem({
  name: 'Customer Support Bot',
  industry: 'retail',
  systemType: 'chatbot',
  description: 'AI-powered customer support'
});

console.log(`System ID: ${system.systemId}`);

// Evaluate the system
const result = await client.evaluateSystem(system.systemId, {
  content: 'Bot response to evaluate',
  mode: 'STANDARD'
});

// Get evaluation history
const history = await client.getSystemHistory(system.systemId, {
  limit: 10
});

for (const eval of history.evaluations) {
  console.log(`${eval.timestamp}: Score ${eval.trustScore}`);
}
List and Filter Systemstypescript
// List all systems
const systems = await client.listSystems();

// Filter by criteria
const healthcareSystems = await client.listSystems({
  industry: 'healthcare',
  minTrustScore: 80,
  certificationTier: 'GOLD'
});

for (const system of healthcareSystems.systems) {
  console.log(`${system.name}: ${system.trustScore}`);
}

Error Handling

Handle errors gracefully with specific exception types:

Exception Handlingtypescript
import {
  NEXXUSClient,
  NEXXUSError,
  AuthenticationError,
  RateLimitError,
  ValidationError,
  TimeoutError,
} from '@trustscan/sdk';

const client = new NEXXUSClient({ apiKey: 'ts_live_xxx' });

try {
  const result = await client.evaluate({ content: '...' });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after ${error.retryAfter} seconds`);
  } else if (error instanceof ValidationError) {
    console.error(`Invalid request: ${error.message}`);
    console.error('Details:', error.details);
  } else if (error instanceof TimeoutError) {
    console.error('Request timed out');
  } else if (error instanceof NEXXUSError) {
    console.error(`API error: ${error.message} (code: ${error.code})`);
  } else {
    throw error;
  }
}

Configuration

Customize client behavior:

Advanced Configurationtypescript
import { NEXXUSClient } from '@trustscan/sdk';

const client = new NEXXUSClient({
  apiKey: 'ts_live_your_api_key',
  organizationId: 'org_abc123',
  baseUrl: 'https://api.trustscan.io',  // Custom endpoint
  timeout: 60000,  // Request timeout in ms
  retry: {
    maxRetries: 3,
    initialDelay: 1000,
    maxDelay: 30000,
    retryableStatuses: [429, 500, 502, 503, 504]
  }
});

Common Use Cases

LLM Response Validation

async function validateLLMResponse(prompt: string, response: string): Promise<boolean> {
  const result = await client.evaluate({
    content: response,
    context: prompt,
    mode: 'INSTANT'
  });

  if (result.verdict === 'FAIL' || result.verdict === 'HARD_FAIL') {
    console.warn('Response failed validation:', result.blockers);
    return false;
  }

  return true;
}

Batch Processing

interface Item {
  id: string;
  content: string;
  context?: string;
}

async function processBatch(items: Item[]): Promise<Array<{
  id: string;
  trustScore: number | null;
  error: string | null;
}>> {
  const results = await Promise.allSettled(
    items.map(item =>
      client.evaluate({
        content: item.content,
        context: item.context,
        mode: 'STANDARD'
      })
    )
  );

  return results.map((result, index) => ({
    id: items[index].id,
    trustScore: result.status === 'fulfilled' ? result.value.trustScore : null,
    error: result.status === 'rejected' ? result.reason.message : null
  }));
}

Express Middleware

import express from 'express';
import { NEXXUSClient } from '@trustscan/sdk';

const client = new NEXXUSClient({ apiKey: process.env.TRUSTSCAN_API_KEY! });

const trustValidation = async (
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
) => {
  const { response } = req.body;

  if (!response) {
    return next();
  }

  try {
    const result = await client.evaluate({
      content: response,
      mode: 'INSTANT'
    });

    if (result.verdict === 'HARD_FAIL') {
      return res.status(400).json({
        error: 'Content failed trust validation',
        blockers: result.blockers
      });
    }

    // Attach result to request for downstream use
    req.trustScanResult = result;
    next();
  } catch (error) {
    console.error('NEXXUS validation failed:', error);
    next(); // Continue on error (fail-open)
  }
};

app.post('/api/chat', trustValidation, (req, res) => {
  // Handle validated request
});

Next.js API Route

// app/api/evaluate/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { NEXXUSClient } from '@trustscan/sdk';

const client = new NEXXUSClient({
  apiKey: process.env.TRUSTSCAN_API_KEY!
});

export async function POST(request: NextRequest) {
  const { content, context } = await request.json();

  try {
    const result = await client.evaluate({
      content,
      context,
      mode: 'STANDARD'
    });

    return NextResponse.json(result);
  } catch (error) {
    console.error('Evaluation failed:', error);
    return NextResponse.json(
      { error: 'Evaluation failed' },
      { status: 500 }
    );
  }
}

TypeScript Types

The SDK includes comprehensive TypeScript definitions:

import {
  NEXXUSClient,
  NEXXUSConfig,
  EvaluationRequest,
  EvaluationResponse,
  EvaluationMode,
  Verdict,
  CertificationTier,
  Issue,
  EvaluatorResult,
  AISystem,
  SystemFilters,
} from '@trustscan/sdk';

// All types are exported for your use
const config: NEXXUSConfig = {
  apiKey: 'ts_live_xxx',
  timeout: 30000
};

const request: EvaluationRequest = {
  content: 'Text to evaluate',
  mode: 'STANDARD' as EvaluationMode
};

// Response types are fully typed
function processResult(result: EvaluationResponse): void {
  const verdict: Verdict = result.verdict;
  const tier: CertificationTier = result.certificationTier;

  result.evaluatorResults.forEach((evaluator: EvaluatorResult) => {
    evaluator.issues.forEach((issue: Issue) => {
      console.log(`${issue.severity}: ${issue.message}`);
    });
  });
}

Browser Usage

The SDK works in modern browsers with the Fetch API:

Security Note: Never expose your API key in client-side code. Use a backend proxy or serverless function to handle API calls.

Via Backend Proxytypescript
// Frontend code - calls your backend
async function evaluateContent(content: string) {
  const response = await fetch('/api/trustscan/evaluate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ content })
  });

  return response.json();
}

// Backend (Next.js, Express, etc.) - uses SDK
import { NEXXUSClient } from '@trustscan/sdk';

const client = new NEXXUSClient({
  apiKey: process.env.TRUSTSCAN_API_KEY! // Server-side only
});

More Resources