Widget API Reference

Core Package

createConfig(options)

Creates a configuration instance for the chat widget.

import { createConfig } from '@opencx/widget';

const config = createConfig({
  // Required
  token: string;                // Bot authentication token
  
  // Optional
  apiUrl?: string;             // Custom API endpoint
  headers?: Record<string, string>;     // Custom request headers
  queryParams?: Record<string, string>; // URL query parameters
  pathParams?: Record<string, string>;  // URL path parameters
  collectUserData?: boolean;   // Show user data form
  debug?: boolean;             // Enable debug mode
  language?: string;           // Interface language (default: "en")
  contactToken?: string;       // Contact authentication token
  
  // User Configuration
  user?: {
    external_id?: string;     // External user ID
    name?: string;            // User's name
    email?: string;           // User's email
    phone?: string;           // User's phone
    customData?: Record<string, string>; // Additional user data
    avatarUrl?: string;       // User's avatar URL
  };

  // Bot Configuration
  bot?: {
    name?: string;           // Bot's display name
    avatarUrl?: string;      // Bot's avatar URL
    id?: number | null;      // Bot's ID
    is_ai?: boolean;         // Whether bot is AI-powered
  };

  // Theme Customization
  theme?: {
    primaryColor?: string;   // Primary theme color
    triggerOffset?: string;  // Distance from edges
  };

  // Behavior Settings
  settings?: {
    persistSession?: boolean;    // Keep chat history
    useSoundEffects?: boolean;   // Enable sound effects
  };

  // Sound Effects
  soundEffectFiles?: {
    messageArrived?: string;     // Sound for new messages
  };
});

createChat(options)

Creates a chat instance with state management and message handling.

import { createChat } from '@opencx/widget';

const chat = createChat({
  api: ApiCaller;        // API instance
  config: ConfigInstance; // Configuration instance
  platform: Platform;    // Platform-specific implementations
  onSessionDestroy?: () => void; // Session destroy callback
});

Chat State Interface

interface ChatState {
  messages: MessageType[];   // Array of chat messages
  keyboard: { options: string[] } | null; // Quick reply options
  loading: {
    isLoading: boolean;
    reason?: 'sending_message_to_bot' | 'sending_message_to_agent' 
      | 'creating_session' | 'polling' | null;
  };
  error: {
    hasError: boolean;
    message?: string;
    code?: 'SESSION_CREATION_FAILED' | 'SESSION_CLEAR_FAILED' 
      | 'MESSAGE_SEND_FAILED' | 'NO_ACTIVE_SESSION';
  };
}

ApiCaller

Handles API communication with the backend.

import { ApiCaller } from '@opencx/widget';

const api = new ApiCaller({
  config: NormalizedConfig;  // Normalized configuration
});

// Available methods
await api.me();                    // Get current user info
await api.widgetPrelude();         // Fetch initial widget data
await api.handleMessage(message);  // Send a message
await api.createSession();         // Create new chat session
await api.getSession(sessionId);   // Get session by ID
await api.getSessionHistory(sessionId, lastMessageTimestamp?); // Get message history

React Package

WidgetRoot

Root component that provides chat context.

import { WidgetRoot } from '@opencx/widget/react';

<WidgetRoot
  options={CoreOptions}     // Core configuration options
  children={ReactNode}      // Child components
/>

Hooks

useChat()

Access chat state and actions.

const {
  messages,              // Current messages array
  sendMessage,          // Function to send message
  loading: {
    isLoading,
    reason              // Loading state reason
  },
  error: {
    hasError,
    message,
    code                // Error details
  }
} = useChat();

useConfigData()

Access configuration data.

const {
  config,               // Current configuration
  updateConfig         // Function to update config
} = useConfigData();

Error Handling

The widget includes built-in error classes for different scenarios:

// Base error class
class OpenCXError extends Error {}

// Specific error types
class ConnectionError extends OpenCXError {}
class AuthenticationError extends OpenCXError {}
class SessionError extends OpenCXError {}
class SessionNotDefinedError extends SessionError {}
class TransportError extends OpenCXError {}
class FileUploadError extends OpenCXError {}

Platform Interface

When implementing custom platform support:

interface Platform {
  env: {
    platform: 'web' | 'mobile' | string;
  };
  storage?: {
    getItem: (key: string) => Promise<string | null>;
    setItem: (key: string, value: string) => Promise<void>;
    removeItem: (key: string) => Promise<void>;
  };
  logger?: {
    level: string;
    prefix: string;
    enabled: boolean;
  };
}