Element API

@avaya/infinity-elements-api v1.2.0


ElementAPI

ElementAPI - Main API for web components to interact with the Infinity Extensibility Framework

This is the primary interface that elements use to communicate with core-agent-ui.
Uses window.postMessage for API requests/responses and events.

Sandboxed Iframe Environment

IMPORTANT: Elements run in sandboxed iframes using srcdoc, which means:

  • window.location.origin returns "null" (the literal string "null")
  • document.referrer may be empty
  • Direct access to parent window properties is blocked
  • BroadcastChannel doesn't work (requires valid origin for message scoping)

All communication with the host (core-agent-ui) must go through window.postMessage.
The host has a valid origin and can make HTTP requests, handle OAuth, etc.

The methods are organized into four API families:

  • Interaction API Family - Controls and monitors customer interactions throughout their lifecycle. Initiate new voice and chat interactions, execute controls (transfer, consult, conference), and subscribe to interaction events.
  • Media API Family - Manages channel-specific capabilities including DTMF tones on voice channels and rich text messages with formatting and attachments.
  • Agent API Family - Manages agent presence and availability. Modify agent state and subscribe to state change notifications.
  • Admin API Family - Provides environmental and configuration data including logged-in agent context, users, queues, and reason codes.

Examples

import { ElementAPI } from '@avaya/infinity-elements-api';

const api = new ElementAPI({
  elementId: 'my-element',
  timeout: 5000,
  debug: true
});
const userInfo = await api.getUserInfo();
console.log('Agent name:', userInfo.firstName, userInfo.lastName);
console.log('Email:', userInfo.email);
api.onInteractionAccepted((interactionId) => {
  console.log('Interaction accepted:', interactionId);
});

api.onInteractionEnded((interactionId) => {
  console.log('Interaction ended:', interactionId);
});

Constructors

Constructor

new ElementAPI(options?: ElementAPIOptions): ElementAPI;

Creates a new ElementAPI instance

Parameters

ParameterType
optionsElementAPIOptions

Returns

ElementAPI

Example

const api = new ElementAPI({
  elementId: 'my-custom-element',
  timeout: 10000,
  debug: true
});

Interaction API Family

getInteraction()

getInteraction(options?: InteractionContextOptions): Promise<InteractionInfo>;

Get information about the current active interaction

Parameters

ParameterTypeDescription
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<InteractionInfo>

Promise resolving to the interaction information

Throws

Error if no active interaction exists

Examples

// Interaction-level widget (no interactionId needed)
try {
  const interaction = await api.getInteraction();
  console.log('Interaction ID:', interaction.interactionId);
  console.log('Customer:', interaction.customer?.name);
  console.log('Status:', interaction.status);
} catch (error) {
  console.error('No active interaction');
}
// App-level widget (interactionId required)
const interaction = await api.getInteraction({ interactionId: 'int-123' });
console.log('Status:', interaction.status);

getUserInteractions()

getUserInteractions(params?: GetUserInteractionsParams): Promise<GetUserInteractionsResponse>;

Get user interactions including owned and viewing interactions

Retrieves all active interactions for the current or specified user,
including interactions they own and ones they are viewing.
Optionally includes queue and user details.

Parameters

ParameterTypeDescription
params?GetUserInteractionsParamsOptional parameters
params.userId?stringUser ID to get interactions for (defaults to current user)
params.details?booleanInclude queue and user details (defaults to true)

Returns

Promise<GetUserInteractionsResponse>

Promise resolving to user interactions data

Examples

// Get current user's interactions with full details
const result = await api.getUserInteractions({ details: true });
console.log('Owned interactions:', result.interactions);
console.log('Viewing interactions:', result.viewing);
console.log('Logged in queues:', result.queue.loggedIn);
// Get interactions without queue/user details for better performance
const result = await api.getUserInteractions({ details: false });
const totalCount = result.interactions.length + result.viewing.length;
console.log('Total active interactions:', totalCount);

viewerRemoveInteraction()

viewerRemoveInteraction(options?: InteractionContextOptions): Promise<{ message: string }>;

Remove the current interaction from the viewer

Parameters

ParameterTypeDescription
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget
await api.viewerRemoveInteraction();
// App-level widget
await api.viewerRemoveInteraction({ interactionId: 'int-123' });

endInteraction()

endInteraction(options?: InteractionContextOptions): Promise<{ message: string }>;

End the current interaction

Terminates the active interaction and disconnects the call.

Parameters

ParameterTypeDescription
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget
await api.endInteraction();
console.log('Interaction ended');
// App-level widget
await api.endInteraction({ interactionId: 'int-123' });

startVoiceCall()

startVoiceCall(options?: InteractionContextOptions): Promise<{ message: string }>;

Start a voice call for the current interaction

Parameters

ParameterTypeDescription
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget
await api.startVoiceCall();
// App-level widget
await api.startVoiceCall({ interactionId: 'int-123' });

createVoiceInteraction()

createVoiceInteraction(params: CreateVoiceInteractionParams): Promise<{ message: string }>;

Create a new voice interaction with a Queue ID and Phone Number

Creates a new outbound voice call interaction to the specified phone number
and assigns it to the specified queue.

Parameters

ParameterTypeDescription
paramsCreateVoiceInteractionParamsVoice interaction parameters

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Example

await api.createVoiceInteraction({
  phoneNumber: '+1234567890',
  queueId: '003'
});

completeBlindTransfer()

