@eka-care/medassist-core 1.0.70 → 1.0.71

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.
Files changed (94) hide show
  1. package/dist/index.d.mts +1442 -0
  2. package/dist/index.mjs +2 -0
  3. package/dist/messages/types.d.ts +1 -0
  4. package/package.json +1 -1
  5. package/dist/Synapse.d.ts.map +0 -1
  6. package/dist/connection/ConnectionFactory.d.ts.map +0 -1
  7. package/dist/connection/SSE.d.ts.map +0 -1
  8. package/dist/connection/Websocket.d.ts.map +0 -1
  9. package/dist/constants/index.d.ts.map +0 -1
  10. package/dist/constants/types.d.ts.map +0 -1
  11. package/dist/conversation.d.ts.map +0 -1
  12. package/dist/esm/Synapse.js +0 -612
  13. package/dist/esm/connection/ConnectionFactory.js +0 -27
  14. package/dist/esm/connection/SSE.js +0 -212
  15. package/dist/esm/connection/Websocket.js +0 -178
  16. package/dist/esm/constants/index.js +0 -25
  17. package/dist/esm/constants/types.js +0 -1
  18. package/dist/esm/conversation.js +0 -7
  19. package/dist/esm/events/Events.js +0 -41
  20. package/dist/esm/events/Incoming.js +0 -1
  21. package/dist/esm/events/Outgoing.js +0 -1
  22. package/dist/esm/events/index.js +0 -2
  23. package/dist/esm/events/types.js +0 -5
  24. package/dist/esm/index.js +0 -34
  25. package/dist/esm/internal/Api/BaseResource.js +0 -50
  26. package/dist/esm/internal/Api/HttpClient.js +0 -131
  27. package/dist/esm/internal/Api/types.js +0 -1
  28. package/dist/esm/internal/Error/Error.js +0 -229
  29. package/dist/esm/internal/Error/types.js +0 -9
  30. package/dist/esm/internal/connection/BaseConnection.js +0 -134
  31. package/dist/esm/internal/connection/types.js +0 -17
  32. package/dist/esm/internal/events/EventEmitter.js +0 -26
  33. package/dist/esm/internal/store/index.js +0 -5
  34. package/dist/esm/media/audio/Audio.copy.js +0 -363
  35. package/dist/esm/media/audio/Audio.js +0 -310
  36. package/dist/esm/media/audio/types.js +0 -13
  37. package/dist/esm/media/file/File.js +0 -159
  38. package/dist/esm/messages/MessageManager.js +0 -476
  39. package/dist/esm/messages/types.js +0 -35
  40. package/dist/esm/resources/config/Config.js +0 -11
  41. package/dist/esm/resources/feedback/Feedback.js +0 -9
  42. package/dist/esm/resources/feedback/types.js +0 -7
  43. package/dist/esm/resources/index.js +0 -152
  44. package/dist/esm/resources/session/Session.js +0 -44
  45. package/dist/esm/resources/session/types.js +0 -5
  46. package/dist/esm/resources/toolCall/ToolCall.js +0 -12
  47. package/dist/esm/resources/toolCall/types.js +0 -34
  48. package/dist/esm/resources/types.js +0 -4
  49. package/dist/esm/resources/voice/VoiceResource.js +0 -14
  50. package/dist/esm/resources/voice/types.js +0 -1
  51. package/dist/esm/types/index.js +0 -8
  52. package/dist/esm/utils/Error.js +0 -110
  53. package/dist/esm/voice/VoiceAgent.js +0 -305
  54. package/dist/esm/voice/VoiceAudioAnalyser.js +0 -32
  55. package/dist/esm/voice/index.js +0 -1
  56. package/dist/esm/voice/types.js +0 -15
  57. package/dist/events/Events.d.ts.map +0 -1
  58. package/dist/events/Incoming.d.ts.map +0 -1
  59. package/dist/events/Outgoing.d.ts.map +0 -1
  60. package/dist/events/index.d.ts.map +0 -1
  61. package/dist/events/types.d.ts.map +0 -1
  62. package/dist/index.d.ts.map +0 -1
  63. package/dist/internal/Api/BaseResource.d.ts.map +0 -1
  64. package/dist/internal/Api/HttpClient.d.ts.map +0 -1
  65. package/dist/internal/Api/types.d.ts.map +0 -1
  66. package/dist/internal/Error/Error.d.ts.map +0 -1
  67. package/dist/internal/Error/types.d.ts.map +0 -1
  68. package/dist/internal/connection/BaseConnection.d.ts.map +0 -1
  69. package/dist/internal/connection/types.d.ts.map +0 -1
  70. package/dist/internal/events/EventEmitter.d.ts.map +0 -1
  71. package/dist/internal/store/index.d.ts.map +0 -1
  72. package/dist/media/audio/Audio.copy.d.ts.map +0 -1
  73. package/dist/media/audio/Audio.d.ts.map +0 -1
  74. package/dist/media/audio/types.d.ts.map +0 -1
  75. package/dist/media/file/File.d.ts.map +0 -1
  76. package/dist/messages/MessageManager.d.ts.map +0 -1
  77. package/dist/messages/types.d.ts.map +0 -1
  78. package/dist/resources/config/Config.d.ts.map +0 -1
  79. package/dist/resources/feedback/Feedback.d.ts.map +0 -1
  80. package/dist/resources/feedback/types.d.ts.map +0 -1
  81. package/dist/resources/index.d.ts.map +0 -1
  82. package/dist/resources/session/Session.d.ts.map +0 -1
  83. package/dist/resources/session/types.d.ts.map +0 -1
  84. package/dist/resources/toolCall/ToolCall.d.ts.map +0 -1
  85. package/dist/resources/toolCall/types.d.ts.map +0 -1
  86. package/dist/resources/types.d.ts.map +0 -1
  87. package/dist/resources/voice/VoiceResource.d.ts.map +0 -1
  88. package/dist/resources/voice/types.d.ts.map +0 -1
  89. package/dist/types/index.d.ts.map +0 -1
  90. package/dist/utils/Error.d.ts.map +0 -1
  91. package/dist/voice/VoiceAgent.d.ts.map +0 -1
  92. package/dist/voice/VoiceAudioAnalyser.d.ts.map +0 -1
  93. package/dist/voice/index.d.ts.map +0 -1
  94. package/dist/voice/types.d.ts.map +0 -1
