@openfin/cloud-interop-core-api 0.0.1-alpha.0034b20

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