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

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