@@ -1,612 +0,0 @@
1
- /**
2
- * High-level SynapseSDK API
3
- * Provides a simple interface for managing chat sessions
4
- */
5
- import { ConnectionFactory, ConnectionType, } from "./connection/ConnectionFactory";
6
- import { DisconnectionReason, } from "./internal/connection/types";
7
- import { getConfig } from "./constants";
8
- import { ResourceManager } from "./resources";
9
- // import { type AgentConfig } from "./resources/types";
10
- import { MessageManager } from "./messages/MessageManager";
11
- import { SYNAPSE_REALTIME_EVENTS, SYNAPSE_REALTIME_RESERVED_EVENTS, } from "./messages/types";
12
- import { EventEmitter } from "./internal/events/EventEmitter";
13
- import { ErrorUtils } from "./utils/Error";
14
- import { APIError,
15
- // AuthenticationError,
16
- ConnectionError, MessageError, NotFoundError,
17
- // RecordingError,
18
- SessionError, SynapseError, normalizeError, } from "./internal/Error/Error";
19
- import { SOCKET_EVENTS, } from "./events/Events";
20
- import { VoiceAgent } from "./voice/VoiceAgent";
21
- //TODO: Fix issue with handling error content type ,which is comming as a connection error to the user
22
- export class SynapseSDK {
23
- connection = null;
24
- messageManager;
25
- resourceManager;
26
- // private agentConfig: AgentConfig | null = null;
27
- sessionConfig = null;
28
- config;
29
- connectionType;
30
- isRefreshingSession = false;
31
- connectionAttempts = 0;
32
- sdkEventEmitter = new EventEmitter();
33
- _voice = null;
34
- constructor(config) {
35
- this.config = {
36
- ...config,
37
- environment: config.environment || "production",
38
- };
39
- this.connectionType = config.connectionType || ConnectionType.SSE; //by default use SSE, can be overridden by config
40
- const API_ORIGIN = getConfig(this.config?.environment).BASE_API_URL;
41
- this.resourceManager = new ResourceManager({
42
- agentId: this.config.agentId,
43
- serverUrl: this.config.serverUrl || API_ORIGIN, //based on environment
44
- ...(this.config.auth && { authorization: this.config.auth }),
45
- ...(this.config.authToken && { authToken: this.config.authToken }),
46
- });
47
- this.messageManager = new MessageManager(this.config?.callbacks);
48
- }
49
- /**
50
- * Start the session
51
- * if existing session is provided, it will be validated and refreshed
52
- * if no existing session is provided, a new session will be created
53
- * then the connection will be initialized and event handlers will be setup
54
- * return the session response
55
- */
56
- async startSession(existingSession) {
57
- try {
58
- const sessionResponse = await this.manageSession(existingSession);
59
- await this.initializeConnection(sessionResponse);
60
- this.setupEventHandlers();
61
- return sessionResponse;
62
- }
63
- catch (error) {
64
- const userFriendlyMessage = ErrorUtils.getUserFriendlyMessage(error);
65
- const errorDetails = ErrorUtils.getErrorDetails(error);
66
- if (error instanceof APIError) {
67
- if (error.status === 404 || error.status === 403) {
68
- throw error;
69
- }
70
- }
71
- const sessionError = this.toSessionError(error, userFriendlyMessage || "Failed to start session", {
72
- stage: "startSession",
73
- details: errorDetails,
74
- }, "Check network connectivity or recheck credentials before retrying.");
75
- this.emitError(sessionError);
76
- throw sessionError;
77
- }
78
- }
79
- /**
80
- * Send a message conetnt will be text always
81
- */
82
- async sendMessage({ message, files, audio, tool_declined, tool_id, initial_prompts, tool_result }) {
83
- switch (this.connectionType) {
84
- case ConnectionType.SOCKET:
85
- case ConnectionType.SSE:
86
- this.messageManager.sendSocketMessage({
87
- message: message,
88
- files: files,
89
- audio: audio,
90
- ...(tool_declined && { tool_declined }),
91
- ...(tool_id && { tool_id }),
92
- ...(initial_prompts?.length && { initial_prompts }),
93
- ...(tool_result && Object.keys(tool_result)?.length && { tool_result })
94
- });
95
- break;
96
- default:
97
- const error = new ConnectionError("Unsupported connection type", {
98
- context: {
99
- stage: "sendChatMessage",
100
- connectionType: this.connectionType,
101
- },
102
- });
103
- this.emitError(error);
104
- throw error;
105
- }
106
- }
107
- /**
108
- * Send feedback on a message
109
- */
110
- async sendFeedback(messageId, feedback, reason) {
111
- if (!this.connection) {
112
- const error = new ConnectionError("Connection not established. Session may not be initialized.", {
113
- context: { stage: "sendFeedback" },
114
- hint: "Call startSession() before attempting to send feedback.",
115
- });
116
- this.emitError(error);
117
- throw error;
118
- }
119
- if (!this.sessionConfig?.session_id) {
120
- const error = new SessionError("Session ID not found", {
121
- context: { stage: "sendFeedback" },
122
- hint: "Call startSession() before attempting to send feedback.",
123
- });
124
- this.emitError(error);
125
- throw error;
126
- }
127
- switch (this.connectionType) {
128
- case ConnectionType.SOCKET:
129
- case ConnectionType.SSE:
130
- await this.resourceManager.sendFeedback(this.sessionConfig.session_id, messageId, feedback, reason);
131
- break;
132
- }
133
- }
134
- /**
135
- * Register a listener for a specific event
136
- */
137
- on(event, listener) {
138
- this.sdkEventEmitter.on(event, listener);
139
- }
140
- /**
141
- * Remove a listener for a specific event
142
- */
143
- off(event, listener) {
144
- this.sdkEventEmitter.off(event, listener);
145
- }
146
- /**
147
- * Get the session ID
148
- */
149
- getSessionConfig() {
150
- if (!this.sessionConfig?.session_id || !this.sessionConfig?.session_token) {
151
- throw new SessionError("Session ID or token not found", {
152
- context: { stage: "getSessionConfig" },
153
- hint: "Ensure the session API returns both identifiers.",
154
- });
155
- }
156
- return this.sessionConfig;
157
- }
158
- /**
159
- * Call tool
160
- */
161
- async callTool(tool_id, message_id, params) {
162
- if (!this.connection) {
163
- const error = new ConnectionError("Connection not established. Session may not be initialized.", {
164
- context: { stage: "callTool" },
165
- hint: "Call startSession() before attempting to call tool.",
166
- });
167
- this.emitError(error);
168
- throw error;
169
- }
170
- if (!this.sessionConfig?.session_id || !this.sessionConfig?.session_token) {
171
- const error = new SessionError("Session ID not found", {
172
- context: { stage: "callTool" },
173
- hint: "Call startSession() before attempting to call tool.",
174
- });
175
- this.emitError(error);
176
- throw error;
177
- }
178
- switch (this.connectionType) {
179
- case ConnectionType.SOCKET:
180
- case ConnectionType.SSE:
181
- try {
182
- const response = await this.resourceManager.callTool(this.sessionConfig.session_id, tool_id, message_id, this.sessionConfig.session_token, params);
183
- if (response.error) {
184
- throw new APIError(response.error.msg, 500, response.error);
185
- }
186
- let cleanedResponse = {
187
- data: { ...response.data },
188
- messageId: response._id,
189
- timestamp: response.ts,
190
- };
191
- this.connection.emit(SYNAPSE_REALTIME_EVENTS.TOOL_CALL, cleanedResponse);
192
- }
193
- catch (error) {
194
- if (error instanceof APIError && error?.status === 401) {
195
- await this.handleSessionExpiry();
196
- return await this.callTool(tool_id, message_id, params);
197
- }
198
- throw error;
199
- }
200
- break;
201
- default:
202
- const error = new ConnectionError("Unsupported connection type", {
203
- context: { stage: "callTool", connectionType: this.connectionType },
204
- });
205
- this.emitError(error);
206
- throw error;
207
- }
208
- }
209
- /**
210
- * Send audio
211
- * */
212
- async startRecording({ onChunks, onError, }) {
213
- switch (this.connectionType) {
214
- case ConnectionType.SOCKET:
215
- case ConnectionType.SSE:
216
- try {
217
- await this.messageManager.startRecording({
218
- onChunks,
219
- onError,
220
- });
221
- }
222
- catch (error) {
223
- throw error;
224
- }
225
- break;
226
- default:
227
- const error = new ConnectionError("Unsupported connection type", {
228
- context: { stage: "sendAudio", connectionType: this.connectionType },
229
- });
230
- this.emitError(error);
231
- throw error;
232
- }
233
- }
234
- /**
235
- * Stop recording audio
236
- */
237
- endRecording() {
238
- switch (this.connectionType) {
239
- case ConnectionType.SOCKET:
240
- case ConnectionType.SSE:
241
- this.messageManager.endRecordingWithSocket();
242
- break;
243
- default:
244
- const error = new ConnectionError("Unsupported connection type", {
245
- context: {
246
- stage: "endRecording",
247
- connectionType: this.connectionType,
248
- },
249
- });
250
- this.emitError(error);
251
- throw error;
252
- }
253
- }
254
- // /**
255
- // * Get the agent configuration
256
- // */
257
- async getAgentConfig() {
258
- return this.resourceManager.getAgentConfig();
259
- }
260
- isConnected() {
261
- return this.connection?.isConnected() ?? false;
262
- }
263
- get voice() {
264
- if (!this._voice) {
265
- this._voice = new VoiceAgent(this.buildVoiceConfig(), this.resourceManager, async () => {
266
- const session = await this.resourceManager.createSession();
267
- return {
268
- sessionId: session.session_id,
269
- sessionToken: session.session_token,
270
- };
271
- });
272
- }
273
- return this._voice;
274
- }
275
- /**
276
- * End the session
277
- */
278
- endSession() {
279
- this._voice?.destroy();
280
- this._voice = null;
281
- this.closeConnection();
282
- this.cleanup();
283
- }
284
- buildVoiceConfig() {
285
- const base = this.config.serverUrl ||
286
- getConfig(this.config.environment).BASE_API_URL;
287
- return {
288
- offerUrl: `${base}/med-assist/voice/offer`,
289
- handleRefresh: async () => {
290
- await this.handleSessionExpiry();
291
- },
292
- };
293
- }
294
- toClientError(error) {
295
- if (error instanceof APIError) {
296
- return {
297
- message: (error.error?.msg) || error.message,
298
- error: error.error,
299
- code: error.code,
300
- status: error.status,
301
- context: error.context,
302
- };
303
- }
304
- if (error instanceof SynapseError) {
305
- return {
306
- message: error.displayMessage || error.message,
307
- code: error.code,
308
- context: error.context,
309
- };
310
- }
311
- if (error instanceof Error) {
312
- return { message: error.message };
313
- }
314
- return { message: "An unexpected error occurred" };
315
- }
316
- emitError(error) {
317
- this.config.callbacks?.onError?.(this.toClientError(error));
318
- }
319
- toSessionError(error, fallbackMessage, context, hint) {
320
- return normalizeError(error, SessionError, fallbackMessage, {
321
- context,
322
- hint,
323
- });
324
- }
325
- /**
326
- * Initialize the connection
327
- * eg: socket connection or polling connection
328
- */
329
- async initializeConnection(sessionResponse) {
330
- this.closeConnection();
331
- if (!sessionResponse.session_id || !sessionResponse.session_token) {
332
- throw new SessionError("Session ID or token not found", {
333
- context: { stage: "initializeConnection" },
334
- hint: "Ensure the session API returns both identifiers.",
335
- });
336
- }
337
- this.sessionConfig = sessionResponse;
338
- const envConfig = getConfig(this.config?.environment);
339
- const isSocket = this.connectionType === ConnectionType.SOCKET;
340
- const defaultUrl = isSocket ? envConfig.WEBSOCKET_URL : envConfig.BASE_API_URL;
341
- const customUrl = this.config.serverUrl
342
- ? isSocket
343
- ? `wss://${this.config.serverUrl.split("://")[1]}`
344
- : this.config.serverUrl
345
- : null;
346
- this.connection = await ConnectionFactory.createConnection(this.connectionType, {
347
- serverUrl: customUrl || defaultUrl,
348
- auth: {
349
- sessionId: sessionResponse.session_id,
350
- sessionToken: sessionResponse.session_token,
351
- },
352
- agentId: this.config.agentId,
353
- userId: this.config.userId,
354
- // authorization: this.config?.authorization,
355
- overrides: this.config.overrides,
356
- });
357
- this.connectionAttempts++;
358
- this.messageManager.setConnection(this.connection);
359
- // Bridge all connection events to the persistent SDK-level emitter so that
360
- // widget listeners registered via .on() survive internal reconnections.
361
- const originalEmit = this.connection.emit.bind(this.connection);
362
- this.connection.emit = (event, ...args) => {
363
- originalEmit(event, ...args);
364
- this.sdkEventEmitter.emit(event, ...args);
365
- };
366
- }
367
- /**
368
- * Resolve the session
369
- * function to decide whether to create a new session or refresh the existing session
370
- */
371
- async manageSession(existingSession) {
372
- try {
373
- if (!existingSession?.session_id) {
374
- return this.createNewSession();
375
- }
376
- const result = await this.resourceManager.validateSession(existingSession.session_id);
377
- if (result.active) {
378
- return existingSession;
379
- }
380
- if (result.expired) {
381
- return this.refreshSession(existingSession.session_id, existingSession.session_token);
382
- }
383
- throw new APIError("Failed to create session", 500, undefined, undefined);
384
- }
385
- catch (error) {
386
- console.log("error", error, error instanceof APIError);
387
- if (error instanceof APIError) {
388
- if (error.status === 404 || error.status === 403) {
389
- throw error;
390
- }
391
- }
392
- else if (error instanceof NotFoundError && error.status === 404) {
393
- throw error;
394
- }
395
- throw this.toSessionError(error, "Failed to resolve session", {
396
- stage: "resolveSession",
397
- });
398
- }
399
- }
400
- /**
401
- * Refresh the session
402
- */
403
- async refreshSession(sessionId, sessionToken) {
404
- try {
405
- return await this.resourceManager.refreshSession(sessionId, sessionToken);
406
- }
407
- catch (error) {
408
- if (error instanceof APIError) {
409
- // Emit API error via onError callback before handling
410
- this.emitError(error);
411
- // if (status === 404 || status === 500) {
412
- // return this.createNewSession();
413
- // }
414
- }
415
- throw this.toSessionError(error, "Failed to refresh session", {
416
- stage: "refreshSession",
417
- sessionId,
418
- });
419
- }
420
- }
421
- /**
422
- * Create a new session
423
- */
424
- async createNewSession() {
425
- return await this.resourceManager.createSession(this.config.userId, this.config.context);
426
- }
427
- /**
428
- * Set up event handlers for connection and messages
429
- */
430
- setupEventHandlers() {
431
- if (!this.connection)
432
- return;
433
- switch (this.connectionType) {
434
- case ConnectionType.SOCKET:
435
- this.connection.onOpen(() => {
436
- this.onSocketConnectionOpen();
437
- });
438
- this.connection.onMessage((message) => {
439
- this.onIncomingSocketMessage(message);
440
- });
441
- this.connection.onError((error) => {
442
- this.onSocketConnectionError(error);
443
- });
444
- this.connection.on(SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_EXPIRED, () => {
445
- this.handleSessionExpiry();
446
- });
447
- break;
448
- case ConnectionType.SSE:
449
- // SSE auth is handled at the URL/header layer, no auth message needed.
450
- // Connection is considered "established" as soon as the stream opens.
451
- this.connection.onOpen(() => {
452
- this.messageManager.handleConnectionEstablished();
453
- });
454
- this.connection.onMessage((message) => {
455
- this.onIncomingSocketMessage(message);
456
- });
457
- this.connection.onError((error) => {
458
- this.onSocketConnectionError(error);
459
- });
460
- this.connection.on(SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_EXPIRED, () => {
461
- this.handleSessionExpiry();
462
- });
463
- break;
464
- default:
465
- throw new ConnectionError("Unsupported connection type", {
466
- context: {
467
- stage: "setupEventHandlers",
468
- connectionType: this.connectionType,
469
- },
470
- hint: "Use ConnectionType.SOCKET or provide a custom handler.",
471
- });
472
- }
473
- //common handler for all connection types
474
- this.connection.onDisconnect(async (details) => {
475
- if (details.reason === DisconnectionReason.CLIENT_CLOSED)
476
- return;
477
- if (this.connectionAttempts < 3 && this.sessionConfig?.session_id && this.sessionConfig.session_token) {
478
- try {
479
- await this.startSession({ session_id: this.sessionConfig.session_id, session_token: this.sessionConfig.session_token });
480
- }
481
- catch (error) {
482
- this.messageManager.handleDisconnect(details);
483
- }
484
- }
485
- else {
486
- this.messageManager.handleDisconnect(details);
487
- }
488
- });
489
- }
490
- /**
491
- * Handle socket error
492
- */
493
- onSocketConnectionError(error) {
494
- this.connection?.emit(SYNAPSE_REALTIME_EVENTS.ERROR, error);
495
- const connectionError = this.toConnectionError(error, "WebSocket connection error", { stage: "onSocketConnectionError" }, "Verify network connectivity or attempt to reconnect.");
496
- this.emitError(connectionError);
497
- }
498
- /**
499
- * Handle socket connection open
500
- */
501
- onSocketConnectionOpen() {
502
- if (!this.sessionConfig?.session_token) {
503
- const error = new SessionError("Session token not set. Call startSession() first.", {
504
- context: { stage: "onSocketConnectionOpen" },
505
- hint: "Ensure startSession() completes successfully before socket opens.",
506
- });
507
- this.emitError(error);
508
- throw error;
509
- }
510
- this.messageManager.sendSocketAuthMessage(this.sessionConfig.session_token);
511
- }
512
- /**
513
- * Handle incoming socket messages
514
- */
515
- onIncomingSocketMessage(message) {
516
- // this.config.callbacks?.onMessage?.(message.content, message.messageId);
517
- switch (message.ev) {
518
- case SOCKET_EVENTS.CHAT:
519
- this.messageManager.handleIncomingSocketChatMessage(message);
520
- // this.config.callbacks?.onMessage?.(message.data.content, message.data.messageId);
521
- break;
522
- case SOCKET_EVENTS.CONNECTION_ESTABLISHED: //emit after internal handlings
523
- this.messageManager.handleConnectionEstablished();
524
- break;
525
- case SOCKET_EVENTS.STREAM:
526
- this.messageManager.handleIncomingSocketStreamMessage(message);
527
- break;
528
- case SOCKET_EVENTS.END_OF_STREAM: //emit
529
- this.messageManager.handleIncomingSocketEndOfStreamMessage(message);
530
- break;
531
- case SOCKET_EVENTS.PING:
532
- this.messageManager.sendSocketPongMessage();
533
- break;
534
- case SOCKET_EVENTS.PONG:
535
- this.messageManager.sendSocketPingMessage();
536
- break;
537
- case SOCKET_EVENTS.SYNC:
538
- break;
539
- case SOCKET_EVENTS.ERROR:
540
- this.messageManager.handleIncomingSocketErrorMessage(message);
541
- break;
542
- default:
543
- const error = new MessageError("Unsupported message type", {
544
- context: {
545
- stage: "onIncomingSocketMessage",
546
- event: message.ev ?? "unknown",
547
- },
548
- hint: "Ensure the server is sending supported socket events.",
549
- });
550
- this.emitError(error);
551
- return;
552
- }
553
- }
554
- /**
555
- * Handle session expired
556
- */
557
- async handleSessionExpiry() {
558
- if (this.isRefreshingSession) {
559
- console.warn("Session is already being refreshed");
560
- return;
561
- }
562
- try {
563
- this.closeConnection();
564
- if (!this.sessionConfig?.session_id ||
565
- !this.sessionConfig?.session_token) {
566
- const error = new SessionError("Session ID or token not found", {
567
- context: { stage: "handleSessionExpiry" },
568
- });
569
- this.emitError(error);
570
- throw error;
571
- }
572
- this.isRefreshingSession = true;
573
- const refreshed = await this.refreshSession(this.sessionConfig.session_id, this.sessionConfig.session_token);
574
- if (!refreshed.session_id || !refreshed.session_token) {
575
- throw new SessionError("Session refresh failed", {
576
- context: { stage: "handleSessionExpiry" },
577
- });
578
- }
579
- this.sessionConfig.session_id = refreshed.session_id;
580
- this.sessionConfig.session_token = refreshed.session_token;
581
- await this.initializeConnection(refreshed);
582
- this.setupEventHandlers();
583
- this.config.callbacks?.onSessionRefreshed?.(refreshed);
584
- }
585
- catch (error) {
586
- const sessionError = this.toSessionError(error, "Session expired", {
587
- stage: "handleSessionExpiry",
588
- });
589
- this.emitError(sessionError);
590
- }
591
- finally {
592
- this.isRefreshingSession = false;
593
- }
594
- }
595
- toConnectionError(error, fallbackMessage, context, hint) {
596
- return normalizeError(error, ConnectionError, fallbackMessage, {
597
- context,
598
- hint,
599
- });
600
- }
601
- closeConnection() {
602
- if (this.connection) {
603
- this.connection.close();
604
- this.connection = null;
605
- }
606
- }
607
- cleanup() {
608
- this.connectionAttempts = 0;
609
- this.sdkEventEmitter?.removeAllListeners?.();
610
- this.messageManager?.cleanupMessageServerState?.();
611
- }
612
- }
@@ -1,27 +0,0 @@
1
- /**
2
- * Factory class to create the appropriate connection type
3
- */
4
- import { WebSocketConnection, } from "./Websocket";
5
- import { SSEConnection } from "./SSE";
6
- import { ConnectionError } from "../internal/Error/Error";
7
- export const ConnectionType = {
8
- SOCKET: "socket",
9
- SSE: "sse",
10
- };
11
- export class ConnectionFactory {
12
- /**
13
- * Create a connection based on the specified type
14
- */
15
- static async createConnection(type, config) {
16
- switch (type) {
17
- case ConnectionType.SOCKET:
18
- return new WebSocketConnection(config);
19
- case ConnectionType.SSE:
20
- return new SSEConnection(config);
21
- default:
22
- throw new ConnectionError(`Unsupported connection type: ${type}`, {
23
- context: { type },
24
- });
25
- }
26
- }
27
- }