completeBlindTransfer(options: BlindTransferOptions): Promise<boolean>;

Complete a blind transfer

Transfers the call to another agent or number without consultation.

Parameters

ParameterTypeDescription
optionsBlindTransferOptionsTransfer configuration

Returns

Promise<boolean>

Promise resolving to true if successful

Example

const interaction = await api.getInteraction();
await api.completeBlindTransfer({
  interactionId: interaction.interactionId,
  transferTo: '[email protected]',
  transferToName: 'John Doe',
  transferCallerIdType: 'internal'
});

singleStepTransfer()

singleStepTransfer(params: SingleStepTransferParams): Promise<{ message: string }>;

Perform a single-step transfer

Transfers the interaction directly to the specified target.

Parameters

ParameterTypeDescription
paramsSingleStepTransferParamsTransfer parameters

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget (no interactionId needed)
await api.singleStepTransfer({
  targetId: 'user123',
  targetName: 'Support Team'
});
// App-level widget (interactionId required)
await api.singleStepTransfer({
  targetId: 'queue-456',
  targetName: 'Sales Queue',
  interactionId: 'int-123'
});

consultCall()

consultCall(options: ConsultCallOptions): Promise<{ message: string }>;

Initiate a consult call

Starts a consultation with another agent, phone number, or queue while keeping
the original caller on hold.

Parameters

ParameterTypeDescription
optionsConsultCallOptionsConsult call configuration

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Consult with agent
const interaction = await api.getInteraction();
await api.consultCall({
  interactionId: interaction.interactionId,
  transferTo: '[email protected]'
});
// Consult with phone number
await api.consultCall({
  interactionId: interaction.interactionId,
  phoneNumber: '+1234567890'
});
// Consult with queue
const queues = await api.getTransferQueuesInteraction();
const targetQueue = queues.find(q => q.name === 'Support Queue');

await api.consultCall({
  interactionId: interaction.interactionId,
  queueId: targetQueue.id
});

completeAttendedTransfer()

completeAttendedTransfer(options?: InteractionContextOptions): Promise<{ message: string }>;

Complete an attended transfer

Finalizes the attended transfer after consulting with the target party.

Parameters

ParameterTypeDescription
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget
await api.completeAttendedTransfer();
// App-level widget
await api.completeAttendedTransfer({ interactionId: 'int-123' });

completeConference()

completeConference(options?: InteractionContextOptions): Promise<{ message: string }>;

Complete the interaction as a conference

Merges all parties into a conference call instead of completing a transfer.

Parameters

ParameterTypeDescription
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget — after consulting
await api.completeConference();
// App-level widget
await api.completeConference({ interactionId: 'int-123' });

attendedTransferWarm()

attendedTransferWarm(options?: InteractionContextOptions): Promise<{ message: string }>;

Perform a warm attended transfer

Introduces the caller to the transfer target before completing the transfer.

Parameters

ParameterTypeDescription
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget
await api.attendedTransferWarm();
// App-level widget
await api.attendedTransferWarm({ interactionId: 'int-123' });

attendedTransferCancel()

attendedTransferCancel(options?: InteractionContextOptions): Promise<{ message: string }>;

Cancel an attended transfer

Cancels the ongoing attended transfer and returns to the original call.

Parameters

ParameterTypeDescription
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget
await api.attendedTransferCancel();
// App-level widget
await api.attendedTransferCancel({ interactionId: 'int-123' });

acceptInteraction()

acceptInteraction(options?: InteractionContextOptions): Promise<{ message: string }>;

Accept an incoming interaction

Accepts a queued or alerting interaction.

Parameters

ParameterTypeDescription
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget
api.onInteractionAccepted(async (interactionId) => {
  console.log('New interaction:', interactionId);
});

await api.acceptInteraction();
// App-level widget
await api.acceptInteraction({ interactionId: 'int-123' });

onInteractionStatusChanged()

onInteractionStatusChanged(callback: InteractionStatusChangedCallback): () => void;

Subscribe to interaction status changes

Fires when the status of an interaction changes (e.g., alerting, connected, held)

Parameters

ParameterTypeDescription
callbackInteractionStatusChangedCallbackFunction to call when interaction status changes

Returns

Unsubscribe function () => void

Example

const unsubscribe = api.onInteractionStatusChanged(({ interactionId, status }) => {
  console.log(`Interaction ${interactionId} status changed to ${status}`);
});

// Later, to unsubscribe:
unsubscribe();

onInteractionAccepted()

onInteractionAccepted(callback: InteractionAcceptedCallback): () => void;

Subscribe to interaction accepted events

Fires when an agent accepts an incoming interaction

Parameters

ParameterTypeDescription
callbackInteractionAcceptedCallbackFunction to call when an interaction is accepted

Returns

Unsubscribe function () => void

Example

api.onInteractionAccepted((interactionId) => {
  console.log('Accepted interaction:', interactionId);
  // Load customer data, show interaction UI, etc.
});

onInteractionEnded()

onInteractionEnded(callback: InteractionEndedCallback): () => void;

Subscribe to interaction ended events

Fires when an interaction is ended or disconnected

Parameters

ParameterTypeDescription
callbackInteractionEndedCallbackFunction to call when an interaction ends

Returns

Unsubscribe function () => void

Example

api.onInteractionEnded((interactionId) => {
  console.log('Interaction ended:', interactionId);
  // Clean up UI, save data, etc.
});

onInteractionUpdated()

