@openfin/cloud-interop-core-api 0.0.1-alpha.e6793f0 → 0.0.1-alpha.e6a1a71

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.
package/index.mjs ADDED
@@ -0,0 +1,754 @@
1
+ import { Buffer } from 'buffer';
2
+ import mqtt from 'mqtt';
3
+
4
+ var l=t=>{let e=t.replaceAll("-","+").replaceAll("_","/");return e.padEnd(e.length+(4-e.length%4)%4,"=")};
5
+
6
+ class CloudInteropAPIError extends Error {
7
+ code;
8
+ constructor(message = 'An unexpected error has occurred', code = 'UNEXPECTED_ERROR', cause) {
9
+ super(message, { cause: cause });
10
+ this.name = this.constructor.name;
11
+ this.code = code;
12
+ }
13
+ }
14
+ class AuthorizationError extends CloudInteropAPIError {
15
+ constructor(message = 'Not authorized', code = 'ERR_UNAUTHORIZED') {
16
+ super(message, code, undefined);
17
+ }
18
+ }
19
+
20
+ class EventController {
21
+ #eventListeners = new Map();
22
+ addEventListener(type, callback) {
23
+ const listeners = this.#eventListeners.get(type) || [];
24
+ listeners.push(callback);
25
+ this.#eventListeners.set(type, listeners);
26
+ }
27
+ removeEventListener(type, callback) {
28
+ const listeners = this.#eventListeners.get(type) || [];
29
+ const index = listeners.indexOf(callback);
30
+ if (index !== -1) {
31
+ listeners.splice(index, 1);
32
+ }
33
+ this.#eventListeners.set(type, listeners);
34
+ }
35
+ once(type, callback) {
36
+ const listener = (...args) => {
37
+ this.removeEventListener(type, listener);
38
+ // @ts-expect-error - TS doesn't like the spread operator here
39
+ callback(...args);
40
+ };
41
+ this.addEventListener(type, listener);
42
+ }
43
+ emitEvent(type, ...args) {
44
+ const listeners = this.#eventListeners.get(type) || [];
45
+ listeners.forEach((listener) => listener(...args));
46
+ }
47
+ }
48
+
49
+ const isErrorIntentResult = (result) => 'error' in result;
50
+
51
+ const APP_ID_DELIM = '::';
52
+ const getRequestHeaders = (connectionParameters) => {
53
+ const headers = {};
54
+ headers['Content-Type'] = 'application/json';
55
+ if (connectionParameters.authenticationType === 'jwt' && connectionParameters.jwtAuthenticationParameters) {
56
+ const tokenResult = connectionParameters.jwtAuthenticationParameters.jwtRequestCallback();
57
+ if (!tokenResult) {
58
+ throw new Error('jwtRequestCallback must return a token');
59
+ }
60
+ headers['x-of-auth-id'] = connectionParameters.jwtAuthenticationParameters.authenticationId;
61
+ headers['Authorization'] =
62
+ typeof tokenResult === 'string' ? `Bearer ${tokenResult}` : `Bearer ${Buffer.from(JSON.stringify(tokenResult)).toString('base64')}`;
63
+ }
64
+ if (connectionParameters.authenticationType === 'basic' && connectionParameters.basicAuthenticationParameters) {
65
+ const { username, password } = connectionParameters.basicAuthenticationParameters;
66
+ headers['Authorization'] = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
67
+ }
68
+ return headers;
69
+ };
70
+ /**
71
+ * Encodes all app intents in the format: `appId::sourceId::sessionId`,
72
+ * where sourceId and sessionId are URI encoded
73
+ * @param appIntents
74
+ * @param source
75
+ * @returns
76
+ */
77
+ const encodeAppIntents = (appIntents, source) => appIntents.map((intent) => ({
78
+ ...intent,
79
+ apps: intent.apps.map((app) => ({ ...app, appId: encodeAppId(app.appId, source) })),
80
+ }));
81
+ /**
82
+ * Decodes all app intents by URI decoding the parts previously encoded by `encodeAppIntents`
83
+ * @param appIntents
84
+ * @returns
85
+ */
86
+ const decodeAppIntents = (appIntents) => appIntents.map((intent) => ({
87
+ ...intent,
88
+ apps: intent.apps.map((app) => ({ ...app, appId: decodeAppId(app.appId) })),
89
+ }));
90
+ const encodeAppId = (appIdString, { sessionId, sourceId }) => {
91
+ const id = encodeURIComponent(appIdString);
92
+ const sId = encodeURIComponent(sourceId);
93
+ return `${id}${APP_ID_DELIM}${sId}${APP_ID_DELIM}${sessionId}`;
94
+ };
95
+ const decodeAppId = (appId) => {
96
+ const [encodedAppId, encodedSourceId, sessionId] = appId.split(APP_ID_DELIM);
97
+ const id = decodeURIComponent(encodedAppId);
98
+ const sourceId = decodeURIComponent(encodedSourceId);
99
+ return `${id}${APP_ID_DELIM}${sourceId}${APP_ID_DELIM}${sessionId}`;
100
+ };
101
+ /**
102
+ * Decodes the AppIdentifier to extract the appId, sourceId, and sessionId.
103
+ * @returns an object with:
104
+ * - appId: The appId, or the original appId if unable to parse.
105
+ * - sourceId: The sourceId, or an '' if unable to parse.
106
+ * - sessionId: The sessionId, or an '' if unable to parse.
107
+ */
108
+ const parseCloudAppId = (appId = '') => {
109
+ const originalAppString = typeof appId === 'string' ? appId : (appId.appId ?? '');
110
+ const parts = originalAppString.split(APP_ID_DELIM);
111
+ return {
112
+ appId: parts[0]?.trim() ?? originalAppString,
113
+ sourceId: parts[1]?.trim() ?? '',
114
+ sessionId: parts[2]?.trim() ?? '',
115
+ };
116
+ };
117
+ const getSourceFromSession = (sessionDetails) => ({
118
+ sessionId: sessionDetails.sessionId,
119
+ sourceId: sessionDetails.sourceId,
120
+ userId: sessionDetails.sub,
121
+ orgId: sessionDetails.orgId,
122
+ platformId: sessionDetails.platformId,
123
+ });
124
+
125
+ const MIN_TIMEOUT = 500;
126
+ const DEFAULT_TIMEOUT = 3000;
127
+ const newDiscovery = () => ({
128
+ id: undefined,
129
+ pendingIntentDetailsEvents: [],
130
+ sessionCount: 0,
131
+ responseCount: 0,
132
+ state: 'not-started',
133
+ });
134
+ class IntentController {
135
+ #url;
136
+ #mqttClient;
137
+ #sessionDetails;
138
+ #connectionParams;
139
+ #events;
140
+ #logger;
141
+ #discovery = newDiscovery();
142
+ #discoveryTimeout;
143
+ constructor(url, mqttClient, sessionDetails, connectionParameters, events, logger) {
144
+ this.#url = url;
145
+ this.#mqttClient = mqttClient;
146
+ this.#sessionDetails = sessionDetails;
147
+ this.#connectionParams = connectionParameters;
148
+ this.#events = events;
149
+ this.#logger = logger;
150
+ }
151
+ async startIntentDiscovery(options) {
152
+ if (this.#discovery.state === 'in-progress') {
153
+ throw new Error('Intent discovery already in progress');
154
+ }
155
+ const { timeout = DEFAULT_TIMEOUT, findOptions } = options;
156
+ // clamp min value to 500ms
157
+ const clampedTimeout = Math.max(timeout, MIN_TIMEOUT);
158
+ try {
159
+ const startResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}`, {
160
+ method: 'POST',
161
+ headers: getRequestHeaders(this.#connectionParams),
162
+ body: JSON.stringify({ findOptions }),
163
+ });
164
+ if (!startResponse.ok) {
165
+ throw new Error(`Error creating intent discovery record: ${startResponse.statusText}`);
166
+ }
167
+ // TODO: type this response?
168
+ const json = await startResponse.json();
169
+ this.#discovery.id = json.discoveryId;
170
+ this.#discovery.sessionCount = json.sessionCount;
171
+ this.#discovery.state = 'in-progress';
172
+ if (this.#discovery.sessionCount === 1) {
173
+ // since we have no other connected sessions, we can end discovery immediately
174
+ await this.#endIntentDiscovery(false);
175
+ return;
176
+ }
177
+ // Listen out for discovery results directly sent to us
178
+ await this.#mqttClient.subscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`);
179
+ this.#discoveryTimeout = setTimeout(() => this.#endIntentDiscovery(), clampedTimeout);
180
+ }
181
+ catch (error) {
182
+ // Clean up any ongoing discoveries
183
+ this.#endIntentDiscovery();
184
+ throw new CloudInteropAPIError('Error starting intent discovery', 'ERR_STARTING_INTENT_DISCOVERY', error);
185
+ }
186
+ }
187
+ async #endIntentDiscovery(mqttUnsubscribe = true) {
188
+ if (this.#discovery.state !== 'in-progress') {
189
+ return;
190
+ }
191
+ if (this.#discoveryTimeout) {
192
+ clearTimeout(this.#discoveryTimeout);
193
+ this.#discoveryTimeout = undefined;
194
+ }
195
+ this.#discovery.state = 'ended';
196
+ // emit our aggregated events
197
+ this.#events.emitEvent('aggregate-intent-details', { responses: this.#discovery.pendingIntentDetailsEvents });
198
+ if (mqttUnsubscribe) {
199
+ // gracefully end discovery
200
+ await this.#mqttClient.unsubscribeAsync(`${this.#sessionDetails.sessionRootTopic}/commands/${this.#discovery.id}`).catch(() => {
201
+ this.#logger('warn', `Error ending intent discovery: could not unsubscribe from discovery id ${this.#discovery.id}`);
202
+ });
203
+ }
204
+ await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${this.#discovery.id}`, {
205
+ method: 'DELETE',
206
+ headers: getRequestHeaders(this.#connectionParams),
207
+ })
208
+ .then((deleteResponse) => {
209
+ if (!deleteResponse.ok) {
210
+ throw new Error(`Error ending intent discovery: ${deleteResponse.statusText}`);
211
+ }
212
+ })
213
+ .catch((error) => {
214
+ this.#logger('warn', `Error ending intent discovery: ${error}`);
215
+ });
216
+ // clean up
217
+ this.#discovery = newDiscovery();
218
+ }
219
+ async raiseIntent({ raiseOptions, appId }) {
220
+ const targetSessionId = parseCloudAppId(appId).sessionId;
221
+ if (!targetSessionId) {
222
+ // TODO: should we add more info here about the format?
223
+ throw new CloudInteropAPIError(`Invalid AppId specified, must be encoded as a cloud-session app id`, 'ERR_INVALID_TARGET_SESSION_ID');
224
+ }
225
+ const postResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/sessions/${targetSessionId}`, {
226
+ method: 'POST',
227
+ headers: getRequestHeaders(this.#connectionParams),
228
+ body: JSON.stringify({ raiseOptions }),
229
+ });
230
+ if (!postResponse.ok) {
231
+ // TODO: maybe add a debug flag to print these when dev'ing?
232
+ // console.log(`Error raising intent: ${await postResponse.text()}`);
233
+ throw new CloudInteropAPIError(`Error raising intent`, 'ERR_RAISING_INTENT', new Error(postResponse.statusText));
234
+ }
235
+ }
236
+ async reportAppIntents(discoveryId, intents) {
237
+ intents = encodeAppIntents(intents, getSourceFromSession(this.#sessionDetails));
238
+ try {
239
+ const reportResponse = await fetch(`${this.#url}/api/intents/${this.#sessionDetails.sessionId}/${discoveryId}`, {
240
+ method: 'POST',
241
+ headers: getRequestHeaders(this.#connectionParams),
242
+ body: JSON.stringify({ intents }),
243
+ });
244
+ if (reportResponse.ok) {
245
+ return true;
246
+ }
247
+ throw new CloudInteropAPIError('Error reporting intents', 'ERR_REPORTING_INTENTS', new Error(reportResponse.statusText));
248
+ }
249
+ catch (error) {
250
+ this.#logger('warn', `Error reporting intents for discovery ID ${discoveryId}: ${error}`);
251
+ }
252
+ return false;
253
+ }
254
+ async sendIntentResult(initiatingSessionId, result) {
255
+ if (!isErrorIntentResult(result)) {
256
+ // cloud-encode the source app id to support chained intent actions over cloud
257
+ // https://fdc3.finos.org/docs/2.0/api/spec#resolution-object -> "Use metadata about the resolving app instance to target a further intent"
258
+ const source = getSourceFromSession(this.#sessionDetails);
259
+ const encoded = encodeAppId(typeof result.source === 'string' ? result.source : result.source.appId, source);
260
+ result.source = typeof result.source === 'string' ? encoded : { ...result.source, appId: encoded };
261
+ }
262
+ const { sessionId } = getSourceFromSession(this.#sessionDetails);
263
+ const resultResponse = await fetch(`${this.#url}/api/intents/${initiatingSessionId}/result/${sessionId}`, {
264
+ method: 'POST',
265
+ headers: getRequestHeaders(this.#connectionParams),
266
+ body: JSON.stringify({ result }),
267
+ });
268
+ if (!resultResponse.ok) {
269
+ throw new CloudInteropAPIError('Error sending intent result', 'ERR_SENDING_INTENT_RESULT', new Error(resultResponse.statusText));
270
+ }
271
+ }
272
+ handleCommandMessage(message) {
273
+ switch (message.command) {
274
+ case 'report-intents': {
275
+ if (message.initiatingSessionId === this.#sessionDetails?.sessionId) {
276
+ // Ignore if this originated from us
277
+ return;
278
+ }
279
+ const { command: _, ...event } = message;
280
+ this.#events.emitEvent('report-intents', event);
281
+ break;
282
+ }
283
+ case 'intent-details': {
284
+ /**
285
+ * We aggregate intent details commands from all connected sessions on the server side
286
+ * to ensure upstream clients don't have to do this. Also given @openfin/cloud-interop
287
+ * exposes FDC3 compliant APIs, there is no concept of streaming available, hence we
288
+ * aggregate the responses here and send them in a synchronous manner.
289
+ */
290
+ const { command: _, ...event } = message;
291
+ // Decode intents before emitting to client
292
+ event.intents = decodeAppIntents(event.intents);
293
+ // always emit individual intent-details events in addition to aggregate-intent-details
294
+ // for flexibility after intent discovery has ended, this can be useful for late-joining
295
+ // clients nearing the timeout
296
+ this.#events.emitEvent('intent-details', event);
297
+ if (message.discoveryId !== this.#discovery.id || this.#discovery.state !== 'in-progress') {
298
+ // Ignore if its any other discovery id for some reason, or
299
+ // if we're not in the middle of a discovery
300
+ return;
301
+ }
302
+ this.#discovery.responseCount += 1;
303
+ this.#logger('debug', `Received intent details from ${message.source.sessionId}, received: ${this.#discovery.responseCount}, out of connected sessions: ${this.#discovery.sessionCount - 1}`);
304
+ this.#discovery.pendingIntentDetailsEvents.push(event);
305
+ const allResponded = this.#discovery.responseCount === this.#discovery.sessionCount - 1;
306
+ if (allResponded) {
307
+ this.#endIntentDiscovery();
308
+ }
309
+ break;
310
+ }
311
+ case 'raise-intent': {
312
+ if (message.targetSessionId === this.#sessionDetails?.sessionId) {
313
+ const { command: _, ...event } = message;
314
+ this.#events.emitEvent('raise-intent', event);
315
+ }
316
+ break;
317
+ }
318
+ case 'intent-result': {
319
+ if (message.initiatingSessionId === this.#sessionDetails?.sessionId) {
320
+ // Return result to originator and end discovery
321
+ const { command: _, ...resultEvent } = message;
322
+ this.#events.emitEvent('intent-result', resultEvent);
323
+ }
324
+ break;
325
+ }
326
+ default: {
327
+ this.#logger('warn', `Unknown command message received:\n${JSON.stringify(message, null, 2)}`);
328
+ break;
329
+ }
330
+ }
331
+ }
332
+ }
333
+
334
+ // Error codes as defined in https://docs.emqx.com/en/cloud/latest/connect_to_deployments/mqtt_client_error_codes.html
335
+ const BadUserNamePasswordError = 134;
336
+ /**
337
+ * Represents a single connection to a Cloud Interop service
338
+ *
339
+ * @public
340
+ * @class
341
+ */
342
+ class CloudInteropAPI {
343
+ #cloudInteropSettings;
344
+ #sessionDetails;
345
+ #mqttClient;
346
+ #reconnectRetryLimit = 30;
347
+ #keepAliveIntervalSeconds = 30;
348
+ #logger = (level, message) => {
349
+ console[level](message);
350
+ };
351
+ #reconnectRetries = 0;
352
+ #connectionParams;
353
+ #attemptingToReconnect = false;
354
+ #events = new EventController();
355
+ #intents;
356
+ #sessionTimer;
357
+ constructor(cloudInteropSettings) {
358
+ this.#cloudInteropSettings = cloudInteropSettings;
359
+ }
360
+ get sessionDetails() {
361
+ return this.#sessionDetails;
362
+ }
363
+ get mqttClient() {
364
+ return this.#mqttClient;
365
+ }
366
+ /**
367
+ * Connects and creates a session on the Cloud Interop service
368
+ *
369
+ * @param parameters - The parameters to use to connect
370
+ * @returns Promise that resolves when connection is established
371
+ * @memberof CloudInteropAPI
372
+ * @throws CloudInteropAPIError - If an error occurs during connection
373
+ * @throws AuthorizationError - If the connection is unauthorized
374
+ */
375
+ async connect(parameters) {
376
+ this.#validateConnectParams(parameters);
377
+ this.#connectionParams = parameters;
378
+ this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
379
+ this.#keepAliveIntervalSeconds = parameters.keepAliveIntervalSeconds || this.#keepAliveIntervalSeconds;
380
+ this.#logger = parameters.logger || this.#logger;
381
+ const { sourceId, platformId } = this.#connectionParams;
382
+ const createSessionResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions`, {
383
+ method: 'POST',
384
+ headers: getRequestHeaders(this.#connectionParams),
385
+ body: JSON.stringify({ sourceId: sourceId.trim(), platformId }),
386
+ });
387
+ if (!createSessionResponse.ok) {
388
+ if (createSessionResponse.status === 401 || createSessionResponse.status === 403) {
389
+ throw new AuthorizationError();
390
+ }
391
+ throw new CloudInteropAPIError();
392
+ }
393
+ if (createSessionResponse.status !== 201) {
394
+ throw new CloudInteropAPIError(`Failed to connect to the Cloud Interop service: ${this.#cloudInteropSettings.url}`, 'ERR_CONNECT', new Error(createSessionResponse.statusText));
395
+ }
396
+ this.#sessionDetails = (await createSessionResponse.json());
397
+ // If local session expiry handling is enabled, start the session timer
398
+ if (this.#sessionDetails.localSessionExpiryHandling) {
399
+ this.#logger('debug', `Local session expiry handling is enabled`);
400
+ this.#startSessionTimer();
401
+ }
402
+ const sessionRootTopic = this.#sessionDetails.sessionRootTopic;
403
+ const clientOptions = {
404
+ keepalive: this.#keepAliveIntervalSeconds,
405
+ clientId: this.#sessionDetails.sessionId,
406
+ clean: true,
407
+ protocolVersion: 5,
408
+ // The "will" message will be published on an unexpected disconnection
409
+ // The server can then tidy up. So it needs every for this client to do that, the session details is perfect
410
+ will: {
411
+ topic: 'interop/lastwill',
412
+ payload: Buffer.from(JSON.stringify(this.#sessionDetails)),
413
+ qos: 0,
414
+ retain: false,
415
+ },
416
+ username: this.#sessionDetails.token,
417
+ };
418
+ this.#mqttClient = await mqtt.connectAsync(this.#sessionDetails.url, clientOptions);
419
+ // TODO: Dynamic intent discovery
420
+ // search for any ongoing discoveries in DB and fire report-intents on self
421
+ this.#logger('log', `Cloud Interop successfully connected to ${this.#cloudInteropSettings.url}`);
422
+ this.#mqttClient.on('error', async (error) => {
423
+ // We will receive errors for each failed reconnection attempt
424
+ // We don't want to disconnect on these else we will never reconnect
425
+ if (!this.#attemptingToReconnect) {
426
+ await this.#disconnect(false);
427
+ }
428
+ if (error instanceof mqtt.ErrorWithReasonCode) {
429
+ switch (error.code) {
430
+ case BadUserNamePasswordError: {
431
+ this.#handleSessionExpiry();
432
+ return;
433
+ }
434
+ default: {
435
+ this.#logger('error', `Unknown Infrastructure Error Code ${error.code} : ${error.message}${this.#attemptingToReconnect ? ' during reconnection attempt' : ''}`);
436
+ // As we are in the middle of a reconnect, lets not emit an error to cut down on the event noise
437
+ if (!this.#attemptingToReconnect) {
438
+ this.#events.emitEvent('error', new CloudInteropAPIError(`Unknown Infrastructure Error Code ${error.code} : ${error.message}`, 'ERR_INFRASTRUCTURE', error));
439
+ break;
440
+ }
441
+ }
442
+ }
443
+ }
444
+ else {
445
+ this.#logger('error', `Unknown Error${this.#attemptingToReconnect ? ' during reconnection attempt' : ''}: ${error}`);
446
+ // As we are in the middle of a reconnect, lets not emit an error to cut down on the event noise
447
+ if (!this.#attemptingToReconnect) {
448
+ this.#events.emitEvent('error', new CloudInteropAPIError(`Unknown Error`, 'ERR_UNKNOWN', error));
449
+ }
450
+ }
451
+ });
452
+ this.#mqttClient.on('reconnect', () => {
453
+ this.#attemptingToReconnect = true;
454
+ this.#reconnectRetries += 1;
455
+ this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
456
+ if (this.#reconnectRetries === this.#reconnectRetryLimit) {
457
+ this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
458
+ this.#disconnect(true);
459
+ }
460
+ this.#events.emitEvent('reconnecting', this.#reconnectRetries);
461
+ });
462
+ // Does not fire on initial connection, only successful reconnection attempts
463
+ this.#mqttClient.on('connect', () => {
464
+ this.#logger('debug', `Cloud Interop successfully reconnected after ${this.#reconnectRetries} attempts`);
465
+ this.#reconnectRetries = 0;
466
+ this.#attemptingToReconnect = false;
467
+ this.#events.emitEvent('reconnected');
468
+ });
469
+ this.#mqttClient.on('message', (topic, message) => {
470
+ if (!this.#sessionDetails) {
471
+ this.#logger('warn', 'Received message when session not connected');
472
+ return;
473
+ }
474
+ this.#handleMessage(topic, message, this.#sessionDetails);
475
+ });
476
+ // Subscribe to all context groups
477
+ this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
478
+ // Listen out for global commands
479
+ this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
480
+ this.#initControllers(this.#mqttClient, this.#sessionDetails, this.#connectionParams);
481
+ }
482
+ /**
483
+ * Disconnects from the Cloud Interop service
484
+ *
485
+ * @returns Promise that resolves when disconnected
486
+ * @memberof CloudInteropAPI
487
+ * @throws CloudInteropAPIError - If an error occurs during disconnection
488
+ */
489
+ async disconnect() {
490
+ await this.#disconnect(true);
491
+ }
492
+ /**
493
+ * Publishes a new context for the given context group to the other connected sessions
494
+ *
495
+ * @param contextGroup - The context group to publish to
496
+ * @param context - The context to publish
497
+ * @returns Promise that resolves when context is published
498
+ * @memberof CloudInteropAPI
499
+ */
500
+ async setContext(contextGroup, context) {
501
+ // TODO: make context of type OpenFin.Context
502
+ if (!this.#sessionDetails || !this.#connectionParams) {
503
+ throw new Error('Session not connected');
504
+ }
505
+ if (!this.#mqttClient) {
506
+ throw new Error('MQTT client not connected');
507
+ }
508
+ const payload = {
509
+ context,
510
+ timestamp: Date.now(),
511
+ };
512
+ const postResponse = await fetch(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, {
513
+ method: 'POST',
514
+ headers: getRequestHeaders(this.#connectionParams),
515
+ body: JSON.stringify(payload),
516
+ });
517
+ if (!postResponse.ok) {
518
+ throw new CloudInteropAPIError(`Error setting context for ${contextGroup}`, 'ERR_SETTING_CONTEXT', new Error(postResponse.statusText));
519
+ }
520
+ }
521
+ /**
522
+ * Starts an intent discovery operation
523
+ *
524
+ * @returns Promise that resolves when intent discovery is started
525
+ * @memberof CloudInteropAPI
526
+ * @throws CloudInteropAPIError - If an error occurs during intent discovery
527
+ */
528
+ async startIntentDiscovery(options) {
529
+ this.#throwIfNotConnected();
530
+ return this.#intents?.startIntentDiscovery(options);
531
+ }
532
+ async raiseIntent(options) {
533
+ this.#throwIfNotConnected();
534
+ return this.#intents?.raiseIntent(options);
535
+ }
536
+ async reportAppIntents(discoveryId, intents) {
537
+ this.#throwIfNotConnected();
538
+ return this.#intents?.reportAppIntents(discoveryId, intents) ?? false;
539
+ }
540
+ async sendIntentResult(initiatingSessionId, result) {
541
+ this.#throwIfNotConnected();
542
+ return this.#intents?.sendIntentResult(initiatingSessionId, result);
543
+ }
544
+ parseSessionId(appId) {
545
+ return parseCloudAppId(appId).sessionId;
546
+ }
547
+ parseAppId(appId) {
548
+ return parseCloudAppId(appId).appId;
549
+ }
550
+ addEventListener(type, callback) {
551
+ this.#events.addEventListener(type, callback);
552
+ }
553
+ removeEventListener(type, callback) {
554
+ this.#events.removeEventListener(type, callback);
555
+ }
556
+ once(type, callback) {
557
+ this.#events.once(type, callback);
558
+ }
559
+ async #disconnect(fireDisconnectedEvent) {
560
+ if (!this.#sessionDetails) {
561
+ return;
562
+ }
563
+ try {
564
+ if (!this.#connectionParams) {
565
+ throw new Error('Connect parameters must be provided');
566
+ }
567
+ // Cancel session timer if it's running
568
+ if (this.#sessionTimer) {
569
+ clearTimeout(this.#sessionTimer);
570
+ this.#sessionTimer = undefined;
571
+ }
572
+ const disconnectResponse = await fetch(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
573
+ method: 'DELETE',
574
+ headers: getRequestHeaders(this.#connectionParams),
575
+ });
576
+ if (disconnectResponse.status !== 200) {
577
+ throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', new Error(disconnectResponse.statusText));
578
+ }
579
+ }
580
+ catch (error) {
581
+ throw new CloudInteropAPIError('Error during disconnection', 'ERR_DISCONNECT', error);
582
+ }
583
+ finally {
584
+ this.#destroyControllers();
585
+ this.#mqttClient?.removeAllListeners();
586
+ await this.#mqttClient?.endAsync(true);
587
+ this.#sessionDetails = undefined;
588
+ this.#mqttClient = undefined;
589
+ this.#reconnectRetries = 0;
590
+ this.#attemptingToReconnect = false;
591
+ if (fireDisconnectedEvent) {
592
+ this.#events.emitEvent('disconnected');
593
+ }
594
+ }
595
+ }
596
+ #handleMessage(topic, message, sessionDetails) {
597
+ if (message.length === 0 || !sessionDetails) {
598
+ // Ignore clean up messages
599
+ return;
600
+ }
601
+ const messageEnvelope = JSON.parse(message.toString());
602
+ if (topic.startsWith(`${sessionDetails.sessionRootTopic}/context-groups/`)) {
603
+ const contextEvent = messageEnvelope;
604
+ if (contextEvent.source.sessionId === sessionDetails.sessionId) {
605
+ return;
606
+ }
607
+ const { context, payload, contextGroup, channelName, source, history } = contextEvent;
608
+ this.#events.emitEvent('context', {
609
+ contextGroup: channelName || contextGroup,
610
+ context: payload || context,
611
+ source,
612
+ history: { ...history, clientReceived: Date.now() },
613
+ });
614
+ }
615
+ else if (topic.startsWith(`${sessionDetails.sessionRootTopic}/commands`)) {
616
+ this.#handleCommandMessage(messageEnvelope);
617
+ }
618
+ }
619
+ #handleCommandMessage(message) {
620
+ switch (message.command) {
621
+ case 'report-intents':
622
+ case 'intent-details':
623
+ case 'raise-intent':
624
+ case 'intent-result': {
625
+ this.#intents?.handleCommandMessage(message);
626
+ break;
627
+ }
628
+ default: {
629
+ this.#logger('warn', `Unknown command message received:\n${JSON.stringify(message, null, 2)}`);
630
+ break;
631
+ }
632
+ }
633
+ }
634
+ #validateConnectParams = (parameters) => {
635
+ if (!parameters) {
636
+ throw new Error('Connect parameters must be provided');
637
+ }
638
+ if (!parameters.sourceId) {
639
+ throw new Error('sourceId must be provided');
640
+ }
641
+ if (parameters.sourceId.includes(APP_ID_DELIM)) {
642
+ throw new Error(`sourceId cannot contain "${APP_ID_DELIM}"`);
643
+ }
644
+ if (!parameters.platformId) {
645
+ throw new Error('platformId must be provided');
646
+ }
647
+ if (parameters.authenticationType === 'jwt' &&
648
+ (!parameters.jwtAuthenticationParameters?.jwtRequestCallback || !parameters.jwtAuthenticationParameters?.authenticationId)) {
649
+ throw new Error('jwtAuthenticationParameters must be provided when using jwt authentication');
650
+ }
651
+ if (parameters.authenticationType === 'basic' &&
652
+ (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
653
+ throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
654
+ }
655
+ };
656
+ #initControllers(mqttClient, sessionDetails, connectionParameters) {
657
+ this.#intents = new IntentController(this.#cloudInteropSettings.url, mqttClient, sessionDetails, connectionParameters, this.#events, this.#logger);
658
+ }
659
+ #destroyControllers() {
660
+ this.#intents = undefined;
661
+ }
662
+ #throwIfNotConnected() {
663
+ if (!this.#sessionDetails || !this.#connectionParams) {
664
+ throw new Error('Session not connected');
665
+ }
666
+ if (!this.#mqttClient) {
667
+ throw new Error('MQTT client not connected');
668
+ }
669
+ }
670
+ /**
671
+ * Extracts the expiration timestamp from a JWT token.
672
+ *
673
+ * @param token - The JWT token string
674
+ * @returns The expiration timestamp in seconds, or null if extraction fails
675
+ */
676
+ #extractExpirationFromJwt(token) {
677
+ try {
678
+ // JWT tokens have three parts separated by dots: header.payload.signature
679
+ // The exp claim is in the payload
680
+ const parts = token.split('.');
681
+ if (parts.length < 2) {
682
+ this.#logger('warn', 'Invalid JWT token format: expected at least 2 parts');
683
+ return null;
684
+ }
685
+ const payload = parts[1];
686
+ // Decode base64url encoded payload
687
+ const decodedBytes = Buffer.from(l(payload), 'base64');
688
+ const payloadJson = decodedBytes.toString('utf8');
689
+ // Parse JSON to get the exp claim
690
+ const claims = JSON.parse(payloadJson);
691
+ const exp = claims.exp;
692
+ if (exp === undefined || exp === null) {
693
+ this.#logger('warn', "JWT token does not contain 'exp' claim");
694
+ return null;
695
+ }
696
+ if (typeof exp !== 'number') {
697
+ this.#logger('warn', `JWT token 'exp' claim is not a number: ${exp}`);
698
+ return null;
699
+ }
700
+ return exp;
701
+ }
702
+ catch (error) {
703
+ this.#logger('error', `Failed to extract expiration from JWT token: ${error instanceof Error ? error.message : error}`);
704
+ return null;
705
+ }
706
+ }
707
+ /**
708
+ * Start a session timer that will expire at the time specified in the JWT token's exp claim.
709
+ * When the timer fires, it executes the same actions as the BadUserNamePasswordError case.
710
+ */
711
+ #startSessionTimer() {
712
+ if (!this.#sessionDetails?.localSessionExpiryHandling) {
713
+ return;
714
+ }
715
+ const token = this.#sessionDetails.token;
716
+ if (!token) {
717
+ this.#logger('warn', 'Cannot start session timer: token not available');
718
+ return;
719
+ }
720
+ // Extract expiration time from JWT token
721
+ const expTimestamp = this.#extractExpirationFromJwt(token);
722
+ if (expTimestamp === null) {
723
+ this.#logger('warn', 'Cannot start session timer: could not extract expiration from JWT token');
724
+ return;
725
+ }
726
+ const currentTimeSeconds = Math.floor(Date.now() / 1000);
727
+ const delaySeconds = expTimestamp - currentTimeSeconds;
728
+ if (delaySeconds <= 0) {
729
+ this.#logger('warn', 'JWT token has already expired or expires immediately');
730
+ // Execute the same actions as BadUserNamePasswordError case
731
+ this.#handleSessionExpiry();
732
+ return;
733
+ }
734
+ // Clear any existing timer
735
+ if (this.#sessionTimer) {
736
+ clearTimeout(this.#sessionTimer);
737
+ }
738
+ const expirationTimeString = new Date(expTimestamp * 1000).toISOString();
739
+ this.#logger('debug', `Starting session timer to expire in ${delaySeconds} seconds (at ${expirationTimeString})`);
740
+ this.#sessionTimer = setTimeout(async () => {
741
+ this.#handleSessionExpiry();
742
+ }, delaySeconds * 1000);
743
+ }
744
+ /**
745
+ * Handles session expiry by executing the same actions as the BadUserNamePasswordError case.
746
+ */
747
+ async #handleSessionExpiry() {
748
+ await this.#disconnect(false);
749
+ this.#logger('warn', 'Session expired');
750
+ this.#events.emitEvent('session-expired');
751
+ }
752
+ }
753
+
754
+ export { AuthorizationError, CloudInteropAPI, CloudInteropAPIError };