@avaya/infinity-elements-api
v1.2.0
Published
InfinityElement API for web components to interact with the Infinity Extensibility Framework
Readme
@avaya/infinity-elements-api v1.1.1
@avaya/infinity-elements-api
Element API for InfinityElements to interact with the Infinity Extensibility Framework. This library provides a robust interface for communication between web components and the Infinity Agent Desktop.
Table of Contents
Installation
npm install @avaya/infinity-elements-apiFeatures
- 🔌 Easy Integration - Simple API for web components to interact with core-agent-ui
- 📡 Event-Driven - Subscribe to interaction events (accepted, ended, status changes)
- 🎯 Type-Safe - Full TypeScript support with comprehensive type definitions
- 📞 Call Management - Complete call control (transfer, consult, hold, mute, etc.)
- 👤 Agent Management - Get/set agent status, access user information
- 💬 Messaging - Send rich media messages and interact with the chat feed
Quick Start
Basic Setup
import { ElementAPI } from "@avaya/infinity-elements-api";
// Create API instance
const api = new ElementAPI();
// Get user information
const userInfo = await api.getUserInfo();
console.log("Agent:", userInfo.firstName, userInfo.lastName);
console.log("Email:", userInfo.email);
// Listen for interaction events
api.onInteractionAccepted((interactionId) => {
console.log("Interaction accepted:", interactionId);
});
api.onInteractionEnded((interactionId) => {
console.log("Interaction ended:", interactionId);
});
// Don't forget to clean up!
// In React: useEffect cleanup, in plain JS: on element unmount
api.destroy();React Example
import { ElementAPI } from "@avaya/infinity-elements-api";
import { useEffect, useState } from "react";
function MyElement() {
const [userInfo, setUserInfo] = useState(null);
useEffect(() => {
const api = new ElementAPI();
// Fetch user info on mount
api.getUserInfo().then(setUserInfo);
// Subscribe to interaction events
const unsubscribe = api.onInteractionAccepted((interactionId) => {
console.log("Interaction accepted:", interactionId);
});
// Cleanup on unmount
return () => {
unsubscribe();
api.destroy();
};
}, [api]);
return (
<div>
<h1>Agent: {userInfo?.displayName}</h1>
<p>Status: {userInfo?.agentStatus}</p>
</div>
);
}Core Concepts
ElementAPI
The main class for interacting with the Infinity Extensibility Framework. It handles:
- API requests to core-agent-ui via
window.postMessage - Event subscriptions for interaction lifecycle
- Inter-element communication via the host (postMessage)
Development
# Install dependencies
npm install
# Build the library
npm run build
# Run tests
npm test
# Watch mode for tests
npm run test:watch
# Generate documentation
npm run docs
# Lint
npm run lintLicense
MIT
Related Packages
@avaya/infinity-elements-sdk- CLI tool for scaffolding InfinityElement projects
API Documentation
DialpadDigit
Defined in: api/ElementAPI.ts:60
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);ElementAPI
Defined in: api/ElementAPI.ts:308
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.originreturns"null"(the literal string "null")document.referrermay 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.
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);
});Extends
Constructors
Constructor
new ElementAPI(options: ElementAPIOptions): ElementAPI;Defined in: api/ElementAPI.ts:345
Creates a new ElementAPI instance
Parameters
| Parameter | Type |
| ------ | ------ |
| options | ElementAPIOptions |
Returns
Example
const api = new ElementAPI({
elementId: 'my-custom-element',
timeout: 10000,
debug: true
});Overrides
Methods
destroy()
destroy(): void;Defined in: api/ElementAPI.ts:375
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
};
}, []);getInteraction()
getInteraction(options?: InteractionContextOptions): Promise<InteractionInfo>;Defined in: api/ElementAPI.ts:424
Get information about the current active interaction
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<InteractionInfo>
Promise resolving to the interaction information
Throws
Error if no active interaction exists
Examples
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');
}const interaction = await api.getInteraction({ interactionId: 'int-123' });
console.log('Status:', interaction.status);getUserInfo()
getUserInfo(): Promise<UserInfo>;Defined in: api/ElementAPI.ts:446
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);getUserInteractions()
getUserInteractions(params?: GetUserInteractionsParams): Promise<GetUserInteractionsResponse>;Defined in: api/ElementAPI.ts:479
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
| Parameter | Type | Description |
| ------ | ------ | ------ |
| params? | GetUserInteractionsParams | Optional parameters |
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);getUsers()
getUsers(params?: {
interactionId?: string;
filter?: string;
}): Promise<GetUsersResponse[]>;Defined in: api/ElementAPI.ts:540
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
interactionIdparameter - Interaction Level (interaction widgets): Omit
interactionId, uses interaction context automatically
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| params? | { interactionId?: string; filter?: string; } | Optional parameters |
| params.interactionId? | string | Required for app-level widgets, optional for interaction-level widgets |
| params.filter? | string | Optional substring search against user name fields |
Returns
Promise<GetUsersResponse[]>
Promise resolving to array of user information
Examples
const users = await api.getUsers();
users.forEach(user => {
console.log(`${user.fullName} - ${user.cxStatus.status} - ${user.presence}`);
});const users = await api.getUsers({ filter: 'john' });
console.log('Found users:', users.map(u => u.fullName));const users = await api.getUsers({ interactionId: 'int-123' });
users.forEach(user => {
console.log(`${user.fullName} - ${user.cxStatus.status} - ${user.presence}`);
});const users = await api.getUsers({
interactionId: 'int-123',
filter: 'john'
});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}`);
});viewerRemoveInteraction()
viewerRemoveInteraction(options?: InteractionContextOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:564
Remove the current interaction from the viewer
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
await api.viewerRemoveInteraction();await api.viewerRemoveInteraction({ interactionId: 'int-123' });endInteraction()
endInteraction(options?: InteractionContextOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:593
End the current interaction
Terminates the active interaction and disconnects the call.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
await api.endInteraction();
console.log('Interaction ended');await api.endInteraction({ interactionId: 'int-123' });startVoiceCall()
startVoiceCall(options?: InteractionContextOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:619
Start a voice call for the current interaction
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
await api.startVoiceCall();await api.startVoiceCall({ interactionId: 'int-123' });createVoiceInteraction()
createVoiceInteraction(params: CreateVoiceInteractionParams): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:645
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
| Parameter | Type | Description |
| ------ | ------ | ------ |
| params | CreateVoiceInteractionParams | Voice 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>;Defined in: api/ElementAPI.ts:673
Complete a blind transfer
Transfers the call to another agent or number without consultation.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options | BlindTransferOptions | Transfer 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;
}>;Defined in: api/ElementAPI.ts:693
Perform a single-step transfer
Transfers the interaction directly to the specified target.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| params | SingleStepTransferParams | Transfer parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Example
await api.singleStepTransfer({
targetId: 'user123',
targetName: 'Support Team'
});consultCall()
consultCall(options: ConsultCallOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:740
Initiate a consult call
Starts a consultation with another agent, phone number, or queue while keeping the original caller on hold.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options | ConsultCallOptions | Consult call configuration |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
const interaction = await api.getInteraction();
await api.consultCall({
interactionId: interaction.interactionId,
transferTo: '[email protected]'
});await api.consultCall({
interactionId: interaction.interactionId,
phoneNumber: '+1234567890'
});// Get available queues first
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;
}>;Defined in: api/ElementAPI.ts:764
Complete an attended transfer
Finalizes the attended transfer after consulting with the target party.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
// After consulting
await api.completeAttendedTransfer();await api.completeAttendedTransfer({ interactionId: 'int-123' });completeConference()
completeConference(options?: InteractionContextOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:793
Complete the interaction as a conference
Merges all parties into a conference call instead of completing a transfer.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
// After consulting
await api.completeConference();await api.completeConference({ interactionId: 'int-123' });attendedTransferWarm()
attendedTransferWarm(options?: InteractionContextOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:821
Perform a warm attended transfer
Introduces the caller to the transfer target before completing the transfer.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
await api.attendedTransferWarm();await api.attendedTransferWarm({ interactionId: 'int-123' });attendedTransferCancel()
attendedTransferCancel(options?: InteractionContextOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:849
Cancel an attended transfer
Cancels the ongoing attended transfer and returns to the original call.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
await api.attendedTransferCancel();await api.attendedTransferCancel({ interactionId: 'int-123' });acceptInteraction()
acceptInteraction(options?: InteractionContextOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:882
Accept an incoming interaction
Accepts a queued or alerting interaction.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
api.onInteractionAccepted(async (interactionId) => {
console.log('New interaction:', interactionId);
});
// When ready to accept
await api.acceptInteraction();await api.acceptInteraction({ interactionId: 'int-123' });sendDialpadDigit()
sendDialpadDigit(
digit: DialpadDigit,
audioOutputDeviceId: string | null,
noSendDialTone: boolean,
audioContextOverride?: "none" | "standard" | "webkit",
options?: InteractionContextOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:924
Send a DTMF dialpad digit during a call
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| digit | DialpadDigit | The dialpad digit to send (0-9) |
| audioOutputDeviceId | string | null | Audio output device ID or null for default |
| noSendDialTone | boolean | Whether to suppress the dial tone sound |
| audioContextOverride? | "none" | "standard" | "webkit" | Audio context type override |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
import { DialpadDigit } from '@avaya/infinity-elements-api';
await api.sendDialpadDigit(
DialpadDigit.One,
null,
false
);await api.sendDialpadDigit(
DialpadDigit.One,
null,
false,
undefined,
{ interactionId: 'int-123' }
);insertTextIntoFeedInput()
insertTextIntoFeedInput(text: string, options?: InteractionContextOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:958
Insert text into the chat feed input field
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| text | string | The text to insert |
| options? | InteractionContextOptions | Optional parameters |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
await api.insertTextIntoFeedInput('Hello, how can I help you today?');await api.insertTextIntoFeedInput('Hello!', { interactionId: 'int-123' });~~sendRichMediaMessage()~~
sendRichMediaMessage(options: SendRichMediaMessageOptions): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:999
Send a rich media message (image, file, etc.) to the interaction
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options | SendRichMediaMessageOptions | Message options (must provide either mediaUrl or file) |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Deprecated
This method is deprecated and will be removed in a future version.
Examples
await api.sendRichMediaMessage({
name: 'Product Image',
mediaUrl: 'https://example.com/image.jpg',
text: 'Here is the product you requested'
});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;
}>;Defined in: api/ElementAPI.ts:1077
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
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options | SendChatMessageOptions | Message options (must provide interactionId and at least one of text, mediaUrl, or file) |
Returns
Promise<{
message: string;
}>
Promise resolving to a success message
Examples
await api.sendChatMessage({
interactionId: 'int-123',
text: 'Hello, how can I help you today?'
});await api.sendChatMessage({
interactionId: 'int-123',
mediaUrl: 'https://example.com/image.jpg',
text: 'Here is the product you requested'
});const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
await api.sendChatMessage({
interactionId: 'int-123',
file: file,
text: 'Attached document'
});await api.sendChatMessage({
interactionId: 'int-123',
text: 'Please review this document',
file: documentFile,
fileName: 'Important Document.pdf'
});setAgentStatus()
setAgentStatus(
userId: string,
status: AgentStatus,
reason?: {
id: string;
name: string;
}): Promise<{
message: string;
}>;Defined in: api/ElementAPI.ts:1129
Set the agent's status (Available, Away, Busy, etc.)
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| userId | string | The user ID of the agent |
| status | AgentStatus | The 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
const userInfo = await api.getUserInfo();
await api.setAgentStatus(userInfo.userId, { id: 'available', name: 'Available', category: 'available' });const userInfo = await api.getUserInfo();
await api.setAgentStatus(userInfo.userId, { id: 'away', name: 'Away', category: 'away' }, {
id: 'lunch',
name: 'Lunch Break'
});getUserQueues()
getUserQueues(params?: {
filter?: string;
}): Promise<UserQueueInfo[]>;Defined in: api/ElementAPI.ts:1158
Get all queues available to the current user (App Level)
Returns a basic list of queues the agent has access to.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| params? | { filter?: string; } | Optional filter parameters |
| params.filter? | string | - |
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[]>;Defined in: api/ElementAPI.ts:1184
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
| Parameter | Type | Description |
| ------ | ------ | ------ |
| params | { interactionId: string; filter?: string; } | Required interactionId and optional filter parameters |
| params.interactionId | string | - |
| params.filter? | string | - |
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[]>;Defined in: api/ElementAPI.ts:1222
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
| Parameter | Type | Description |
| ------ | ------ | ------ |
| params? | { filter?: string; interactionId?: string; } | Optional filter parameters |
| params.filter? | string | Optional substring search against queue names |
| params.interactionId? | string | Optional 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
const queues = await api.getTransferQueuesInteraction({ filter: 'support' });
queues.forEach(queue => {
console.log(`${queue.name}: ${queue.waitingInteractions} waiting`);
console.log(`Active agents: ${queue.countActiveAgents}`);
});const queues = await api.getTransferQueuesInteraction({
filter: 'support',
interactionId: 'int-123'
});getReasonCodes()
getReasonCodes(params?: GetReasonCodesParams): Promise<GetReasonCodesResponse>;Defined in: api/ElementAPI.ts:1253
Get reason codes for agent status changes
Returns available reason codes that can be used when changing agent status.
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| params? | GetReasonCodesParams | Optional parameters |
Returns
Promise<GetReasonCodesResponse>
Promise resolving to reason codes response
Examples
const response = await api.getReasonCodes();
console.log('Reason codes:', response.reasons);const response = await api.getReasonCodes({ type: 'away' });
const awayReasons = response.reasons;getAvayaJwt()
getAvayaJwt(options: {
authorizationEndpoint?: string;
tokenEndpoint?: string;
clientId?: string;
scopes?: string[];
redirectUri?: string;
popupOptions?: PopupOptions;
forceRefresh?: boolean;
}): Promise<string>;Defined in: api/ElementAPI.ts:1303
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
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options | { authorizationEndpoint?: string; tokenEndpoint?: string; clientId?: string; scopes?: string[]; redirectUri?: string; popupOptions?: PopupOptions; forceRefresh?: boolean; } | Configuration options (all optional, uses defaults if not provided) |
| options.authorizationEndpoint? | string | Keycloak authorization endpoint URL |
| options.tokenEndpoint? | string | Keycloak token endpoint URL |
| options.clientId? | string | OAuth client ID |
| options.scopes? | string[] | OAuth scopes to request |
| options.redirectUri? | string | OAuth redirect URI (URL to redirect.html) |
| options.popupOptions? | PopupOptions | Popup window size/position (defaults to 500x600) |
| options.forceRefresh? | boolean | Force token refresh even if not expired (defaults to false) |
Returns
Promise<string>
Promise 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>;Defined in: api/ElementAPI.ts:1418
Refresh the access token using the stored refresh token
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| options | { tokenEndpoint?: string; clientId?: string; } | Configuration options |
| options.tokenEndpoint? | string | Keycloak token endpoint URL (required) |
| options.clientId? | string | OAuth client ID (required) |
Returns
Promise<string>
Promise 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;Defined in: api/ElementAPI.ts:1477
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 flowsendInterElementMessage()
sendInterElementMessage<T>(message: T): void;Defined in: api/ElementAPI.ts:1511
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 Parameter | Description |
| ------ | ------ |
| T | The type of the message |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| message | T | The 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;Defined in: api/ElementAPI.ts:1545
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 Parameter | Description |
| ------ | ------ |
| T | The expected type of messages |
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | (message: T) => void | Function called when a message is received |
Returns
Unsubscribe function to stop listening
(): void;Returns
void
Example
const unsubscribe = api.onInterElementMessage<MyMessageType>((message) => {
console.log('Received:', message);
});
// Later, stop listening
unsubscribe();log()
protected log(message: string, data?: unknown): void;Defined in: api/ElementAPI.ts:1704
Debug logging - no-op by default, overridden by ElementAPI subclass
Parameters
| Parameter | Type |
| ------ | ------ |
| message | string |
| data? | unknown |
Returns
void
Overrides
handleMessage()
protected handleMessage(data: Record<string, any>): boolean;Defined in: api/ElementAPIEvents.ts:93
Handle an incoming window message and dispatch to appropriate listeners.
Parameters
| Parameter | Type |
| ------ | ------ |
| data | Record<string, any> |
Returns
boolean
true if the message was handled as an event, false otherwise.
Inherited from
ElementAPIEvents.handleMessage
onInteractionStatusChanged()
onInteractionStatusChanged(callback: InteractionStatusChangedCallback): () => void;Defined in: api/ElementAPIEvents.ts:270
Subscribe to interaction status changes
Fires when the status of an interaction changes (e.g., alerting, connected, held)
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | InteractionStatusChangedCallback | Function to call when interaction status changes |
Returns
Unsubscribe function
(): void;Returns
void
Example
const unsubscribe = api.onInteractionStatusChanged(({ interactionId, status }) => {
console.log(`Interaction ${interactionId} status changed to ${status}`);
});
// Later, to unsubscribe:
unsubscribe();Inherited from
ElementAPIEvents.onInteractionStatusChanged
onInteractionAccepted()
onInteractionAccepted(callback: InteractionAcceptedCallback): () => void;Defined in: api/ElementAPIEvents.ts:293
Subscribe to interaction accepted events
Fires when an agent accepts an incoming interaction
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | InteractionAcceptedCallback | Function to call when an interaction is accepted |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onInteractionAccepted((interactionId) => {
console.log('Accepted interaction:', interactionId);
// Load customer data, show interaction UI, etc.
});Inherited from
ElementAPIEvents.onInteractionAccepted
onInteractionEnded()
onInteractionEnded(callback: InteractionEndedCallback): () => void;Defined in: api/ElementAPIEvents.ts:314
Subscribe to interaction ended events
Fires when an interaction is ended or disconnected
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | InteractionEndedCallback | Function to call when an interaction ends |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onInteractionEnded((interactionId) => {
console.log('Interaction ended:', interactionId);
// Clean up UI, save data, etc.
});Inherited from
ElementAPIEvents.onInteractionEnded
onInteractionUpdated()
onInteractionUpdated(callback: InteractionUpdatedCallback): () => void;Defined in: api/ElementAPIEvents.ts:335
Subscribe to interaction updated events
Fires when an interaction is updated with new information
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | InteractionUpdatedCallback | Function to call when an interaction is updated |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onInteractionUpdated(({ interactionId, payload }) => {
console.log('Interaction updated:', interactionId);
console.log('New data:', payload);
});Inherited from
ElementAPIEvents.onInteractionUpdated
onConsultStatusChanged()
onConsultStatusChanged(callback: ConsultStatusChangedCallback): () => void;Defined in: api/ElementAPIEvents.ts:355
Subscribe to consult status changes
Fires when the status of a consultation changes
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | ConsultStatusChangedCallback | Function to call when consult status changes |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onConsultStatusChanged(({ interactionId, consultStatus, consultParty }) => {
console.log(`Consult ${consultStatus} with ${consultParty}`);
});Inherited from
ElementAPIEvents.onConsultStatusChanged
onCompleteAsConference()
onCompleteAsConference(callback: CompleteAsConferenceCallback): () => void;Defined in: api/ElementAPIEvents.ts:375
Subscribe to complete as conference events
Fires when an interaction is completed as a conference
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | CompleteAsConferenceCallback | Function to call when an interaction is completed as a conference |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onCompleteAsConference(({ interactionId }) => {
console.log(`Interaction ${interactionId} completed as conference`);
});Inherited from
ElementAPIEvents.onCompleteAsConference
onReceivedFeedMessage()
onReceivedFeedMessage(callback: FeedMessageCallback): () => void;Defined in: api/ElementAPIEvents.ts:396
Subscribe to feed messages
Fires when a new message is received in the interaction feed
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | FeedMessageCallback | Function to call when a feed message is received. Receives (message: Message, interactionId?: string) |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onReceivedFeedMessage((message, interactionId) => {
console.log('New message:', message.text, 'for interaction:', interactionId);
});Inherited from
ElementAPIEvents.onReceivedFeedMessage
onError()
onError(callback: ErrorCallback): () => void;Defined in: api/ElementAPIEvents.ts:417
Subscribe to error events
Fires when an error occurs in the API
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | ErrorCallback | Function to call when an error occurs |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onError((error) => {
console.error('API Error:', error.code, error.message);
// Display error notification to user
});Inherited from
onChangedAgentState()
onChangedAgentState(callback: AgentStateChangedCallback): () => void;Defined in: api/ElementAPIEvents.ts:439
Subscribe to agent state changed events
Fires when the agent's state changes (e.g., Available, Away, Busy)
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | AgentStateChangedCallback | Function to call when agent state changes. Receives { previousState, currentState, reason? } |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onChangedAgentState(({ previousState, currentState, reason }) => {
console.log(`Agent state changed from ${previousState} to ${currentState}`);
if (reason) console.log(`Reason: ${reason}`);
});Inherited from
ElementAPIEvents.onChangedAgentState
destroyEventListeners()
protected destroyEventListeners(): void;Defined in: api/ElementAPIEvents.ts:447
Clear all event listeners
Returns
void
Inherited from
ElementAPIEvents.destroyEventListeners
ElementAPIEvents
Defined in: api/ElementAPIEvents.ts:66
ElementAPIEvents - Base class providing event subscription and dispatch for ElementAPI
Owns all event listener Sets, provides on* subscription methods, and dispatches incoming window messages to the appropriate listeners. ElementAPI extends this class to inherit all event functionality.
Extended by
Constructors
Constructor
new ElementAPIEvents(): ElementAPIEvents;Returns
Methods
log()
protected log(_message: string, _data?: unknown): void;Defined in: api/ElementAPIEvents.ts:84
Debug logging - no-op by default, overridden by ElementAPI subclass
Parameters
| Parameter | Type |
| ------ | ------ |
| _message | string |
| _data? | unknown |
Returns
void
handleMessage()
protected handleMessage(data: Record<string, any>): boolean;Defined in: api/ElementAPIEvents.ts:93
Handle an incoming window message and dispatch to appropriate listeners.
Parameters
| Parameter | Type |
| ------ | ------ |
| data | Record<string, any> |
Returns
boolean
true if the message was handled as an event, false otherwise.
onInteractionStatusChanged()
onInteractionStatusChanged(callback: InteractionStatusChangedCallback): () => void;Defined in: api/ElementAPIEvents.ts:270
Subscribe to interaction status changes
Fires when the status of an interaction changes (e.g., alerting, connected, held)
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | InteractionStatusChangedCallback | Function to call when interaction status changes |
Returns
Unsubscribe function
(): void;Returns
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;Defined in: api/ElementAPIEvents.ts:293
Subscribe to interaction accepted events
Fires when an agent accepts an incoming interaction
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | InteractionAcceptedCallback | Function to call when an interaction is accepted |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onInteractionAccepted((interactionId) => {
console.log('Accepted interaction:', interactionId);
// Load customer data, show interaction UI, etc.
});onInteractionEnded()
onInteractionEnded(callback: InteractionEndedCallback): () => void;Defined in: api/ElementAPIEvents.ts:314
Subscribe to interaction ended events
Fires when an interaction is ended or disconnected
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | InteractionEndedCallback | Function to call when an interaction ends |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onInteractionEnded((interactionId) => {
console.log('Interaction ended:', interactionId);
// Clean up UI, save data, etc.
});onInteractionUpdated()
onInteractionUpdated(callback: InteractionUpdatedCallback): () => void;Defined in: api/ElementAPIEvents.ts:335
Subscribe to interaction updated events
Fires when an interaction is updated with new information
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | InteractionUpdatedCallback | Function to call when an interaction is updated |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onInteractionUpdated(({ interactionId, payload }) => {
console.log('Interaction updated:', interactionId);
console.log('New data:', payload);
});onConsultStatusChanged()
onConsultStatusChanged(callback: ConsultStatusChangedCallback): () => void;Defined in: api/ElementAPIEvents.ts:355
Subscribe to consult status changes
Fires when the status of a consultation changes
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | ConsultStatusChangedCallback | Function to call when consult status changes |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onConsultStatusChanged(({ interactionId, consultStatus, consultParty }) => {
console.log(`Consult ${consultStatus} with ${consultParty}`);
});onCompleteAsConference()
onCompleteAsConference(callback: CompleteAsConferenceCallback): () => void;Defined in: api/ElementAPIEvents.ts:375
Subscribe to complete as conference events
Fires when an interaction is completed as a conference
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | CompleteAsConferenceCallback | Function to call when an interaction is completed as a conference |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onCompleteAsConference(({ interactionId }) => {
console.log(`Interaction ${interactionId} completed as conference`);
});onReceivedFeedMessage()
onReceivedFeedMessage(callback: FeedMessageCallback): () => void;Defined in: api/ElementAPIEvents.ts:396
Subscribe to feed messages
Fires when a new message is received in the interaction feed
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | FeedMessageCallback | Function to call when a feed message is received. Receives (message: Message, interactionId?: string) |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onReceivedFeedMessage((message, interactionId) => {
console.log('New message:', message.text, 'for interaction:', interactionId);
});onError()
onError(callback: ErrorCallback): () => void;Defined in: api/ElementAPIEvents.ts:417
Subscribe to error events
Fires when an error occurs in the API
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | ErrorCallback | Function to call when an error occurs |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onError((error) => {
console.error('API Error:', error.code, error.message);
// Display error notification to user
});onChangedAgentState()
onChangedAgentState(callback: AgentStateChangedCallback): () => void;Defined in: api/ElementAPIEvents.ts:439
Subscribe to agent state changed events
Fires when the agent's state changes (e.g., Available, Away, Busy)
Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| callback | AgentStateChangedCallback | Function to call when agent state changes. Receives { previousState, currentState, reason? } |
Returns
Unsubscribe function
(): void;Returns
void
Example
api.onChangedAgentState(({ previousState, currentState, reason }) => {
console.log(`Agent state changed from ${previousState} to ${currentState}`);
if (reason) console.log(`Reason: ${reason}`);
});destroyEventListeners()
protected destroyEventListeners(): void;Defined in: api/ElementAPIEvents.ts:447
Clear all event listeners
Returns
void
InteractionInfo
Defined in: api/ElementAPI.ts:15
Properties
| Property | Type | Defined in |
| ------ | ------ | ------ |
| id | string | api/ElementAPI.ts:16 |
| interactionId | string | api/ElementAPI.ts:17 |
| status | string | api/ElementAPI.ts:18 |
| commType? | string | api/ElementAPI.ts:19 |
| direction? | string | api/ElementAPI.ts:20 |
| customer? | { name?: string; number?: string; id?: string; } | api/ElementAPI.ts:21 |
| customer.name? | string | api/ElementAPI.ts:22 |
| customer.number? | string | api/ElementAPI.ts:23 |
| customer.id? | string | api/ElementAPI.ts:24 |
| startTime? | string | api/ElementAPI.ts:26 |
| duration? | number | api/ElementAPI.ts:27 |
| metadata? | Record<string, unknown> | api/ElementAPI.ts:28 |
InteractionUpdatePayload
Defined in: api/ElementAPI.ts:31
Properties
| Property | Type | Defined in |
| ------ | ------ | ------ |
| id | string | api/ElementAPI.ts:32 |
| status? | string | api/ElementAPI.ts:33 |
| commType? | string | api/ElementAPI.ts:34 |
| subCommType? | string | api/ElementAPI.ts:35 |
| isAudio? | boolean | api/ElementAPI.ts:36 |
| isHold? | boolean | api/ElementAPI.ts:37 |
| isMute? | boolean | api/ElementAPI.ts:38 |
| details? | { notes?: string; subject?: string; } | api/ElementAPI.ts:39 |
| details.notes? | string | api/ElementAPI.ts:40 |
| details.subject? | string | api/ElementAPI.ts:41 |
| sourceDetails? | { phoneNumber?: string; email?: string; name?: string; } | api/ElementAPI.ts:43 |
| sourceDetails.phoneNumber? | string | api/ElementAPI.ts:44 |
| sourceDetails.email? | string | api/ElementAPI.ts:45 |
| sourceDetails.name? | string | api/ElementAPI.ts:46 |
BlindTransferOptions
Defined in: [api/ElementAPI.ts:83](https://github.com/Solutions-and-Technology/core-extensibility-framework/blob/main/Ele