onInteractionUpdated(callback: InteractionUpdatedCallback): () => void;

Subscribe to interaction updated events

Fires when an interaction is updated with new information

Parameters

ParameterTypeDescription
callbackInteractionUpdatedCallbackFunction to call when an interaction is updated

Returns

Unsubscribe function () => void

Example

api.onInteractionUpdated(({ interactionId, payload }) => {
  console.log('Interaction updated:', interactionId);
  console.log('New data:', payload);
});

onConsultStatusChanged()

onConsultStatusChanged(callback: ConsultStatusChangedCallback): () => void;

Subscribe to consult status changes

Fires when the status of a consultation changes

Parameters

ParameterTypeDescription
callbackConsultStatusChangedCallbackFunction to call when consult status changes

Returns

Unsubscribe function () => void

Example

api.onConsultStatusChanged(({ interactionId, consultStatus, consultParty }) => {
  console.log(`Consult ${consultStatus} with ${consultParty}`);
});

onCompleteAsConference()

onCompleteAsConference(callback: CompleteAsConferenceCallback): () => void;

Subscribe to complete as conference events

Fires when an interaction is completed as a conference

Parameters

ParameterTypeDescription
callbackCompleteAsConferenceCallbackFunction to call when an interaction is completed as a conference

Returns

Unsubscribe function () => void

Example

api.onCompleteAsConference(({ interactionId }) => {
  console.log(`Interaction ${interactionId} completed as conference`);
});

Media API Family

sendDialpadDigit()

sendDialpadDigit(
  digit: DialpadDigit,
  audioOutputDeviceId: string | null,
  noSendDialTone: boolean,
  audioContextOverride?: "standard" | "webkit" | "none",
  options?: InteractionContextOptions
): Promise<{ message: string }>;

Send a DTMF dialpad digit during a call

Parameters

ParameterTypeDescription
digitDialpadDigitThe dialpad digit to send (0-9)
audioOutputDeviceIdstring | nullAudio output device ID or null for default
noSendDialTonebooleanWhether to suppress the dial tone sound
audioContextOverride?"standard" | "webkit" | "none"Audio context type override
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget
import { DialpadDigit } from '@avaya/infinity-elements-api';

await api.sendDialpadDigit(
  DialpadDigit.One,
  null,
  false
);
// App-level widget
await api.sendDialpadDigit(
  DialpadDigit.One,
  null,
  false,
  undefined,
  { interactionId: 'int-123' }
);

insertTextIntoFeedInput()

insertTextIntoFeedInput(
  text: string,
  options?: InteractionContextOptions
): Promise<{ message: string }>;

Insert text into the chat feed input field

Parameters

ParameterTypeDescription
textstringThe text to insert
options?InteractionContextOptionsOptional parameters
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Interaction-level widget
await api.insertTextIntoFeedInput('Hello, how can I help you today?');
// App-level widget
await api.insertTextIntoFeedInput('Hello!', { interactionId: 'int-123' });

sendRichMediaMessage()

sendRichMediaMessage(options: SendRichMediaMessageOptions): Promise<{ message: string }>;

Send a rich media message (image, file, etc.) to the interaction

@deprecated This method is deprecated and will be removed in a future version. Use sendChatMessage() instead.

Parameters

ParameterTypeDescription
optionsSendRichMediaMessageOptionsMessage options (must provide either mediaUrl or file)
options.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Send image from URL (interaction-level widget)
await api.sendRichMediaMessage({
  name: 'Product Image',
  mediaUrl: 'https://example.com/image.jpg',
  text: 'Here is the product you requested'
});
// Send file upload (app-level widget)
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

await api.sendRichMediaMessage({
  name: 'Document',
  file: file,
  text: 'Attached document',
  interactionId: 'int-123'
});

sendChatMessage()

sendChatMessage(options: SendChatMessageOptions): Promise<{ message: string }>;

Send a chat message to the interaction

Supports sending text messages, media from URLs, or file uploads.
At least one of text, mediaUrl, or file must be provided.

Parameters

ParameterTypeDescription
optionsSendChatMessageOptionsMessage options (must provide interactionId and at least one of text, mediaUrl, or file)
options.interactionIdstringRequired interaction ID

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Send text message
await api.sendChatMessage({
  interactionId: 'int-123',
  text: 'Hello, how can I help you today?'
});
// Send image from URL
await api.sendChatMessage({
  interactionId: 'int-123',
  mediaUrl: 'https://example.com/image.jpg',
  text: 'Here is the product you requested'
});
// Send file upload
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

await api.sendChatMessage({
  interactionId: 'int-123',
  file: file,
  text: 'Attached document'
});
// Send text with file
await api.sendChatMessage({
  interactionId: 'int-123',
  text: 'Please review this document',
  file: documentFile,
  fileName: 'Important Document.pdf'
});

onReceivedFeedMessage()

onReceivedFeedMessage(callback: FeedMessageCallback): () => void;

Subscribe to feed messages

Fires when a new message is received in the interaction feed

Parameters

ParameterTypeDescription
callbackFeedMessageCallbackFunction to call when a feed message is received. Receives (message: Message, interactionId?: string)

Returns

Unsubscribe function () => void

Example

