@openfin/cloud-interop-core-api 0.0.1-alpha.fffeb9a → 10.0.0-beta.1d

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/package.json CHANGED
@@ -1,231 +1,18 @@
1
1
  {
2
- "name": "@openfin/cloud-interop-core-api",
3
- "version": "0.0.1-alpha.fffeb9a",
4
- "type": "module",
5
- "description": "",
6
- "files": [
7
- "./dist/*"
8
- ],
9
- "main": "./dist/index.cjs",
10
- "browser": "./dist/index.mjs",
11
- "types": "./dist/index.d.ts",
12
- "scripts": {
13
- "build": "rollup -c",
14
- "build:watch": "rollup -c --watch",
15
- "typecheck": "tsc --noEmit",
16
- "test": "jest --coverage",
17
- "lint": "eslint . --max-warnings 0",
18
- "lint:fix": "eslint . --fix --max-warnings 0"
19
- },
20
- "author": "",
21
- "license": "SEE LICENSE IN LICENSE.md",
22
- "devDependencies": {
23
- "@rollup/plugin-commonjs": "^28.0.1",
24
- "@rollup/plugin-inject": "^5.0.5",
25
- "@rollup/plugin-node-resolve": "^15.2.3",
26
- "@rollup/plugin-typescript": "^11.1.6",
27
- "@types/jest": "^29.5.14",
28
- "@types/node": "^20.10.0",
29
- "@typescript-eslint/eslint-plugin": "^7.5.0",
30
- "@typescript-eslint/parser": "^7.15.0",
31
- "eslint": "^8.57.0",
32
- "eslint-config-prettier": "^9.1.0",
33
- "eslint-plugin-check-file": "^2.8.0",
34
- "eslint-plugin-prettier": "^5.2.1",
35
- "eslint-plugin-simple-import-sort": "^12.1.1",
36
- "eslint-plugin-unicorn": "^55.0.0",
37
- "eslint-plugin-unused-imports": "^4.1.4",
38
- "jest": "^29.7.0",
39
- "prettier": "^3.3.3",
40
- "rollup": "^4.9.6",
41
- "ts-jest": "^29.2.5",
42
- "typescript": "^5.6.3"
43
- },
44
- "dependencies": {
45
- "axios": "^1.6.2",
46
- "mqtt": "^5.3.1"
47
- },
48
- "eslintConfig": {
49
- "env": {
50
- "browser": true,
51
- "node": true
52
- },
53
- "parser": "@typescript-eslint/parser",
54
- "parserOptions": {
55
- "ecmaVersion": "latest",
56
- "project": true,
57
- "sourceType": "module"
58
- },
59
- "extends": [
60
- "eslint:recommended",
61
- "plugin:@typescript-eslint/recommended",
62
- "plugin:@typescript-eslint/strict",
63
- "plugin:unicorn/recommended",
64
- "plugin:prettier/recommended"
65
- ],
66
- "plugins": [
67
- "prettier",
68
- "check-file",
69
- "simple-import-sort",
70
- "unused-imports"
71
- ],
72
- "rules": {
73
- "unused-imports/no-unused-imports": "warn",
74
- "unicorn/prevent-abbreviations": [
75
- "error",
76
- {
77
- "replacements": {
78
- "props": false,
79
- "prop": false,
80
- "ref": false,
81
- "args": false,
82
- "arg": false,
83
- "src": false,
84
- "dev": false,
85
- "str": false,
86
- "req": false,
87
- "res": false
88
- }
89
- }
90
- ],
91
- "@typescript-eslint/no-non-null-assertion": "error",
92
- "unicorn/no-nested-ternary": "off",
93
- "unicorn/no-array-for-each": "off",
94
- "unicorn/no-useless-undefined": "off",
95
- "unicorn/no-null": "off",
96
- "eqeqeq": [
97
- "error",
98
- "always"
99
- ],
100
- "no-alert": "error",
101
- "no-eval": "error",
102
- "prettier/prettier": "warn",
103
- "simple-import-sort/imports": [
104
- "error",
105
- {
106
- "groups": [
107
- [
108
- "^react$"
109
- ],
110
- [
111
- "^react"
112
- ],
113
- [
114
- "^next"
115
- ],
116
- [
117
- "^zod"
118
- ],
119
- [
120
- "^@radix-ui/"
121
- ],
122
- [
123
- "^[^.]"
124
- ],
125
- [
126
- "@/components/ui/.*"
127
- ],
128
- [
129
- "@/components/.*"
130
- ],
131
- [
132
- "@/config/.*"
133
- ],
134
- [
135
- "@/lib/.*"
136
- ],
137
- [
138
- "^\\.\\.(?!/?$)",
139
- "^\\.\\./?$"
140
- ],
141
- [
142
- "^\\./(?=.*/)(?!/?$)",
143
- "^\\.(?!/?$)",
144
- "^\\./?$"
145
- ],
146
- [
147
- "^.+\\.s?css$"
148
- ]
149
- ]
150
- }
151
- ],
152
- "check-file/no-index": "off",
153
- "check-file/filename-naming-convention": [
154
- "error",
155
- {
156
- "**/*.{jsx,tsx}": "KEBAB_CASE",
157
- "**/*.{js,ts}": "KEBAB_CASE"
158
- },
159
- {
160
- "ignoreMiddleExtensions": true
161
- }
162
- ],
163
- "check-file/filename-blocklist": [
164
- "error",
165
- {
166
- "**/*.spec.js": "*.test.js",
167
- "**/*.spec.jsx": "*.test.jsx",
168
- "**/*.spec.ts": "*.test.ts",
169
- "**/*.spec.tsx": "*.test.tsx"
170
- }
171
- ],
172
- "no-restricted-syntax": [
173
- "error",
174
- {
175
- "selector": "TSEnumDeclaration",
176
- "message": "Prefer string unions to enums."
177
- }
178
- ],
179
- "curly": [
180
- "error",
181
- "multi-line"
182
- ],
183
- "@typescript-eslint/consistent-type-definitions": [
184
- "error",
185
- "type"
186
- ],
187
- "@typescript-eslint/no-unused-vars": [
188
- "warn",
189
- {
190
- "argsIgnorePattern": "^_",
191
- "varsIgnorePattern": "^_"
192
- }
193
- ],
194
- "@typescript-eslint/no-explicit-any": "warn"
195
- },
196
- "ignorePatterns": [
197
- "node_modules",
198
- "out",
199
- "build",
200
- "dist",
201
- "coverage",
202
- "tests",
203
- "rollup.config.mjs",
204
- "examples"
205
- ]
206
- },
207
- "jest": {
208
- "collectCoverage": true,
209
- "collectCoverageFrom": [
210
- "src/**/*.ts"
211
- ],
212
- "coverageReporters": [
213
- "lcov",
214
- "text-summary"
215
- ],
216
- "preset": "ts-jest",
217
- "restoreMocks": true,
218
- "setupFiles": [],
219
- "testMatch": [
220
- "**/tests/*.test.ts"
221
- ],
222
- "testTimeout": 100000
223
- },
224
- "prettier": {
225
- "printWidth": 160,
226
- "semi": true,
227
- "singleQuote": true,
228
- "tabWidth": 4,
229
- "trailingComma": "all"
230
- }
231
- }
2
+ "name": "@openfin/cloud-interop-core-api",
3
+ "version": "10.0.0-beta.1d",
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
+ "dependencies": {
12
+ "mqtt": "^5.13.0",
13
+ "zod": "^3.24.4"
14
+ },
15
+ "optionalDependencies": {
16
+ "@rollup/rollup-linux-x64-gnu": "*"
17
+ }
18
+ }
package/dist/api.d.ts DELETED
@@ -1,63 +0,0 @@
1
- import mqtt from 'mqtt';
2
- import { CloudInteropSettings, ConnectParameters as ConnectParameters, ContextEvent } from './interfaces';
3
- type CreateSessionResponse = {
4
- sessionId: string;
5
- sessionRootTopic: string;
6
- url: string;
7
- token: string;
8
- orgId: string;
9
- sub: string;
10
- platformId: string;
11
- sourceId: string;
12
- };
13
- type EventMap = {
14
- reconnected: () => void;
15
- disconnected: () => void;
16
- context: (event: ContextEvent) => void;
17
- reconnecting: (attemptNo: number) => void;
18
- error: (error: Error) => void;
19
- 'session-expired': () => void;
20
- };
21
- /**
22
- * Represents a single connection to a Cloud Interop service
23
- *
24
- * @export
25
- * @class CloudInteropAPI
26
- * @implements {Client}
27
- */
28
- export declare class CloudInteropAPI {
29
- #private;
30
- constructor(cloudInteropSettings: CloudInteropSettings);
31
- get sessionDetails(): CreateSessionResponse | undefined;
32
- get mqttClient(): mqtt.MqttClient | undefined;
33
- /**
34
- * Connects and creates a session on the Cloud Interop service
35
- *
36
- * @param {ConnectParameters} parameters - The parameters to use to connect
37
- * @return {*} {Promise<void>}
38
- * @memberof CloudInteropAPI
39
- * @throws {CloudInteropAPIError} - If an error occurs during connection
40
- * @throws {AuthorizationError} - If the connection is unauthorized
41
- */
42
- connect(parameters: ConnectParameters): Promise<void>;
43
- /**
44
- * Disconnects from the Cloud Interop service
45
- *
46
- * @return {*} {Promise<void>}
47
- * @memberof CloudInteropAPI
48
- * @throws {CloudInteropAPIError} - If an error occurs during disconnection
49
- */
50
- disconnect(): Promise<void>;
51
- /**
52
- * Publishes a new context for the given context group to the other connected sessions
53
- *
54
- * @param {string} contextGroup - The context group to publish to
55
- * @param {object} context - The context to publish
56
- * @return {*} {Promise<void>}
57
- * @memberof CloudInteropAPI
58
- */
59
- setContext(contextGroup: string, context: object): Promise<void>;
60
- addEventListener<K extends keyof EventMap>(type: K, callback: EventMap[K]): void;
61
- removeEventListener<K extends keyof EventMap>(type: K, callback: EventMap[K]): void;
62
- }
63
- export {};
@@ -1,7 +0,0 @@
1
- export declare class CloudInteropAPIError extends Error {
2
- code: string;
3
- constructor(message?: string, code?: string, cause?: unknown);
4
- }
5
- export declare class AuthorizationError extends CloudInteropAPIError {
6
- constructor(message?: string, code?: string);
7
- }
package/dist/index.cjs DELETED
@@ -1,290 +0,0 @@
1
- 'use strict';
2
-
3
- var axios = require('axios');
4
- var mqtt = require('mqtt');
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
- // Error codes as defined in https://docs.emqx.com/en/cloud/latest/connect_to_deployments/mqtt_client_error_codes.html
21
- const BadUserNamePasswordError = 134;
22
- /**
23
- * Represents a single connection to a Cloud Interop service
24
- *
25
- * @export
26
- * @class CloudInteropAPI
27
- * @implements {Client}
28
- */
29
- class CloudInteropAPI {
30
- #cloudInteropSettings;
31
- #sessionDetails;
32
- #mqttClient;
33
- #reconnectRetryLimit = 30;
34
- #logger = (level, message) => {
35
- console[level](message);
36
- };
37
- #reconnectRetries = 0;
38
- #connectionParams;
39
- #eventListeners = new Map();
40
- #attemptingToReconnect = false;
41
- constructor(cloudInteropSettings) {
42
- this.#cloudInteropSettings = cloudInteropSettings;
43
- }
44
- get sessionDetails() {
45
- return this.#sessionDetails;
46
- }
47
- get mqttClient() {
48
- return this.#mqttClient;
49
- }
50
- /**
51
- * Connects and creates a session on the Cloud Interop service
52
- *
53
- * @param {ConnectParameters} parameters - The parameters to use to connect
54
- * @return {*} {Promise<void>}
55
- * @memberof CloudInteropAPI
56
- * @throws {CloudInteropAPIError} - If an error occurs during connection
57
- * @throws {AuthorizationError} - If the connection is unauthorized
58
- */
59
- async connect(parameters) {
60
- this.#validateConnectParams(parameters);
61
- this.#connectionParams = parameters;
62
- this.#reconnectRetryLimit = parameters.reconnectRetryLimit || this.#reconnectRetryLimit;
63
- this.#logger = parameters.logger || this.#logger;
64
- const { sourceId, platformId } = this.#connectionParams;
65
- try {
66
- const createSessionResponse = await axios.post(`${this.#cloudInteropSettings.url}/api/sessions`, {
67
- sourceId,
68
- platformId,
69
- }, {
70
- headers: this.#getRequestHeaders(),
71
- });
72
- if (createSessionResponse.status !== 201) {
73
- throw new CloudInteropAPIError(`Failed to connect to the Cloud Interop service: ${this.#cloudInteropSettings.url}`, 'ERR_CONNECT', createSessionResponse.status);
74
- }
75
- this.#sessionDetails = createSessionResponse.data;
76
- const sessionRootTopic = this.#sessionDetails.sessionRootTopic;
77
- const clientOptions = {
78
- clientId: this.#sessionDetails.sessionId,
79
- clean: true,
80
- protocolVersion: 5,
81
- // The "will" message will be published on an unexpected disconnection
82
- // The server can then tidy up. So it needs every for this client to do that, the session details is perfect
83
- will: {
84
- topic: 'interop/lastwill',
85
- payload: Buffer.from(JSON.stringify(this.#sessionDetails)),
86
- qos: 0,
87
- retain: false,
88
- },
89
- username: this.#sessionDetails.token,
90
- };
91
- this.#mqttClient = await mqtt.connectAsync(this.#sessionDetails.url, clientOptions);
92
- this.#logger('log', `Cloud Interop successfully connected to ${this.#cloudInteropSettings.url}`);
93
- this.#mqttClient.on('error', async (error) => {
94
- // We will receive errors for each failed reconnection attempt
95
- // We don't won't to disconnect on these else we will never reconnect
96
- if (!this.#attemptingToReconnect) {
97
- await this.#disconnect(false);
98
- }
99
- if (error instanceof mqtt.ErrorWithReasonCode) {
100
- switch (error.code) {
101
- case BadUserNamePasswordError: {
102
- await this.#disconnect(false);
103
- this.#logger('warn', `Session expired`);
104
- this.#emitEvent('session-expired');
105
- return;
106
- }
107
- default: {
108
- this.#logger('error', `Unknown Infrastructure Error Code ${error.code} : ${error.message}${this.#attemptingToReconnect ? ' during reconnection attempt' : ''}`);
109
- // As we are in the middle of a reconnect, lets not emit an error to cut down on the event noise
110
- if (!this.#attemptingToReconnect) {
111
- this.#emitEvent('error', new CloudInteropAPIError(`Unknown Infrastructure Error Code ${error.code} : ${error.message}`, 'ERR_INFRASTRUCTURE', error));
112
- break;
113
- }
114
- }
115
- }
116
- }
117
- else {
118
- this.#logger('error', `Unknown Error${this.#attemptingToReconnect ? ' during reconnection attempt' : ''}: ${error}`);
119
- // As we are in the middle of a reconnect, lets not emit an error to cut down on the event noise
120
- if (!this.#attemptingToReconnect) {
121
- this.#emitEvent('error', new CloudInteropAPIError(`Unknown Error`, 'ERR_UNKNOWN', error));
122
- }
123
- }
124
- });
125
- this.#mqttClient.on('reconnect', () => {
126
- this.#attemptingToReconnect = true;
127
- this.#reconnectRetries += 1;
128
- this.#logger('debug', `Cloud Interop attempting reconnection - ${this.#reconnectRetries}...`);
129
- if (this.#reconnectRetries === this.#reconnectRetryLimit) {
130
- this.#logger('warn', `Cloud Interop reached max reconnection attempts - ${this.#reconnectRetryLimit}...`);
131
- this.#disconnect(true);
132
- }
133
- this.#emitEvent('reconnecting', this.#reconnectRetries);
134
- });
135
- // Does not fire on initial connection, only successful reconnection attempts
136
- this.#mqttClient.on('connect', () => {
137
- this.#logger('debug', `Cloud Interop successfully reconnected after ${this.#reconnectRetries} attempts`);
138
- this.#reconnectRetries = 0;
139
- this.#attemptingToReconnect = false;
140
- this.#emitEvent('reconnected');
141
- });
142
- this.#mqttClient.on('message', (topic, message) => {
143
- if (!this.#sessionDetails) {
144
- this.#logger('warn', 'Received message when session not connected');
145
- return;
146
- }
147
- this.#handleCommand(topic, message, this.#sessionDetails);
148
- });
149
- // Subscribe to all context groups
150
- this.#mqttClient.subscribe(`${sessionRootTopic}/context-groups/#`);
151
- // Listen out for global commands
152
- this.#mqttClient.subscribe(`${sessionRootTopic}/commands`);
153
- }
154
- catch (error) {
155
- if (axios.isAxiosError(error)) {
156
- if (error.response?.status === 401 || error.response?.status === 403) {
157
- throw new AuthorizationError();
158
- }
159
- throw new CloudInteropAPIError();
160
- }
161
- throw error;
162
- }
163
- }
164
- /**
165
- * Disconnects from the Cloud Interop service
166
- *
167
- * @return {*} {Promise<void>}
168
- * @memberof CloudInteropAPI
169
- * @throws {CloudInteropAPIError} - If an error occurs during disconnection
170
- */
171
- async disconnect() {
172
- await this.#disconnect(true);
173
- }
174
- /**
175
- * Publishes a new context for the given context group to the other connected sessions
176
- *
177
- * @param {string} contextGroup - The context group to publish to
178
- * @param {object} context - The context to publish
179
- * @return {*} {Promise<void>}
180
- * @memberof CloudInteropAPI
181
- */
182
- async setContext(contextGroup, context) {
183
- if (!this.#sessionDetails || !this.#connectionParams) {
184
- throw new Error('Session not connected');
185
- }
186
- const payload = {
187
- context,
188
- timestamp: Date.now(),
189
- };
190
- await axios.post(`${this.#cloudInteropSettings.url}/api/context-groups/${this.#sessionDetails.sessionId}/${contextGroup}`, payload, {
191
- headers: this.#getRequestHeaders(),
192
- });
193
- }
194
- addEventListener(type, callback) {
195
- const listeners = this.#eventListeners.get(type) || [];
196
- listeners.push(callback);
197
- this.#eventListeners.set(type, listeners);
198
- }
199
- removeEventListener(type, callback) {
200
- const listeners = this.#eventListeners.get(type) || [];
201
- const index = listeners.indexOf(callback);
202
- if (index !== -1) {
203
- listeners.splice(index, 1);
204
- }
205
- this.#eventListeners.set(type, listeners);
206
- }
207
- async #disconnect(fireDisconnectedEvent) {
208
- if (!this.#sessionDetails) {
209
- return;
210
- }
211
- try {
212
- const disconnectResponse = await axios.delete(`${this.#cloudInteropSettings.url}/api/sessions/${this.#sessionDetails.sessionId}`, {
213
- headers: this.#getRequestHeaders(),
214
- });
215
- if (disconnectResponse.status !== 200) {
216
- throw new CloudInteropAPIError('Error during session tear down - unexpected status', 'ERR_DISCONNECT', disconnectResponse.status);
217
- }
218
- }
219
- catch {
220
- throw new CloudInteropAPIError('Error during disconnection', 'ERR_DISCONNECT');
221
- }
222
- finally {
223
- this.#mqttClient?.removeAllListeners();
224
- await this.#mqttClient?.endAsync(true);
225
- this.#sessionDetails = undefined;
226
- this.#mqttClient = undefined;
227
- this.#reconnectRetries = 0;
228
- this.#attemptingToReconnect = false;
229
- if (fireDisconnectedEvent) {
230
- this.#emitEvent('disconnected');
231
- }
232
- }
233
- }
234
- #handleCommand(topic, message, sessionDetails) {
235
- if (message.length === 0 || !sessionDetails) {
236
- // Ignore clean up messages
237
- return;
238
- }
239
- const messageEnvelope = JSON.parse(message.toString());
240
- if (topic.startsWith(`${sessionDetails.sessionRootTopic}/context-groups/`)) {
241
- if (messageEnvelope.source.sessionId === sessionDetails.sessionId) {
242
- return;
243
- }
244
- const { channelName: contextGroup, payload: context, source, history } = messageEnvelope;
245
- this.#emitEvent('context', { contextGroup, context, source, history: { ...history, clientReceived: Date.now() } });
246
- }
247
- }
248
- #emitEvent(type, ...args) {
249
- const listeners = this.#eventListeners.get(type) || [];
250
- listeners.forEach((listener) => listener(...args));
251
- }
252
- #validateConnectParams = (parameters) => {
253
- if (!parameters) {
254
- throw new Error('Connect parameters must be provided');
255
- }
256
- if (parameters.authenticationType === 'jwt' &&
257
- (!parameters.jwtAuthenticationParameters?.jwtRequestCallback || !parameters.jwtAuthenticationParameters?.authenticationId)) {
258
- throw new Error('jwtAuthenticationParameters must be provided when using jwt authentication');
259
- }
260
- if (parameters.authenticationType === 'basic' &&
261
- (!parameters.basicAuthenticationParameters?.username || !parameters.basicAuthenticationParameters?.password)) {
262
- throw new Error('basicAuthenticationParameters must be provided when using basic authentication');
263
- }
264
- };
265
- #getRequestHeaders = () => {
266
- if (!this.#connectionParams) {
267
- throw new Error('Connect parameters must be provided');
268
- }
269
- const headers = new axios.AxiosHeaders();
270
- headers['Content-Type'] = 'application/json';
271
- if (this.#connectionParams.authenticationType === 'jwt' && this.#connectionParams.jwtAuthenticationParameters) {
272
- const tokenResult = this.#connectionParams.jwtAuthenticationParameters.jwtRequestCallback();
273
- if (!tokenResult) {
274
- throw new Error('jwtRequestCallback must return a token');
275
- }
276
- headers['x-of-auth-id'] = this.#connectionParams.jwtAuthenticationParameters.authenticationId;
277
- headers['Authorization'] =
278
- typeof tokenResult === 'string' ? `Bearer ${tokenResult}` : `Bearer ${Buffer.from(JSON.stringify(tokenResult)).toString('base64')}`;
279
- }
280
- if (this.#connectionParams.authenticationType === 'basic' && this.#connectionParams.basicAuthenticationParameters) {
281
- const { username, password } = this.#connectionParams.basicAuthenticationParameters;
282
- headers['Authorization'] = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
283
- }
284
- return headers;
285
- };
286
- }
287
-
288
- exports.AuthorizationError = AuthorizationError;
289
- exports.CloudInteropAPI = CloudInteropAPI;
290
- exports.CloudInteropAPIError = CloudInteropAPIError;
package/dist/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export * from './api';
2
- export * from './errors/api.error';
3
- export * from './interfaces';