@openfin/cloud-interop-core-api 0.0.1-alpha.f23e349 → 0.0.1-alpha.f2bb355

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