api.onReceivedFeedMessage((message, interactionId) => {
  // Helper function to extract text from a message
  function getMessageText(msg: Message): string {
    if (typeof msg.message === 'string') {
      return msg.message;
    }
    // Handle rich content array
    if (Array.isArray(msg.message)) {
      return msg.message
        .map(part => {
          if (part.type === 'text') return part.text;
          if (part.type === 'email' && part.email) return part.email.plainText;
          return '';
        })
        .join(' ')
        .trim();
    }
    return '';
  }

  const text = getMessageText(message);
  console.log('New message:', text);
  console.log('From:', message.author?.displayName);
  console.log('For interaction:', interactionId);
});

Agent API Family

getUserInfo()

getUserInfo(): Promise<UserInfo>;

Get information about the current logged-in user/agent

Returns

Promise<UserInfo>

Promise resolving to the user information including agent status, queues, and profile

Example

const userInfo = await api.getUserInfo();
console.log('Agent:', userInfo.firstName, userInfo.lastName);
console.log('Queues:', userInfo.queues);
console.log('Email:', userInfo.email);

setAgentStatus()

setAgentStatus(
  userId: string,
  status: AgentStatus,
  reason?: { id: string; name: string }
): Promise<{ message: string }>;

Set the agent's status (Available, Away, Busy, etc.)

Parameters

ParameterTypeDescription
userIdstringThe user ID of the agent
statusAgentStatusThe new agent status
reason?{id: string; name: string}Optional reason for the status change (required for some statuses)
reason.id?string-
reason.name?string-

Returns

Promise<{`message`: `string`}>

Promise resolving to a success message

Examples

// Set agent to Available
const userInfo = await api.getUserInfo();
await api.setAgentStatus(
  userInfo.userId,
  { id: 'available', name: 'Available', category: 'available' }
);
// Set agent to Away with reason
const userInfo = await api.getUserInfo();
await api.setAgentStatus(
  userInfo.userId,
  { id: 'away', name: 'Away', category: 'away' },
  { id: 'lunch', name: 'Lunch Break' }
);

getAvayaJwt()

getAvayaJwt(options?: {
  authorizationEndpoint?: string;
  tokenEndpoint?: string;
  clientId?: string;
  scopes?: string[];
  redirectUri?: string;
  popupOptions?: PopupOptions;
  forceRefresh?: boolean;
}): Promise<string>;

Get Avaya JWT token with multi-level request deduplication and automatic refresh

  • Returns cached token from localStorage if available and not expired
  • Automatically refreshes token if expired (using refresh token)
  • Prevents duplicate concurrent fetch requests (instance-level)
  • Prevents duplicate OAuth popups across iframes/elements (cross-iframe coordination)
  • Initiates Keycloak OAuth flow if no token exists

Cross-iframe coordination ensures that if 10 iframes all call getAvayaJwt(),
only ONE OAuth popup will appear, and all iframes will receive the same token.

Uses localStorage for coordination to ensure only one OAuth popup appears.

GUARANTEE: This function ALWAYS either returns a JWT string or throws an error.
There are no code paths that return undefined or hang indefinitely.

Parameters

ParameterTypeDescription
optionsobjectConfiguration options (all optional, uses defaults if not provided)
options.authorizationEndpoint?stringKeycloak authorization endpoint URL
options.tokenEndpoint?stringKeycloak token endpoint URL
options.clientId?stringOAuth client ID
options.scopes?string[]OAuth scopes to request
options.redirectUri?stringOAuth redirect URI (URL to redirect.html)
options.popupOptions?PopupOptionsPopup window size/position (defaults to 500x600)
options.forceRefresh?booleanForce token refresh even if not expired (defaults to false)

Returns

Promise<string>

The JWT token (never returns undefined, always throws on error)

Example

// Use defaults
const jwt = await api.getAvayaJwt();

// With configuration
const jwt = await api.getAvayaJwt({
  authorizationEndpoint: 'https://keycloak.example.com/auth/realms/xxx/protocol/openid-connect/auth',
  tokenEndpoint: 'https://keycloak.example.com/auth/realms/xxx/protocol/openid-connect/token',
  clientId: 'my-client-id',
  redirectUri: 'https://myapp.com/redirect.html',
  forceRefresh: true
});

refreshToken()

refreshToken(options?: {
  tokenEndpoint?: string;
  clientId?: string;
}): Promise<string>;

Refresh the access token using the stored refresh token

Parameters

ParameterTypeDescription
optionsobjectConfiguration options
options.tokenEndpoint?stringKeycloak token endpoint URL (required)
options.clientId?stringOAuth client ID (required)

Returns

Promise<string>

The new JWT access token

Throws

Error if refresh token is not available or refresh fails

Example

try {
  const newJwt = await api.refreshToken({
    tokenEndpoint: 'https://keycloak.example.com/auth/realms/xxx/protocol/openid-connect/token',
    clientId: 'my-client-id'
  });
  console.log('Token refreshed successfully');
} catch (error) {
  console.error('Token refresh failed:', error);
  // May need to re-authenticate
}

clearAvayaJwt()

clearAvayaJwt(): void;

Clear the cached JWT token and force re-authentication on next getAvayaJwt call

Returns

void

Example

api.clearAvayaJwt();
const newJwt = await api.getAvayaJwt(); // Will trigger OAuth flow

onChangedAgentState()

onChangedAgentState(callback: AgentStateChangedCallback): () => void;

Subscribe to agent state changed events

Fires when the agent's state changes (e.g., Available, Away, Busy)

Parameters

ParameterTypeDescription
callbackAgentStateChangedCallbackFunction to call when agent state changes. Receives {previousState, currentState, reason?}

Returns

Unsubscribe function () => void

Example

