## @vonage/client-sdk - v0.0.0

# Vonage Client SDK

The Client SDK is intended to provide a ready solution for developers to build Programmable Conversation applications across multiple Channels including: Messages, Voice, SIP, websockets, and App.

## Installation

The SDK can be installed using the npm install command

    npm i @vonage/client-sdk

## SDK setup

### With bundler (Webpack, Vite, etc.) and React

    import {
      VonageClient,
      ClientConfig,
      ConfigRegion,
      LoggingLevel
    } from '@vonage/client-sdk';
    import { useState, useEffect } from 'react';

    function App() {
      const [config] = useState(() => new ClientConfig(ConfigRegion.AP));
      const [client] = useState(() => {
        // Initialize client with optional config (default: ERROR logging, US region).
        const client = new VonageClient({
          loggingLevel: LoggingLevel.DEBUG,
          region: ConfigRegion.EU
        });
        // Or update some options after initialization.
        client.setConfig(config);
        return client;
      });
      const [session, setSession] = useState();
      const [user, setUser] = useState();
      const [error, setError] = useState();

      // Create Session as soon as client is available
      useEffect(() => {
        if (!client) return;
        client
          .createSession('my-token')
          .then((session) => setSession(session))
          .catch((error) => setError(error));
      }, [client]);

      // Get User as soon as a session is available
      useEffect(() => {
        if (!client || !session) return;
        client
          .getUser('me')
          .then((user) => setUser(user))
          .catch((error) => setError(error));
      }, [client, session]);

      if (error) return <pre>{JSON.stringify(error)}</pre>;

      if (!session || !user) return <div>Loading...</div>;

      return <div>User {user.displayName || user.name} logged in</div>;
    }

    export default App;

### With script tag (UMD)

    <!-- <script src="./node_modules/@vonage/client-sdk/dist/vonageClientSDK.js"></script> -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/@vonage/client-sdk/dist/vonageClientSDK.min.js"></script> -->
    <script src="./node_modules/@vonage/client-sdk/dist/vonageClientSDK.min.js"></script>
    <script>
      const token = 'my-token';
      // Initialize client with optional config (default: ERROR logging, US region).
      const client = new vonageClientSDK.VoiceClient({
        loggingLevel: LoggingLevel.DEBUG,
        region: ConfigRegion.EU
      });
      // Or update some options after initialization.
      client.setConfig({
        region: ConfigRegion.AP
      });

      client.createSession(token).then((Session) => {});
    </script>

### With CDN (ES)

    import {
      VonageClient,
      ConfigRegion,
      LoggingLevel
    } from 'https://cdn.jsdelivr.net/npm/@vonage/client-sdk/dist/vonageClientSDK.esm.min.js';

    // Initialize client with optional config (default: ERROR logging, US region).
    const client = new VonageClient({
      loggingLevel: LoggingLevel.DEBUG,
      region: ConfigRegion.EU
    });

    // Or update some options after initialization.
    client.setConfig({
      region: ConfigRegion.AP
    });

    (async () => {
      const token = 'my-token';
      try {
        // Create Session
        const sessionId = await client.createSession(token);
        // Get User
        const user = await client.getUser('me');
        console.log(
          `User ${
            user.displayName || user.name
          } logged in with session ID: ${sessionId}`
        );
      } catch (error) {
        // Log errors for either createSession or getUser
        console.error(error);
      }
    })();

## Example Usage

Below are several typical scenarios where the SDK is commonly utilized.

### Make an Outbound Call

    const context = {
      callee: 'user1'
    };

    const callId = await client.serverCall(context);

