JSPM

@verydia/client-sdk

0.0.1
    • ESM via JSPM
    • ES Module Entrypoint
    • Export Map
    • Keywords
    • License
    • Repository URL
    • TypeScript Types
    • README
    • Created
    • Published
    • Downloads 4
    • Score
      100M100P100Q18941F
    • License Apache-2.0

    Official TypeScript SDK for Verydia Cloud API

    Package Exports

    • @verydia/client-sdk

    Readme

    @verydia/client-sdk

    Official TypeScript SDK for Verydia Cloud API

    Part of the Verydia framework โ€” a modern, modular TypeScript framework for building production agentic systems.


    ๐Ÿ“ฆ Installation

    # pnpm
    pnpm add @verydia/client-sdk
    
    # npm
    npm install @verydia/client-sdk
    
    # yarn
    yarn add @verydia/client-sdk

    ๐Ÿš€ Quick Start

    Using Environment Variables

    import { VerydiaClient, isOk } from '@verydia/client-sdk';
    
    // Set environment variables:
    // VERYDIA_API_KEY=your-api-key
    // VERYDIA_PROJECT_ID=your-project-id
    
    const client = new VerydiaClient();
    
    const result = await client.runWorkflow({
      workflowId: 'my-chatbot',
      input: { message: 'Hello!' },
    });
    
    if (isOk(result)) {
      console.log('Success:', result.value.output);
    } else {
      console.error('Error:', result.error.message);
    }

    Using Explicit Configuration

    import { VerydiaClient } from '@verydia/client-sdk';
    
    const client = new VerydiaClient({
      apiKey: 'your-api-key',
      projectId: 'your-project-id',
      baseUrl: 'https://api.verydia.dev', // optional
    });
    
    const result = await client.runWorkflow({
      workflowId: 'my-workflow',
      input: { userId: '123', action: 'process' },
      metadata: { source: 'web-app' },
    });

    ๐Ÿ“š API Reference

    VerydiaClient

    The main client class for interacting with the Verydia API.

    Constructor

    new VerydiaClient(options?: VerydiaClientOptions)

    Options:

    • apiKey?: string - API key (or use VERYDIA_API_KEY env var)
    • projectId?: string - Project ID (or use VERYDIA_PROJECT_ID env var)
    • baseUrl?: string - API base URL (default: https://api.verydia.dev)
    • env?: "development" | "staging" | "production" - Environment
    • fetch?: typeof fetch - Custom fetch implementation

    Methods

    runWorkflow<TOutput>(options: WorkflowRunOptions)

    Execute a workflow and get results.

    const result = await client.runWorkflow<{ answer: string }>({
      workflowId: 'qa-bot',
      input: { question: 'What is AI?' },
      metadata: { userId: '123' },
    });
    
    if (isOk(result)) {
      console.log(result.value.output?.answer);
    }

    Returns: Promise<Result<WorkflowRunResponse<TOutput>, VerydiaClientError>>

    getWorkflowRun<TOutput>(options: GetWorkflowRunOptions)

    Get the status and details of a workflow run.

    const result = await client.getWorkflowRun<{ answer: string }>({
      runId: 'run-123',
    });
    
    if (isOk(result)) {
      console.log(`Status: ${result.value.status}`);
      console.log(`Created: ${result.value.createdAt}`);
    }

    Returns: Promise<Result<GetWorkflowRunResponse<TOutput>, VerydiaClientError>>

    cancelWorkflowRun(options: CancelWorkflowRunOptions)

    Cancel a running workflow.

    const result = await client.cancelWorkflowRun({
      runId: 'run-123',
    });
    
    if (isOk(result)) {
      console.log('Workflow cancelled successfully');
    }

    Returns: Promise<Result<void, VerydiaClientError>>

    listWorkflows(query?: ListWorkflowsQuery)

    List available workflows.

    const result = await client.listWorkflows({
      limit: 10,
      offset: 0,
      name: 'my-workflow',
    });
    
    if (isOk(result)) {
      console.log(`Found ${result.value.total} workflows`);
      result.value.workflows.forEach(wf => {
        console.log(`- ${wf.name}: ${wf.description}`);
      });
    }

    Returns: Promise<Result<ListWorkflowsResponse, VerydiaClientError>>

    listTraces(query?: TracesQuery)

    Query workflow execution traces.

    const result = await client.listTraces({
      workflowId: 'my-workflow',
      status: 'success',
      limit: 10,
      offset: 0,
    });
    
    if (isOk(result)) {
      console.log(`Found ${result.value.total} traces`);
      result.value.traces.forEach(trace => {
        console.log(`- ${trace.id}: ${trace.status}`);
      });
    }

    Returns: Promise<Result<TracesResponse, VerydiaClientError>>

    getConfig()

    Get the resolved client configuration.

    const config = client.getConfig();
    console.log('Base URL:', config.baseUrl);

    ๐ŸŽฏ Error Handling

    The SDK uses a Result type pattern for type-safe error handling without exceptions.

    Using Result Helpers

    import { VerydiaClient, isOk, isErr } from '@verydia/client-sdk';
    
    const client = new VerydiaClient();
    const result = await client.runWorkflow({
      workflowId: 'my-workflow',
      input: {},
    });
    
    // Type-safe error checking
    if (isOk(result)) {
      // result.value is WorkflowRunResponse
      console.log('Success:', result.value);
    } else {
      // result.error is VerydiaClientError
      console.error('Error:', result.error.message);
      
      // Check specific error types
      if (result.error.name === 'VerydiaAuthError') {
        console.error('Authentication failed');
      }
    }

    Error Classes

    • VerydiaClientError - Base error class
    • VerydiaAuthError - Authentication failures (401/403)
    • VerydiaHttpError - HTTP request failures with status codes
    • VerydiaConfigError - Configuration validation errors

    All errors include a context object with additional debugging information.


    โš™๏ธ Configuration

    Environment Variables

    The SDK automatically reads configuration from environment variables:

    • VERYDIA_API_KEY - Your API key
    • VERYDIA_PROJECT_ID - Your project ID
    • VERYDIA_ENV - Environment (development, staging, production)

    Base URL Override

    Override the API endpoint for staging or local development:

    // Staging
    const client = new VerydiaClient({
      baseUrl: 'https://staging.verydia.dev',
      apiKey: 'staging-key',
    });
    
    // Local development
    const client = new VerydiaClient({
      baseUrl: 'http://localhost:3000',
      apiKey: 'dev-key',
    });

    Retry & Backoff

    The SDK automatically retries transient errors with exponential backoff:

    const client = new VerydiaClient({
      maxRetries: 3,        // default: 2
      retryDelayMs: 500,    // base delay in ms, default: 250
      retryJitter: true,    // add random jitter, default: true
    });

    Retried errors:

    • Network failures (fetch errors, timeouts)
    • HTTP 429 (rate limit)
    • HTTP 502, 503, 504 (server errors)

    NOT retried:

    • HTTP 401, 403 (authentication/authorization)
    • HTTP 4xx client errors (except 429)
    • Configuration errors

    Backoff strategy:

    • Delay = retryDelayMs * 2^attempt
    • Jitter adds ยฑ25% randomness to prevent thundering herd
    • Retry count included in error context when exhausted

    Request/Response Hooks

    Monitor or log all API calls with interceptors:

    const client = new VerydiaClient({
      onRequest: async (ctx) => {
        console.log(`โ†’ ${ctx.method} ${ctx.url}`);
        console.log('Headers:', ctx.headers);
        console.log('Body:', ctx.body);
      },
      onResponse: async (ctx) => {
        console.log(`โ† ${ctx.status} (${ctx.durationMs}ms)`);
      },
    });

    Use cases:

    • Logging and debugging
    • Performance monitoring
    • Integration with telemetry systems (e.g., OpenTelemetry)
    • Request/response transformation

    Error handling:

    • Interceptor errors are caught and logged to console.warn
    • Interceptor failures do NOT break the main request
    • Both sync and async interceptors are supported

    ๐Ÿงช Testing & Mocking

    The SDK is designed to be easily testable with mocked fetch:

    import { VerydiaClient } from '@verydia/client-sdk';
    import { vi } from 'vitest';
    
    const mockFetch = vi.fn().mockResolvedValue({
      ok: true,
      status: 200,
      headers: new Headers({ 'content-type': 'application/json' }),
      json: async () => ({
        id: 'run-123',
        status: 'success',
        output: { result: 'mocked' },
      }),
    });
    
    const client = new VerydiaClient({
      apiKey: 'test-key',
      fetch: mockFetch as unknown as typeof fetch,
    });
    
    const result = await client.runWorkflow({
      workflowId: 'test',
      input: {},
    });
    
    // Assert on mockFetch calls
    expect(mockFetch).toHaveBeenCalledWith(
      expect.stringContaining('/v1/workflows/test/run'),
      expect.objectContaining({ method: 'POST' })
    );

    ๐Ÿ“– Types

    WorkflowRunOptions

    interface WorkflowRunOptions {
      workflowId: string;
      input: unknown;
      metadata?: Record<string, unknown>;
    }

    WorkflowRunResponse

    interface WorkflowRunResponse<T = unknown> {
      id: string;
      status: "success" | "error";
      output?: T;
      error?: unknown;
      traceId?: string;
    }

    TracesQuery

    interface TracesQuery {
      workflowId?: string;
      status?: "success" | "error";
      limit?: number;
      offset?: number;
      startDate?: string; // ISO 8601
      endDate?: string;   // ISO 8601
    }


    ๐Ÿค Contributing

    Contributions are welcome! Please read our Contributing Guide.


    ๐Ÿ“„ License

    Apache-2.0


    ๐Ÿ†˜ Support


    Built with โค๏ธ for developers who value simplicity, type safety, and production readiness.

    Website โ€ข GitHub โ€ข npm