api.onChangedAgentState(({ previousState, currentState, reason }) => {
  console.log(`Agent state changed from ${previousState} to ${currentState}`);
  if (reason) console.log(`Reason: ${reason}`);
});

Admin API Family

getUsers()

getUsers(params?: {
  interactionId?: string;
  filter?: string;
}): Promise<GetUsersResponse[]>;

Get a list of users in Infinity

Returns users available for transfer or consult operations. Returns up to 100 users.

  • App Level (sidebar widgets): Provide interactionId parameter
  • Interaction Level (interaction widgets): Omit interactionId, uses interaction context automatically

Parameters

ParameterTypeDescription
params?objectOptional parameters
params.interactionId?stringRequired for app-level widgets, optional for interaction-level widgets
params.filter?stringOptional substring search against user name fields

Returns

Promise<GetUsersResponse[]>

Promise resolving to array of user information

Examples

// Get all users (interaction level - no interactionId needed)
const users = await api.getUsers();
users.forEach(user => {
  console.log(`$USER.FULLNAME - ${user.cxStatus.status} - $USER.PRESENCE`);
});
// Get filtered users by name (interaction level)
const users = await api.getUsers({ filter: 'john' });
console.log('Found users:', users.map(u => u.fullName));
// Get all users (app level - requires interactionId)
const users = await api.getUsers({ interactionId: 'int-123' });
users.forEach(user => {
  console.log(`$USER.FULLNAME - ${user.cxStatus.status} - $USER.PRESENCE`);
});
// Get filtered users (app level)
const users = await api.getUsers({
  interactionId: 'int-123',
  filter: 'john'
});
// Use for transfer target selection
const users = await api.getUsers({ filter: searchInput });
const eligibleUsers = users.filter(u => u.eligible);
eligibleUsers.forEach(user => {
  console.log(`$USER.FULLNAME ($USER.EXTENSION) - ${user.cxStatus.status}`);
});

getUserQueues()

getUserQueues(params?: { filter?: string }): Promise<UserQueueInfo[]>;

Get all queues available to the current user (App Level)

Returns a basic list of queues the agent has access to.

Parameters

ParameterTypeDescription
params?objectOptional filter parameters
params.filter?stringOptional substring search against queue names

Returns

Promise<UserQueueInfo[]>

Promise resolving to array of user queue information

Example

const queues = await api.getUserQueues();
console.log('Available queues:', queues.map(q => q.name));

// With filter
const salesQueues = await api.getUserQueues({ filter: 'Sales' });

getTransferQueues()

getTransferQueues(params: {
  interactionId: string;
  filter?: string;
}): Promise<InteractionQueueInfo[]>;

Get transfer queues with real-time statistics (App Level)

Returns detailed queue information including waiting interactions, active agents,
and average wait times. Requires explicit interactionId since this is used at app level
where interaction context is not available.

Parameters

ParameterTypeDescription
paramsobjectRequired interactionId and optional filter parameters
params.interactionIdstringRequired interaction ID
params.filter?stringOptional substring search against queue names

Returns

Promise<InteractionQueueInfo[]>

Promise resolving to array of queue information with statistics

Example

const queues = await api.getTransferQueues({
  interactionId: 'int-123',
  filter: 'support'
});
queues.forEach(queue => {
  console.log(`${queue.name}: ${queue.waitingInteractions} waiting`);
  console.log(`Active agents: ${queue.countActiveAgents}`);
});

getTransferQueuesInteraction()

getTransferQueuesInteraction(params?: {
  filter?: string;
  interactionId?: string;
}): Promise<InteractionQueueInfo[]>;

Get transfer queues with real-time statistics (Interaction Level)

Returns detailed queue information including waiting interactions, active agents,
and average wait times. Uses interaction context automatically for interaction-level widgets.

Parameters

ParameterTypeDescription
params?objectOptional filter parameters
params.filter?stringOptional substring search against queue names
params.interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

Returns

Promise<InteractionQueueInfo[]>

Promise resolving to array of queue information with statistics

Examples

// Interaction-level widget
const queues = await api.getTransferQueuesInteraction({ filter: 'support' });
queues.forEach(queue => {
  console.log(`${queue.name}: ${queue.waitingInteractions} waiting`);
  console.log(`Active agents: ${queue.countActiveAgents}`);
});
// App-level widget
const queues = await api.getTransferQueuesInteraction({
  filter: 'support',
  interactionId: 'int-123'
});

getReasonCodes()

getReasonCodes(params?: GetReasonCodesParams): Promise<GetReasonCodesResponse>;

Get reason codes for agent status changes

Returns available reason codes that can be used when changing agent status.

Parameters

ParameterTypeDescription
params?GetReasonCodesParamsOptional parameters
params.type?"away" | "busy" | "available" | "queueLogout" | nullFilter by reason type

Returns

Promise<GetReasonCodesResponse>

Promise resolving to reason codes response

Examples

// Get all reason codes
const response = await api.getReasonCodes();
console.log('Reason codes:', response.reasons);
// Get away reason codes only
const response = await api.getReasonCodes({ type: 'away' });
const awayReasons = response.reasons;

Inter-Element Communication

sendInterElementMessage()

sendInterElementMessage<T>(message: T): void;

Send a message to other elements via the host (parent window)

Messages are routed through the host application which acts as a broker,
relaying messages to all other element iframes. This approach works in
sandboxed iframes where BroadcastChannel is not available.

Type Parameters