### Answer/Reject an Inbound Call

    client.on('callInvite', async (callId, from, channelType) => {
      console.log(`Received call invite from ${from} on ${channelType}`);

      // Accept the call
      await client.answer(callId);

      // Reject the call
      await client.reject(callId);
    });

    client.on('callInviteCancel', (callId, reason) => {
      if (reason === CancelReason.AnsweredElsewhere) {
        console.log(`Call ${callId} was answered elsewhere`);
      } else if (reason === CancelReason.RejectedElsewhere) {
        console.log(`Call ${callId} was rejected elsewhere`);
      } else if (reason === CancelReason.RemoteCancel) {
        console.log(`Call ${callId} was cancelled by the caller`);
      } else if (reason === CancelReason.RemoteTimeout) {
        console.log(`Call ${callId} timed out`);
      }
    });

### Hang-up and Collect Stats

    client.on('callHangup', (callId, callQuality, reason) => {
      if (reason.name == 'LOCAL_HANGUP') {
        console.log(`Call ${callId} was hung up locally`);
      } else if (reason.name == 'REMOTE_HANGUP') {
        console.log(`Call ${callId} was hung up remotely`);
      } else if (reason.name == 'REMOTE_REJECT') {
        console.log(`Call ${callId} was rejected remotely`);
      } else if (reason.name == 'REMOTE_NO_ANSWER_TIMEOUT') {
        console.log(`Call ${callId} timed out`);
      } else if (reason.name == 'MEDIA_TIMEOUT') {
        console.log(`Call ${callId} timed out`);
      } else {
        exhaustiveCheck(reason.name);
      }
    });

### Get Conversations

    const { conversations, nextCursor, previousCursor } =
      await client.getConversations({
        order: PresentingOrder.DESC,
        pageSize: 10,
        cursor: undefined,
        includeCustomData: true,
        orderBy: OrderBy.CUSTOM_SORT_KEY
      });

### Send Text Messages

    const timestamp = await client.sendMessageTextEvent(
      'CONVERSATION_ID',
      'Hello World!'
    );

### Listen for Conversation Events

    const eventHandler = (event: ConversationEvent) => {
      if (event.kind == 'member:invited') {
        console.log(`Member invited: ${event.body.memberId}`);
      } else if (event.kind == 'member:joined') {
        console.log(`Member joined: ${event.body.memberId}`);
      } else if (event.kind == 'member:left') {
        console.log(`Member left: ${event.body.memberId}`);
      } else if (event.kind == 'ephemeral') {
        console.log(`Ephemeral event: ${event.body}`);
      } else if (event.kind == 'custom') {
        console.log(`Custom event: ${event.body}`);
      } else if (event.kind == 'message:text') {
        console.log(`Text message: ${event.body.text}`);
      } else if (event.kind == 'message:custom') {
        console.log(`Custom message: ${event.body.customData}`);
      } else if (event.kind == 'message:image') {
        console.log(`Image message: ${event.body.imageUrl}`);
      } else if (event.kind == 'message:video') {
        console.log(`Video message: ${event.body.videoUrl}`);
      } else if (event.kind == 'message:audio') {
        console.log(`Audio message: ${event.body.audioUrl}`);
      } else if (event.kind == 'message:file') {
        console.log(`File message: ${event.body.fileUrl}`);
      } else if (event.kind == 'message:vcard') {
        console.log(`Vcard message: ${event.body.vcardUrl}`);
      } else if (event.kind == 'message:location') {
        console.log(`Location message: ${event.body.location}`);
      } else if (event.kind == 'message:template') {
        console.log(`Template message: ${event.body.template}`);
      } else if (event.kind == 'event:delete') {
        console.log(`Template message: ${event.body}`);
      } else {
        exhaustiveCheck(event);
      }
    };

    const listener = client.on('conversationEvent', eventHandler);

    client.off('conversationEvent', listener);

## Documentation and examples

Visit Vonage website

## License

Copyright (c) 2023 Vonage, Inc. All rights reserved. Licensed only under the Vonage Client SDK License Agreement (the "License") located at LICENSE.

By downloading or otherwise using our software or services, you acknowledge that you have read, understand and agree to be bound by the Vonage Client SDK License Agreement and Privacy Policy.

You may not use, exercise any rights with respect to or exploit this SDK, or any modifications or derivative works thereof, except in accordance with the License.