@webex/calling 3.13.0-next.1 → 3.13.0-next.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +1 -1
  2. package/dist/CallHistory/CallHistory.js +1 -1
  3. package/dist/CallHistory/CallHistory.js.map +1 -1
  4. package/dist/CallHistory/CallHistory.test.js +2 -1
  5. package/dist/CallHistory/CallHistory.test.js.map +1 -1
  6. package/dist/CallQueue/CallQueue.js +1322 -0
  7. package/dist/CallQueue/CallQueue.js.map +1 -0
  8. package/dist/CallQueue/CallQueue.test.js +3321 -0
  9. package/dist/CallQueue/CallQueue.test.js.map +1 -0
  10. package/dist/CallQueue/constants.js +65 -0
  11. package/dist/CallQueue/constants.js.map +1 -0
  12. package/dist/CallQueue/types.js +4 -0
  13. package/dist/CallQueue/types.js.map +1 -0
  14. package/dist/CallQueue/utils.js +370 -0
  15. package/dist/CallQueue/utils.js.map +1 -0
  16. package/dist/CallQueue/utils.test.js +548 -0
  17. package/dist/CallQueue/utils.test.js.map +1 -0
  18. package/dist/CallingClient/constants.js +1 -1
  19. package/dist/CallingClient/constants.js.map +1 -1
  20. package/dist/CallingClient/registration/register.js +2 -2
  21. package/dist/CallingClient/registration/register.js.map +1 -1
  22. package/dist/CallingClient/registration/register.test.js +133 -97
  23. package/dist/CallingClient/registration/register.test.js.map +1 -1
  24. package/dist/Events/types.js +1 -0
  25. package/dist/Events/types.js.map +1 -1
  26. package/dist/SDKConnector/types.js.map +1 -1
  27. package/dist/Voicemail/Voicemail.js +10 -10
  28. package/dist/Voicemail/Voicemail.js.map +1 -1
  29. package/dist/Voicemail/Voicemail.test.js +40 -20
  30. package/dist/Voicemail/Voicemail.test.js.map +1 -1
  31. package/dist/api.js +47 -8
  32. package/dist/api.js.map +1 -1
  33. package/dist/common/Utils.js +8 -7
  34. package/dist/common/Utils.js.map +1 -1
  35. package/dist/common/Utils.test.js +320 -239
  36. package/dist/common/Utils.test.js.map +1 -1
  37. package/dist/index.js +102 -45
  38. package/dist/index.js.map +1 -1
  39. package/dist/module/CallHistory/CallHistory.js +1 -1
  40. package/dist/module/CallQueue/CallQueue.js +718 -0
  41. package/dist/module/CallQueue/constants.js +41 -0
  42. package/dist/module/CallQueue/types.js +1 -0
  43. package/dist/module/CallQueue/utils.js +253 -0
  44. package/dist/module/CallingClient/constants.js +1 -1
  45. package/dist/module/CallingClient/registration/register.js +1 -1
  46. package/dist/module/Events/types.js +1 -0
  47. package/dist/module/Voicemail/Voicemail.js +10 -10
  48. package/dist/module/api.js +5 -2
  49. package/dist/module/common/Utils.js +7 -5
  50. package/dist/module/index.js +4 -1
  51. package/dist/types/CallQueue/CallQueue.d.ts +45 -0
  52. package/dist/types/CallQueue/CallQueue.d.ts.map +1 -0
  53. package/dist/types/CallQueue/constants.d.ts +37 -0
  54. package/dist/types/CallQueue/constants.d.ts.map +1 -0
  55. package/dist/types/CallQueue/types.d.ts +97 -0
  56. package/dist/types/CallQueue/types.d.ts.map +1 -0
  57. package/dist/types/CallQueue/utils.d.ts +19 -0
  58. package/dist/types/CallQueue/utils.d.ts.map +1 -0
  59. package/dist/types/CallingClient/constants.d.ts +1 -1
  60. package/dist/types/CallingClient/constants.d.ts.map +1 -1
  61. package/dist/types/Events/types.d.ts +2 -1
  62. package/dist/types/Events/types.d.ts.map +1 -1
  63. package/dist/types/SDKConnector/types.d.ts +1 -1
  64. package/dist/types/SDKConnector/types.d.ts.map +1 -1
  65. package/dist/types/api.d.ts +8 -4
  66. package/dist/types/api.d.ts.map +1 -1
  67. package/dist/types/common/Utils.d.ts.map +1 -1
  68. package/dist/types/index.d.ts +5 -1
  69. package/dist/types/index.d.ts.map +1 -1
  70. package/package.json +12 -25