Type ParameterDescription
TThe type of the message

Parameters

ParameterTypeDescription
messageTThe message to send (can be any serializable type)

Returns

void

Example

api.sendInterElementMessage({ type: 'my-event', payload: { key: 'value' } });

onInterElementMessage()

onInterElementMessage<T>(callback: (message: T) => void): () => void;

Subscribe to messages from other elements routed through the host

The host application receives inter-element messages and relays them to
all element iframes. This works in sandboxed iframes where BroadcastChannel
is not available.

Type Parameters

Type ParameterDescription
TThe expected type of messages

Parameters

ParameterTypeDescription
callback(message: T) => voidFunction called when a message is received

Returns

Unsubscribe function () => void

Example

const unsubscribe = api.onInterElementMessage<MyMessageType>((message) => {
  console.log('Received:', message);
});

// Later, stop listening
unsubscribe();

Events

onError()

onError(callback: ErrorCallback): () => void;

Subscribe to error events

Fires when an error occurs in the API

Parameters

ParameterTypeDescription
callbackErrorCallbackFunction to call when an error occurs

Returns

Unsubscribe function () => void

Example

api.onError((error) => {
  console.error('API Error:', error.code, error.message);
  // Display error notification to user
});

Lifecycle

destroy()

destroy(): void;

Clean up resources when the React component is unmounted or no longer needed

Removes all event listeners, closes channels, and clears pending requests.
Call this method in your React component's cleanup/unmount lifecycle.

Returns

void

Example

// In a React component
useEffect(() => {
  const api = new ElementAPI();
  return () => {
    api.destroy(); // Cleanup on unmount
  };
}, []);

Enumerations

DialpadDigit

DTMF dialpad digits (0-9) for sending tones during calls

Example

import { DialpadDigit } from '@avaya/infinity-elements-api';

await api.sendDialpadDigit(DialpadDigit.Five, null, false);

Functions

setupOAuthCallbackHandler()

function setupOAuthCallbackHandler(): void;

Setup OAuth callback handler - call once at app initialization

Sets up listener for redirect.html config requests

Returns

void


refreshAccessToken()

function refreshAccessToken(
  refreshToken: string,
  tokenEndpoint: string,
  clientId: string
): Promise<TokenResponse>;

Refresh an expired access token using the refresh token

Elements run in sandboxed iframes (about:srcdoc) which have origin "null".
Direct fetch to Keycloak fails due to CORS.

This function delegates the refresh request to the host (agent-ui) via
postMessage. The host has a proper origin and can make the request
without CORS issues. This is completely silent - no popups or visible UI.

Parameters

ParameterTypeDescription
refreshTokenstringThe refresh token to use
tokenEndpointstringThe token endpoint URL
clientIdstringThe OAuth client ID

Returns

Promise<TokenResponse>


getStoredTokenData()

function getStoredTokenData(jwtStorageKey: string): StoredTokenData | null;

Get stored token data from localStorage

Parameters

ParameterType
jwtStorageKeystring

Returns

StoredTokenData | null


isTokenExpired()

function isTokenExpired(tokenData: StoredTokenData): boolean;

Check if a token is expired

Parameters

ParameterType
tokenDataStoredTokenData

Returns

boolean


isRefreshTokenExpired()

function isRefreshTokenExpired(tokenData: StoredTokenData): boolean;

Check if refresh token is expired

Parameters

ParameterType
tokenDataStoredTokenData

Returns

boolean


Interfaces

InteractionInfo

PropertyType
idstring
interactionIdstring
statusstring
commType?string
direction?string
customer?{name?: string; number?: string; id?: string}
startTime?string
duration?number
metadata?Record<string, unknown>

InteractionUpdatePayload

PropertyType
idstring
status?string
commType?string
subCommType?string
isAudio?boolean
isHold?boolean
isMute?boolean
details?{notes?: string; subject?: string}
sourceDetails?{phoneNumber?: string; email?: string; name?: string}

InteractionContextOptions

Common options for interaction-context methods. Used to optionally specify an interaction ID for app-level widgets.

PropertyTypeDescription
interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

BlindTransferOptions

PropertyTypeDescription
interactionIdstring-
transferTostringThe target User ID, Queue ID, or Phone Number
transferToNamestringThe display name of the target
transferCallerIdType?string-

SingleStepTransferParams

PropertyTypeDescription
targetIdstringThe target User ID, Queue ID, or Phone Number
targetNamestringThe display name of the target
interactionId?stringOptional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets)

CreateVoiceInteractionParams

PropertyType
phoneNumberstring
queueIdstring

SendRichMediaMessageOptions

PropertyType
name?string
mediaUrl?string
file?File
text?string
interactionId?string

SendChatMessageOptions

PropertyTypeDescription
interactionIdstringRequired interaction ID
text?stringOptional message text
mediaUrl?stringOptional media URL (image, file, etc.)
file?FileOptional file to upload
fileName?stringOptional file name for the message/file

ConsultCallOptions

PropertyTypeDescription
interactionIdstring-
transferTo?stringUser ID or handle to consult with (internal user/agent)
phoneNumber?stringPhone number to consult with (external number)
queueId?stringQueue ID to consult to. Can be obtained via getTransferQueuesInteraction

AgentStatus

PropertyType
idstring
namestring
categorystring

ReasonCode