@@ -0,0 +1,718 @@
1
+ import SDKConnector from '../SDKConnector';
2
+ import { CALLING_BACKEND, HTTP_METHODS } from '../common/types';
3
+ import log from '../Logger';
4
+ import { getCallingBackEnd, serviceErrorCodeHandler, uploadLogs } from '../common/Utils';
5
+ import { FAILURE_MESSAGE, METHOD_START_MESSAGE, STATUS_CODE, SUCCESS_MESSAGE, WEBEX_API_BTS, WEBEX_API_FEDRAMP, WEBEX_API_PROD, } from '../common/constants';
6
+ import { Eventing } from '../Events/impl';
7
+ import { COMMON_EVENT_KEYS } from '../Events/types';
8
+ import { CALL_QUEUE_FILE, CALL_QUEUE_MERCURY_EVENT_KEYS, LINE_OWNER_ID_PATTERN, METHODS, MAX_QUEUE_CATALOG_PAGES, QUEUES_CATALOG_PATH, QUEUES_PATH, SECONDARY_LINES_PATH, SUPPORTED_STATES, SYNC_PATH, UNSUPPORTED_BACKEND_MESSAGE, WDM_DEVICE_ID_PATTERN, } from './constants';
9
+ import actorIdentity, { applyCallQueueEvent, applyQueueNames, parseCallQueueCatalog, parseCallQueueSettings, hasMalformedQueueRecords, publicApiId, queueIdKey, unwrapAgentPayload, hasReadyEntitlementModels, lifecycleConflictResponse, } from './utils';
10
+ export class CallQueueClient extends Eventing {
11
+ webex;
12
+ callingBackend;
13
+ webexApiEndpoint;
14
+ currentByLine = new Map();
15
+ queueNames = new Map();
16
+ eventGeneration = new Map();
17
+ requestSequence = 0;
18
+ committedSequence = new Map();
19
+ pendingEventRefresh = new Map();
20
+ mercuryListeners = [];
21
+ disposed = false;
22
+ lifecycleEpoch = 0;
23
+ constructor(webex, logger, options) {
24
+ super();
25
+ if (!SDKConnector.getWebex()) {
26
+ SDKConnector.setWebex(webex);
27
+ }
28
+ if (SDKConnector.getWebex() !== webex) {
29
+ throw new Error('Call queue Webex instance must match the SDKConnector instance');
30
+ }
31
+ this.webex = SDKConnector.getWebex();
32
+ const apiBaseUrl = options?.webexApiBaseUrl;
33
+ const allowedOrigins = [WEBEX_API_BTS, WEBEX_API_PROD, WEBEX_API_FEDRAMP];
34
+ const normalized = typeof apiBaseUrl === 'string' ? apiBaseUrl.replace(/\/$/, '') : '';
35
+ this.webexApiEndpoint = allowedOrigins.includes(normalized) ? `${normalized}/v1` : undefined;
36
+ this.callingBackend = hasReadyEntitlementModels(this.webex)
37
+ ? getCallingBackEnd(this.webex)
38
+ : CALLING_BACKEND.INVALID;
39
+ log.setLogger(logger.level, CALL_QUEUE_FILE);
40
+ this.registerAgentListeners();
41
+ }
42
+ async getCallQueueSettings(lineOwnerId) {
43
+ const loggerContext = { file: CALL_QUEUE_FILE, method: METHODS.GET_CALL_QUEUE_SETTINGS };
44
+ log.info(METHOD_START_MESSAGE, loggerContext);
45
+ const rejected = this.rejectBeforeRequest(lineOwnerId);
46
+ if (rejected) {
47
+ return rejected;
48
+ }
49
+ const epoch = this.lifecycleEpoch;
50
+ const generation = this.eventGeneration.get(lineOwnerId) ?? 0;
51
+ this.requestSequence += 1;
52
+ const sequence = this.requestSequence;
53
+ try {
54
+ const response = await this.webex.request({
55
+ uri: this.queuesUrl(lineOwnerId),
56
+ method: HTTP_METHODS.GET,
57
+ });
58
+ if (epoch !== this.lifecycleEpoch) {
59
+ return lifecycleConflictResponse();
60
+ }
61
+ log.log(`Response trackingId: ${response?.headers?.trackingid}`, loggerContext);
62
+ const parsed = parseCallQueueSettings(response.body, this.currentByLine.get(lineOwnerId));
63
+ const named = parsed ? await this.fillQueueNames(parsed) : undefined;
64
+ if (epoch !== this.lifecycleEpoch) {
65
+ return lifecycleConflictResponse();
66
+ }
67
+ if ((this.eventGeneration.get(lineOwnerId) ?? 0) !== generation ||
68
+ (this.committedSequence.get(lineOwnerId) ?? 0) > sequence) {
69
+ await this.waitForEventRefreshes(lineOwnerId);
70
+ if (epoch !== this.lifecycleEpoch) {
71
+ return lifecycleConflictResponse();
72
+ }
73
+ const latest = this.currentByLine.get(lineOwnerId);
74
+ return latest
75
+ ? {
76
+ statusCode: Number(response[STATUS_CODE]) || 200,
77
+ data: { callQueue: latest },
78
+ message: SUCCESS_MESSAGE,
79
+ }
80
+ : {
81
+ statusCode: 409,
82
+ data: { error: 'Call queue settings changed while loading; retry the request' },
83
+ message: FAILURE_MESSAGE,
84
+ };
85
+ }
86
+ if (!named) {
87
+ return {
88
+ statusCode: 502,
89
+ data: { error: 'Call queue settings response was invalid or did not include agent status' },
90
+ message: FAILURE_MESSAGE,
91
+ };
92
+ }
93
+ this.currentByLine.set(lineOwnerId, named);
94
+ this.committedSequence.set(lineOwnerId, sequence);
95
+ log.log(`Call queue settings loaded, state=${named.acdState}, queues=${named.queues.length}`, loggerContext);
96
+ return {
97
+ statusCode: Number(response[STATUS_CODE]) || 200,
98
+ data: { callQueue: named },
99
+ message: SUCCESS_MESSAGE,
100
+ };
101
+ }
102
+ catch (err) {
103
+ const failure = await this.fail(err, loggerContext, 'Failed to get call queue settings', epoch);
104
+ if (failure && epoch === this.lifecycleEpoch)
105
+ return failure;
106
+ return lifecycleConflictResponse();
107
+ }
108
+ }
109
+ async updateCallQueueSettings(request, lineOwnerId) {
110
+ const loggerContext = { file: CALL_QUEUE_FILE, method: METHODS.UPDATE_CALL_QUEUE_SETTINGS };
111
+ log.info(METHOD_START_MESSAGE, loggerContext);
112
+ const rejected = this.rejectBeforeRequest(lineOwnerId) ?? this.rejectUpdate(request);
113
+ if (rejected) {
114
+ return rejected;
115
+ }
116
+ const epoch = this.lifecycleEpoch;
117
+ let requestSent = false;
118
+ try {
119
+ if (this.needsQueuePolicyRefresh(request, lineOwnerId)) {
120
+ const settings = await this.getCallQueueSettings(lineOwnerId);
121
+ if (epoch !== this.lifecycleEpoch) {
122
+ return lifecycleConflictResponse();
123
+ }
124
+ if (settings.statusCode >= 400) {
125
+ return settings;
126
+ }
127
+ if (!settings.data.callQueue) {
128
+ return {
129
+ statusCode: 400,
130
+ data: { error: 'Call queue settings are required before updating queue membership' },
131
+ message: FAILURE_MESSAGE,
132
+ };
133
+ }
134
+ }
135
+ const body = this.buildUpdateBody(request, lineOwnerId);
136
+ const generation = this.eventGeneration.get(lineOwnerId) ?? 0;
137
+ this.requestSequence += 1;
138
+ const sequence = this.requestSequence;
139
+ requestSent = true;
140
+ const response = await this.webex.request({
141
+ uri: this.queuesUrl(lineOwnerId),
142
+ method: HTTP_METHODS.PUT,
143
+ body,
144
+ });
145
+ if (epoch !== this.lifecycleEpoch) {
146
+ return lifecycleConflictResponse(true);
147
+ }
148
+ log.log(`Response trackingId: ${response?.headers?.trackingid}`, loggerContext);
149
+ const current = this.currentByLine.get(lineOwnerId);
150
+ const parsed = parseCallQueueSettings(response.body, current);
151
+ const local = parsed ??
152
+ (current && !hasMalformedQueueRecords(response.body)
153
+ ? this.applyLocalUpdate(request, lineOwnerId)
154
+ : undefined);
155
+ const named = local ? await this.fillQueueNames(local) : undefined;
156
+ if (epoch !== this.lifecycleEpoch) {
157
+ return lifecycleConflictResponse(true);
158
+ }
159
+ if (!named ||
160
+ (this.eventGeneration.get(lineOwnerId) ?? 0) !== generation ||
161
+ (this.committedSequence.get(lineOwnerId) ?? 0) > sequence) {
162
+ const refreshed = await this.getCallQueueSettings(lineOwnerId);
163
+ if (epoch !== this.lifecycleEpoch) {
164
+ return lifecycleConflictResponse(true);
165
+ }
166
+ return refreshed.data.callQueue
167
+ ? {
168
+ statusCode: Number(response[STATUS_CODE]) || 200,
169
+ data: { callQueue: refreshed.data.callQueue },
170
+ message: SUCCESS_MESSAGE,
171
+ }
172
+ : refreshed;
173
+ }
174
+ this.currentByLine.set(lineOwnerId, named);
175
+ this.committedSequence.set(lineOwnerId, sequence);
176
+ log.log(`Call queue settings updated, state=${named.acdState}, queues=${named.queues.length}`, loggerContext);
177
+ return {
178
+ statusCode: Number(response[STATUS_CODE]) || 200,
179
+ data: { callQueue: named },
180
+ message: SUCCESS_MESSAGE,
181
+ };
182
+ }
183
+ catch (err) {
184
+ const failure = await this.fail(err, loggerContext, 'Failed to update call queue settings', epoch);
185
+ if (failure && epoch === this.lifecycleEpoch)
186
+ return failure;
187
+ return lifecycleConflictResponse(requestSent);
188
+ }
189
+ }
190
+ async syncTelephonyCalls() {
191
+ const loggerContext = { file: CALL_QUEUE_FILE, method: METHODS.SYNC_TELEPHONY_CALLS };
192
+ log.info(METHOD_START_MESSAGE, loggerContext);
193
+ const rejected = this.rejectBeforeRequest();
194
+ if (rejected) {
195
+ return rejected;
196
+ }
197
+ const wdmUrl = this.webex.internal.device?.url;
198
+ if (!wdmUrl || !this.wdmDeviceId()) {
199
+ return {
200
+ statusCode: 400,
201
+ data: { error: 'A registered device is required to sync telephony calls' },
202
+ message: FAILURE_MESSAGE,
203
+ };
204
+ }
205
+ const epoch = this.lifecycleEpoch;
206
+ try {
207
+ const response = await this.webex.request({
208
+ uri: this.joinUrl(SYNC_PATH),
209
+ method: HTTP_METHODS.POST,
210
+ body: { wdmUrl, resources: [{ resource: 'telephony_agents' }] },
211
+ });
212
+ if (epoch !== this.lifecycleEpoch) {
213
+ return lifecycleConflictResponse();
214
+ }
215
+ log.log(`Response trackingId: ${response?.headers?.trackingid}`, loggerContext);
216
+ const current = this.currentByLine.get(undefined);
217
+ return {
218
+ statusCode: Number(response[STATUS_CODE]) || 200,
219
+ data: current ? { callQueue: current } : {},
220
+ message: SUCCESS_MESSAGE,
221
+ };
222
+ }
223
+ catch (err) {
224
+ const failure = await this.fail(err, loggerContext, 'Failed to sync telephony calls', epoch);
225
+ if (failure && epoch === this.lifecycleEpoch)
226
+ return failure;
227
+ return lifecycleConflictResponse();
228
+ }
229
+ }
230
+ registerAgentListeners() {
231
+ if (this.callingBackend !== CALLING_BACKEND.WXC) {
232
+ return;
233
+ }
234
+ const events = [
235
+ [CALL_QUEUE_MERCURY_EVENT_KEYS.TELEPHONY_AGENT_SYNC, 'sync'],
236
+ [CALL_QUEUE_MERCURY_EVENT_KEYS.TELEPHONY_AGENT_STATE, 'state'],
237
+ [CALL_QUEUE_MERCURY_EVENT_KEYS.TELEPHONY_AGENT_JOIN, 'join'],
238
+ [CALL_QUEUE_MERCURY_EVENT_KEYS.TELEPHONY_AGENT_SYNC_SINGULAR, 'sync'],
239
+ [CALL_QUEUE_MERCURY_EVENT_KEYS.TELEPHONY_AGENT_STATE_SINGULAR, 'state'],
240
+ [CALL_QUEUE_MERCURY_EVENT_KEYS.TELEPHONY_AGENT_JOIN_SINGULAR, 'join'],
241
+ ];
242
+ const startingCount = this.mercuryListeners.length;
243
+ try {
244
+ events.forEach(([event, kind]) => {
245
+ const listener = (data) => this.handleAgentEvent(kind, data);
246
+ this.mercuryListeners.push({ event, listener });
247
+ this.webex.internal.mercury.on(event, listener);
248
+ });
249
+ }
250
+ catch (error) {
251
+ const added = this.mercuryListeners.splice(startingCount);
252
+ added.forEach(({ event, listener }) => {
253
+ try {
254
+ this.webex.internal.mercury.off(event, listener);
255
+ }
256
+ catch {
257
+ this.mercuryListeners.push({ event, listener });
258
+ log.warn('Failed to remove call queue Mercury listener after registration failed', {
259
+ file: CALL_QUEUE_FILE,
260
+ method: 'registerAgentListeners',
261
+ });
262
+ }
263
+ });
264
+ throw error;
265
+ }
266
+ }
267
+ prepareForReuse() {
268
+ if (this.disposed)
269
+ return false;
270
+ const backend = hasReadyEntitlementModels(this.webex)
271
+ ? getCallingBackEnd(this.webex)
272
+ : CALLING_BACKEND.INVALID;
273
+ if (this.mercuryListeners.length && backend !== CALLING_BACKEND.WXC)
274
+ return false;
275
+ this.lifecycleEpoch += 1;
276
+ this.currentByLine.clear();
277
+ this.queueNames.clear();
278
+ this.eventGeneration.clear();
279
+ this.committedSequence.clear();
280
+ this.pendingEventRefresh.clear();
281
+ this.callingBackend = backend;
282
+ if (backend === CALLING_BACKEND.WXC && !this.mercuryListeners.length) {
283
+ this.registerAgentListeners();
284
+ }
285
+ return true;
286
+ }
287
+ dispose() {
288
+ this.disposed = true;
289
+ this.lifecycleEpoch += 1;
290
+ this.mercuryListeners.forEach(({ event, listener }) => {
291
+ this.webex.internal.mercury.off(event, listener);
292
+ });
293
+ this.mercuryListeners = [];
294
+ this.currentByLine.clear();
295
+ this.queueNames.clear();
296
+ this.eventGeneration.clear();
297
+ this.committedSequence.clear();
298
+ this.pendingEventRefresh.clear();
299
+ this.removeAllListeners();
300
+ }
301
+ eventLine(event) {
302
+ const payload = unwrapAgentPayload(event);
303
+ if (payload?.actorType !== undefined && typeof payload.actorType !== 'string') {
304
+ return { kind: 'ignore' };
305
+ }
306
+ const type = payload?.actorType?.toUpperCase();
307
+ const actorId = payload?.actorId ?? (type === 'VIRTUAL_LINE' ? undefined : payload?.actorPersonId);
308
+ if (!actorId) {
309
+ return type ? { kind: 'ignore' } : { kind: 'primary' };
310
+ }
311
+ if (typeof actorId !== 'string')
312
+ return { kind: 'ignore' };
313
+ const actor = actorIdentity(actorId);
314
+ const actorType = type ?? actor.type;
315
+ const primaryId = this.webex.internal.device?.userId;
316
+ if (actorType === 'PERSON' || actorType === 'PEOPLE') {
317
+ return primaryId && actor.id === actorIdentity(primaryId).id
318
+ ? { kind: 'primary' }
319
+ : { kind: 'ignore' };
320
+ }
321
+ if (actorType && actorType !== 'VIRTUAL_LINE')
322
+ return { kind: 'ignore' };
323
+ const cachedLine = [...this.currentByLine.keys()].find((id) => id !== undefined && actorIdentity(id).id === actor.id);
324
+ if (actorType === 'VIRTUAL_LINE') {
325
+ const lineOwnerId = cachedLine ?? actor.id;
326
+ return LINE_OWNER_ID_PATTERN.test(lineOwnerId)
327
+ ? { kind: 'secondary', lineOwnerId }
328
+ : { kind: 'ignore' };
329
+ }
330
+ if (primaryId && actor.id === actorIdentity(primaryId).id)
331
+ return { kind: 'primary' };
332
+ return cachedLine ? { kind: 'secondary', lineOwnerId: cachedLine } : { kind: 'ignore' };
333
+ }
334
+ handleAgentEvent(kind, event) {
335
+ if (this.disposed)
336
+ return;
337
+ const epoch = this.lifecycleEpoch;
338
+ const line = this.eventLine(event);
339
+ if (line.kind === 'ignore')
340
+ return;
341
+ const lineOwnerId = line.kind === 'secondary' ? line.lineOwnerId : undefined;
342
+ const current = this.currentByLine.get(lineOwnerId);
343
+ const next = applyCallQueueEvent(current, kind, event);
344
+ if (!next || (current && next === current))
345
+ return;
346
+ const generation = (this.eventGeneration.get(lineOwnerId) ?? 0) + 1;
347
+ this.eventGeneration.set(lineOwnerId, generation);
348
+ if (!current) {
349
+ const pending = this.refreshEventLine(lineOwnerId, generation);
350
+ if (epoch !== this.lifecycleEpoch)
351
+ return;
352
+ this.pendingEventRefresh.set(lineOwnerId, pending);
353
+ pending.then(() => {
354
+ if (this.pendingEventRefresh.get(lineOwnerId) === pending) {
355
+ this.pendingEventRefresh.delete(lineOwnerId);
356
+ }
357
+ });
358
+ return;
359
+ }
360
+ if (next.acdState === current.acdState && next.queues === current.queues) {
361
+ return;
362
+ }
363
+ const named = applyQueueNames(next, this.queueNames);
364
+ this.currentByLine.set(lineOwnerId, named);
365
+ log.log(`Call queue ${kind} event applied, state=${named.acdState}, queues=${named.queues.length}`, { file: CALL_QUEUE_FILE, method: 'handleAgentEvent' });
366
+ this.emit(COMMON_EVENT_KEYS.CALL_QUEUE_UPDATED, lineOwnerId ? { ...named, lineOwnerId } : named);
367
+ if (epoch !== this.lifecycleEpoch)
368
+ return;
369
+ if (named.queues.some((queue) => !queue.name)) {
370
+ this.refreshQueueNames(named, generation, lineOwnerId).catch((err) => {
371
+ log.error(`Failed to refresh call queue names: ${String(err)}`, {
372
+ file: CALL_QUEUE_FILE,
373
+ method: 'refreshQueueNames',
374
+ });
375
+ });
376
+ }
377
+ }
378
+ async waitForEventRefreshes(lineOwnerId) {
379
+ let pending = this.pendingEventRefresh.get(lineOwnerId);
380
+ while (pending) {
381
+ await pending;
382
+ const next = this.pendingEventRefresh.get(lineOwnerId);
383
+ if (next === pending)
384
+ return;
385
+ pending = next;
386
+ }
387
+ }
388
+ async refreshEventLine(lineOwnerId, generation) {
389
+ if (this.rejectBeforeRequest(lineOwnerId))
390
+ return;
391
+ const epoch = this.lifecycleEpoch;
392
+ this.requestSequence += 1;
393
+ const sequence = this.requestSequence;
394
+ try {
395
+ const response = await this.webex.request({
396
+ uri: this.queuesUrl(lineOwnerId),
397
+ method: HTTP_METHODS.GET,
398
+ });
399
+ if (epoch !== this.lifecycleEpoch)
400
+ return;
401
+ const parsed = parseCallQueueSettings(response.body, this.currentByLine.get(lineOwnerId));
402
+ if (!parsed)
403
+ return;
404
+ const named = await this.fillQueueNames(parsed);
405
+ if (epoch !== this.lifecycleEpoch ||
406
+ generation !== this.eventGeneration.get(lineOwnerId) ||
407
+ (this.committedSequence.get(lineOwnerId) ?? 0) > sequence)
408
+ return;
409
+ this.currentByLine.set(lineOwnerId, named);
410
+ this.committedSequence.set(lineOwnerId, sequence);
411
+ this.emit(COMMON_EVENT_KEYS.CALL_QUEUE_UPDATED, lineOwnerId ? { ...named, lineOwnerId } : named);
412
+ }
413
+ catch {
414
+ log.error('Failed to refresh call queue settings after an event', {
415
+ file: CALL_QUEUE_FILE,
416
+ method: 'refreshEventLine',
417
+ });
418
+ }
419
+ }
420
+ async refreshQueueNames(status, generation, lineOwnerId) {
421
+ const epoch = this.lifecycleEpoch;
422
+ const named = await this.fillQueueNames(status);
423
+ if (epoch !== this.lifecycleEpoch ||
424
+ generation !== this.eventGeneration.get(lineOwnerId) ||
425
+ this.currentByLine.get(lineOwnerId) !== status ||
426
+ named === status) {
427
+ return;
428
+ }
429
+ this.currentByLine.set(lineOwnerId, named);
430
+ this.emit(COMMON_EVENT_KEYS.CALL_QUEUE_UPDATED, lineOwnerId ? { ...named, lineOwnerId } : named);
431
+ }
432
+ async fillQueueNames(status) {
433
+ const missingIds = status.queues
434
+ .filter((queue) => !queue.name && !this.queueNames.has(queueIdKey(queue.id)))
435
+ .map((queue) => queueIdKey(queue.id));
436
+ if (missingIds.length > 0) {
437
+ await this.loadQueueCatalog(missingIds);
438
+ }
439
+ return applyQueueNames(status, this.queueNames);
440
+ }
441
+ async loadQueueCatalog(neededIds) {
442
+ const loggerContext = { file: CALL_QUEUE_FILE, method: METHODS.GET_CALL_QUEUE_NAMES };
443
+ const epoch = this.lifecycleEpoch;
444
+ const loadPage = async (uri, remainingPages) => {
445
+ if (epoch !== this.lifecycleEpoch ||
446
+ remainingPages === 0 ||
447
+ neededIds.every((id) => this.queueNames.has(id))) {
448
+ return;
449
+ }
450
+ const response = await this.webex.request({
451
+ uri,
452
+ method: HTTP_METHODS.GET,
453
+ });
454
+ if (epoch !== this.lifecycleEpoch)
455
+ return;
456
+ const catalog = parseCallQueueCatalog(response.body);
457
+ catalog.entries.forEach((entry) => {
458
+ if (entry.name) {
459
+ this.queueNames.set(queueIdKey(entry.id), entry.name);
460
+ }
461
+ });
462
+ const link = response.headers?.link || response.headers?.Link;
463
+ const headerNext = link
464
+ ?.split(',')
465
+ .map((entry) => /<([^>]+)>\s*;\s*rel=["']?next["']?/i.exec(entry)?.[1])
466
+ .find(Boolean);
467
+ const next = this.catalogNextUrl(headerNext || catalog.next);
468
+ if (next) {
469
+ await loadPage(next, remainingPages - 1);
470
+ }
471
+ };
472
+ try {
473
+ await loadPage(this.joinUrl(QUEUES_CATALOG_PATH), MAX_QUEUE_CATALOG_PAGES);
474
+ }
475
+ catch (err) {
476
+ const statusCode = err && typeof err === 'object' && 'statusCode' in err
477
+ ? err.statusCode
478
+ : undefined;
479
+ log.error(`Failed to load call queue names: status=${statusCode ?? 'unknown'}`, loggerContext);
480
+ }
481
+ }
482
+ catalogNextUrl(next) {
483
+ if (!next || next.includes('..') || next.includes('\\') || next.includes('@')) {
484
+ return undefined;
485
+ }
486
+ try {
487
+ const catalog = new URL(this.joinUrl(QUEUES_CATALOG_PATH));
488
+ const candidate = new URL(next.startsWith(QUEUES_CATALOG_PATH) ? this.joinUrl(next) : next, catalog);
489
+ return candidate.origin === catalog.origin && candidate.pathname === catalog.pathname
490
+ ? candidate.toString()
491
+ : undefined;
492
+ }
493
+ catch {
494
+ return undefined;
495
+ }
496
+ }
497
+ wdmDeviceId() {
498
+ const url = this.webex.internal.device?.url;
499
+ const id = typeof url === 'string' ? url.split('/').filter(Boolean).pop() : undefined;
500
+ if (!id || !WDM_DEVICE_ID_PATTERN.test(id)) {
501
+ return undefined;
502
+ }
503
+ return id;
504
+ }
505
+ queuesUrl(lineOwnerId) {
506
+ if (!lineOwnerId) {
507
+ return this.joinUrl(QUEUES_PATH);
508
+ }
509
+ return this.joinUrl(`${SECONDARY_LINES_PATH}/${encodeURIComponent(publicApiId(lineOwnerId, 'VIRTUAL_LINE'))}/queues`);
510
+ }
511
+ joinUrl(path) {
512
+ const endpoint = this.webexApiEndpoint || '';
513
+ const base = endpoint.endsWith('/') ? endpoint : `${endpoint}/`;
514
+ return `${base}${path}`;
515
+ }
516
+ rejectBeforeRequest(lineOwnerId) {
517
+ if (this.disposed) {
518
+ return {
519
+ statusCode: 400,
520
+ data: { error: 'Call queue client has been disposed' },
521
+ message: FAILURE_MESSAGE,
522
+ };
523
+ }
524
+ this.callingBackend = hasReadyEntitlementModels(this.webex)
525
+ ? getCallingBackEnd(this.webex)
526
+ : CALLING_BACKEND.INVALID;
527
+ if (this.callingBackend !== CALLING_BACKEND.WXC) {
528
+ return {
529
+ statusCode: 501,
530
+ data: { error: UNSUPPORTED_BACKEND_MESSAGE },
531
+ message: FAILURE_MESSAGE,
532
+ };
533
+ }
534
+ if (!this.mercuryListeners.length)
535
+ this.registerAgentListeners();
536
+ if (lineOwnerId !== undefined && !LINE_OWNER_ID_PATTERN.test(lineOwnerId)) {
537
+ return {
538
+ statusCode: 400,
539
+ data: { error: 'lineOwnerId is not a valid line id' },
540
+ message: FAILURE_MESSAGE,
541
+ };
542
+ }
543
+ if (!this.webexApiEndpoint) {
544
+ return {
545
+ statusCode: 400,
546
+ data: { error: 'A supported Webex API base URL is required for call queues' },
547
+ message: FAILURE_MESSAGE,
548
+ };
549
+ }
550
+ return undefined;
551
+ }
552
+ rejectUpdate(request) {
553
+ if (!request || typeof request !== 'object' || Array.isArray(request)) {
554
+ return {
555
+ statusCode: 400,
556
+ data: { error: 'a call queue settings update is required' },
557
+ message: FAILURE_MESSAGE,
558
+ };
559
+ }
560
+ const hasState = request.agentACDState !== undefined;
561
+ const hasQueues = request.queues !== undefined;
562
+ if (!hasState && !hasQueues) {
563
+ return {
564
+ statusCode: 400,
565
+ data: { error: 'agentACDState or queues is required' },
566
+ message: FAILURE_MESSAGE,
567
+ };
568
+ }
569
+ if (hasState && !SUPPORTED_STATES.has(request.agentACDState)) {
570
+ return {
571
+ statusCode: 400,
572
+ data: { error: 'agentACDState is not a supported ACD state' },
573
+ message: FAILURE_MESSAGE,
574
+ };
575
+ }
576
+ if (hasQueues && !Array.isArray(request.queues)) {
577
+ return {
578
+ statusCode: 400,
579
+ data: { error: 'queues must be an array of queue updates' },
580
+ message: FAILURE_MESSAGE,
581
+ };
582
+ }
583
+ if (hasQueues && request.queues?.length === 0) {
584
+ return {
585
+ statusCode: 400,
586
+ data: { error: 'queues must include at least one queue update' },
587
+ message: FAILURE_MESSAGE,
588
+ };
589
+ }
590
+ if (hasQueues) {
591
+ const invalid = request.queues?.some((queue) => !queue ||
592
+ typeof queue.id !== 'string' ||
593
+ !queue.id.trim() ||
594
+ typeof queue.available !== 'boolean');
595
+ if (invalid) {
596
+ return {
597
+ statusCode: 400,
598
+ data: { error: 'each queue update needs an id and an available flag' },
599
+ message: FAILURE_MESSAGE,
600
+ };
601
+ }
602
+ }
603
+ return undefined;
604
+ }
605
+ buildUpdateBody(request, lineOwnerId) {
606
+ const body = {};
607
+ if (request.agentACDState) {
608
+ body.agentACDState = request.agentACDState;
609
+ }
610
+ if (request.queues) {
611
+ body.queues = request.queues.map((queue) => ({
612
+ id: publicApiId(queue.id, 'CALL_QUEUE'),
613
+ available: this.canChangeJoin(queue.id, lineOwnerId) ? queue.available : true,
614
+ }));
615
+ }
616
+ return body;
617
+ }
618
+ canChangeJoin(queueId, lineOwnerId) {
619
+ const known = this.currentByLine
620
+ .get(lineOwnerId)
621
+ ?.queues.find((queue) => queueIdKey(queue.id) === queueIdKey(queueId));
622
+ if (!known || known.allowLogOffEnabled === undefined) {
623
+ return true;
624
+ }
625
+ return known.allowLogOffEnabled;
626
+ }
627
+ needsQueuePolicyRefresh(request, lineOwnerId) {
628
+ const status = this.currentByLine.get(lineOwnerId);
629
+ return Boolean(request.queues?.some((queue) => !queue.available &&
630
+ !status?.queues.some((known) => queueIdKey(known.id) === queueIdKey(queue.id) &&
631
+ known.allowLogOffEnabled !== undefined)));
632
+ }
633
+ applyLocalUpdate(request, lineOwnerId) {
634
+ const base = this.currentByLine.get(lineOwnerId);
635
+ const queues = request.queues
636
+ ? request.queues.reduce((list, update) => {
637
+ const index = list.findIndex((queue) => queueIdKey(queue.id) === queueIdKey(update.id));
638
+ const available = this.canChangeJoin(update.id, lineOwnerId) ? update.available : true;
639
+ if (index === -1) {
640
+ return list.concat({ id: update.id, available });
641
+ }
642
+ const next = list.slice();
643
+ next[index] = { ...list[index], available };
644
+ return next;
645
+ }, base.queues)
646
+ : base.queues;
647
+ return {
648
+ acdState: request.agentACDState ?? base.acdState,
649
+ queues,
650
+ };
651
+ }
652
+ async fail(err, loggerContext, message, epoch) {
653
+ if (epoch !== this.lifecycleEpoch)
654
+ return undefined;
655
+ const statusCode = err && typeof err === 'object' && 'statusCode' in err
656
+ ? err.statusCode
657
+ : undefined;
658
+ log.error(`${message}: status=${statusCode ?? 'unknown'}`, loggerContext);
659
+ try {
660
+ await uploadLogs();
661
+ }
662
+ catch {
663
+ log.warn('Unable to upload call queue diagnostic logs', loggerContext);
664
+ }
665
+ return serviceErrorCodeHandler((err ?? {}), loggerContext);
666
+ }
667
+ }
668
+ const clientConfigurations = new WeakMap();
669
+ export function createCallQueueClient(webex, logger, options, previousClient, enabled) {
670
+ const createOrReuse = () => {
671
+ const config = {
672
+ webex,
673
+ apiBaseUrl: options?.webexApiBaseUrl,
674
+ loggerLevel: logger?.level,
675
+ userId: webex.internal.device?.userId,
676
+ orgId: webex.internal.device?.orgId,
677
+ };
678
+ const previousConfig = previousClient && clientConfigurations.get(previousClient);
679
+ const compatible = previousConfig &&
680
+ previousConfig.webex === config.webex &&
681
+ previousConfig.apiBaseUrl === config.apiBaseUrl &&
682
+ previousConfig.loggerLevel === config.loggerLevel &&
683
+ previousConfig.userId === config.userId &&
684
+ previousConfig.orgId === config.orgId;
685
+ if (previousClient && compatible) {
686
+ try {
687
+ if (previousClient.prepareForReuse())
688
+ return previousClient;
689
+ }
690
+ catch (error) {
691
+ previousClient.dispose();
692
+ throw error;
693
+ }
694
+ }
695
+ previousClient?.dispose();
696
+ const client = new CallQueueClient(webex, logger, options);
697
+ clientConfigurations.set(client, config);
698
+ return client;
699
+ };
700
+ if (enabled === undefined)
701
+ return createOrReuse();
702
+ try {
703
+ if (enabled)
704
+ return createOrReuse();
705
+ previousClient?.dispose();
706
+ }
707
+ catch (error) {
708
+ const context = { file: CALL_QUEUE_FILE, method: 'createCallQueueClient' };
709
+ log.warn(`Error occurred while initializing callQueue client ${String(error)}`, context);
710
+ try {
711
+ previousClient?.dispose();
712
+ }
713
+ catch (cleanupError) {
714
+ log.warn(`Error occurred while disposing callQueue client ${String(cleanupError)}`, context);
715
+ }
716
+ }
717
+ return undefined;
718
+ }