PropertyType
idstring
reasonstring
type"away" | "busy" | "available" | "queueLogout"
typeDisplaystring
eliteAuxCode?number
isDisabledboolean
isSystemCode?boolean
createdAtstring
createdBystring
updatedAtstring | null
updatedBystring | null
inWorkflowIdstring | null
inWorkflowVersionIdstring | null
outWorkflowIdstring | null
outWorkflowVersionIdstring | null
queryFieldIdstring | null

GetReasonCodesParams

PropertyType
type?"away" | "busy" | "available" | "queueLogout" | null

GetReasonCodesResponse

PropertyType
reasonsReasonCode[]

GetUserInteractionsParams

PropertyType
userId?string
details?boolean

QueueLoggedIn

PropertyType
queueIdstring
namestring
queueWeightnumber
timeZonestring
extensionnumber | null
createdOnstring
createdOnUnixnumber

QueueAccess

PropertyType
queueIdstring
namestring
queueWeightnumber
timeZonestring
extensionnumber | null

UserInteractionsUser

PropertyType
idstring
firstNamestring
lastNamestring
fullNamestring
titlestring | null
emailstring
extensionstring | null

GetUserInteractionsResponse

PropertyType
interactionsInteraction[]
viewingInteraction[]
combinedIds?string[]
queue{loggedIn: [QueueLoggedIn](#queueloggedin)[]; access: [QueueAccess](#queueaccess)[]}
userUserInteractionsUser

ElementAPIOptions

Configuration options for ElementAPI initialization

PropertyTypeDescription
elementId?stringUnique identifier for this element instance (auto-generated if not provided)
timeout?numberAPI request timeout in milliseconds (default: 5000)
debug?booleanEnable debug logging to console (default: false)
requestTarget?WindowWhen set (e.g. iframe.contentWindow), API sends requests to this window instead of window.parent. Use when ElementAPI runs in the adaptor/bridge and the Agent UI is in an iframe.

InteractionQueueInfo

PropertyType
idstring
namestring
extensionstring | null
waitingInteractionsnumber
countOfCallbacksnumber
countActiveAgentsnumber
totalCurrentInteractionsnumber
connectedInteractionsnumber
avgInteractionWaitTimenumber
weightnumber
eligibleboolean

UserQueueInfo

PropertyType
idstring
namestring

KeycloakConfig

Keycloak OAuth 2.0 PKCE Authentication Module

Supports cross-iframe coordination to prevent multiple OAuth popups.

Uses postMessage-based config exchange with redirect.html:

  1. Component opens popup directly
  2. redirect.html requests config via postMessage
  3. Component responds with config + code verifier
  4. redirect.html performs token exchange
  5. redirect.html sends token back to component

No localStorage bridging needed - config stays in memory.

PropertyTypeDescription
authorizationEndpoint?string-
tokenEndpoint?string-
clientId?string-
scopes?string[]-
redirectUri?stringURL to redirect.html - used for OAuth callback and token refresh

PopupOptions

PropertyType
width?number
height?number
left?number
top?number

TokenResponse

PropertyType
access_tokenstring
refresh_token?string
expires_in?number
refresh_expires_in?number
token_type?string
id_token?string

StoredTokenData

PropertyType
accessTokenstring
refreshToken?string
expiresAt?number
refreshExpiresAt?number

Message

PropertyType
idstring
author{displayName?: string; id?: string; type: "user" | "phoneNumber"; details?: { displayName?: string; id?: string; avatarUrl?: string; imageLastChangedAt?: string | null }}
displayNameOverride?string
channel?string
channelMessageComponentId?string
createdAtstring
direction"in" | "out"
fromPhoneNumber?string | null
isBotboolean
isCanned?boolean
isDeleted?boolean
isEdited?boolean
isEmail?boolean
isMms?boolean
isPinned?boolean
isPrivateboolean
isSaved?boolean
isSms?boolean
messagestring | FancyMessage[]
paginationIdstring
pinnedAtstring | null
pinnedBystring | null
pinnedByUserFirstLastNamestring | null
subType?MessageSubType
type"email" | "sms" | "chat"
updatedAt?string | null
threadChannelMessageId?string | null
translations?Record<string, string>

GetUsersResponse

Response from getUsers API. Used for transfer/consult target selection.

PropertyTypeDescription
idstringHandle / internal user ID
firstNamestringFirst name
lastNamestringLast name
fullNamestringFull name
emailstringEmail address
mobilestring | nullMobile phone number
presencestring | nullVoIP/presence status (e.g., "available", "busy", "offline")
cxStatus{statusType: string; status: string}CX status information
cxStatus.statusTypestringCX status category (e.g., "available", "busy", "away")
cxStatus.statusstringCX status display name (e.g., "Available", "On Call", "Lunch")
extensionstring | nullExtension number
eligiblebooleanWhether user is eligible for transfer

UserLocation

PropertyType
addressData?{address1: string; address2: string; city: string; state: string; country: string; postalCode: string; locationName: string}
locationIdstring
e911Numberstring
isE911string | boolean
e911CallerIdNumber?string | null

QueueInfo

PropertyType
queueIdstring
namestring
isAccessboolean
isAutoLoginboolean
proficiency?unknown

UserTag

PropertyType
tagIdstring
backgroundColorstring
colorstring
iconCodestring
namestring

DefaultLeaveEventToStatus

PropertyType
actionstring
statusstring

InfinityElement

PropertyType
accountIdstring
apiVersionIdstring
config{file: { filename: string; mimetype: string; size: number; storageId: string }}
createdAtstring
createdBystring
folderIdstring | null
iconstring
idstring
namestring
tagNamestring
updatedAtstring
updatedBystring | null
uploadedAtstring | null
uploadedBystring | null

UserInfo

PropertyTypeDescription
userIdstringUser ID
status?stringWhether the user is enabled (status === 'enabled' for yes)
firstNamestringFirst name
lastNamestringLast name
nameSuffix?string | nullName suffix (e.g., Jr., Sr., III)
titlestringJob title
emailstringEmail address
mobile?string | nullMobile phone number
languageCode?stringLanguage code (e.g., 'en', 'es')
location?UserLocation | nullE911 location information
timezone?stringTimezone (e.g., 'America/New_York')
licenseType?stringLicense type
consolePermissions?objectConsole permissions
appPermissions?objectApplication permissions
outboundPermissions?{task: "0" | "1"; email: "0" | "1"; phone: "0" | "1"; messaging: "0" | "1"}Outbound permissions by communication type
rejectInteractions?booleanInbound permissions - can reject interactions
monitoringAction?stringMonitoring action configuration
completedAction?stringCompleted action configuration
interactionViewsType?stringInteraction view type
modifyInteractionViews?booleanCan create/edit interaction views
tags?UserTag[]List of assigned tags
personalQueueId?stringPersonal queue ID
defaultOutboundQueue?stringDefault outbound queue name
outboundActionAndStatus?DefaultLeaveEventToStatusOutbound call action and status
inboundActionAndStatus?DefaultLeaveEventToStatusInbound call action and status
callbackActionAndStatus?DefaultLeaveEventToStatusCallback action and status
voicemailActionAndStatus?DefaultLeaveEventToStatusVoicemail action and status
queues?QueueInfo[]List of assigned queues with access, auto-login, and proficiency info
phoneSpaces?numberNumber of concurrent phone interactions allowed
messagingSpaces?numberNumber of concurrent messaging interactions allowed
emailSpaces?numberNumber of concurrent email interactions allowed
taskSpaces?numberNumber of concurrent task interactions allowed
eliteExtension?string | nullElite Agent Extension
eliteAgentId?string | nullElite Agent ID
eliteSipAddress?string | nullSIP Address
eliteSbcGroupId?string | nullSBC Group ID
crmConfigurations?unknownCRM Configuration object
infinityElements?InfinityElement[]App-level Infinity Elements assigned
authToken?stringAuthentication token (JWT) using accessToken

Type Aliases

CHANNEL_NAMES

const CHANNEL_NAMES = {
  INTERACTION_STATUS_CHANGED: "interaction-status-changed";
  INTERACTION_ENDED: "on-interaction-ended";
  INTERACTION_ACCEPTED: "on-interaction-accepted";
  INTERACTION_UPDATED: "on-interaction-updated";
  CONSULT_STATUS_CHANGED: "consult-status-changed";
  COMPLETE_AS_CONFERENCE: "on-complete-as-conference";
  FEED_MESSAGE: "feed-message";
  AGENT_STATE_CHANGED: "agent-state-changed";
  INTER_ELEMENT: "inter-element";
} as const;
PropertyValue
INTERACTION_STATUS_CHANGED"interaction-status-changed"
INTERACTION_ENDED"on-interaction-ended"
INTERACTION_ACCEPTED"on-interaction-accepted"
INTERACTION_UPDATED"on-interaction-updated"
CONSULT_STATUS_CHANGED"consult-status-changed"
COMPLETE_AS_CONFERENCE"on-complete-as-conference"
FEED_MESSAGE"feed-message"
AGENT_STATE_CHANGED"agent-state-changed"
INTER_ELEMENT"inter-element"

InteractionStatusChangedCallback()

type InteractionStatusChangedCallback = (payload: {
  interactionId: string;
  status: string;
}) => void;

InteractionEndedCallback()

type InteractionEndedCallback = (interactionId: string) => void;

InteractionAcceptedCallback()

type InteractionAcceptedCallback = (interactionId: string) => void;

InteractionUpdatedCallback()

type InteractionUpdatedCallback = (payload: {
  interactionId: string;
  event: "interaction.update";
  payload: Interaction;
}) => void;

ConsultStatusChangedCallback()

type ConsultStatusChangedCallback = (payload: {
  interactionId: string;
  consultStatus: string;
  consultParty?: string;
  error?: string;
}) => void;

CompleteAsConferenceCallback()

type CompleteAsConferenceCallback = (payload: {
  interactionId: string;
}) => void;

FeedMessageCallback()

type FeedMessageCallback = (message: Message, interactionId?: string) => void;

Parameters

ParameterTypeDescription
messageMessageThe message received
interactionId?stringOptional interaction ID the message belongs to

ErrorCallback()

type ErrorCallback = (error: {
  code: string;
  message: string;
  details?: unknown;
}) => void;

AgentStateChangedCallback()

type AgentStateChangedCallback = (payload: {
  previousState: string;
  currentState: string;
  reason?: string;
}) => void;

Parameters

ParameterTypeDescription
payload.previousStatestringThe previous agent state
payload.currentStatestringThe new agent state
payload.reason?stringOptional reason for the state change

FancyMessage

type FancyMessage =
  | AudioMessage
  | TextMessage
  | PreviewMessage
  | FileMessage
  | ActionMessage
  | EmailMessage;

MessageSubType

type MessageSubType = "babelVoice" | "transcription" | null;

Variables

VERSION

export const VERSION = "1.2.0";