@robosystems/client 2.35.0 → 2.37.0

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/README.md CHANGED
@@ -8,12 +8,12 @@ Official TypeScript client for the RoboSystems financial intelligence platform
8
8
  ## Features
9
9
 
10
10
  - **Type-safe API client** with full TypeScript types
11
- - **Browser & Node.js support** with different auth strategies
11
+ - **Browser & Node.js support**, including operation streams
12
12
  - **React hooks** for seamless UI integration
13
13
  - **High-level domain clients** for RoboLedger, RoboInvestor, and the element library
14
- - **Streaming support** for memory-efficient processing of large result sets
14
+ - **Streaming query mode** over NDJSON for large results; the client collects the rows before yielding them
15
15
  - **AI Operator** integration for natural language financial analysis
16
- - **Comprehensive error handling** with typed errors
16
+ - **Typed errors** for GraphQL reads, queued work and operator runs
17
17
 
18
18
  ## Installation
19
19
 
@@ -2,24 +2,14 @@
2
2
  * Core SSE (Server-Sent Events) client for RoboSystems API
3
3
  * Provides automatic reconnection, event replay, and type-safe event handling
4
4
  *
5
- * SECURITY NOTE: When using JWT authentication, tokens are passed as query parameters
6
- * due to EventSource API limitations. This means tokens may appear in:
7
- * - Server access logs
8
- * - Proxy logs
9
- * - Browser history
10
- * - Referer headers
5
+ * The stream is read over `fetch` rather than `EventSource`, so a credential
6
+ * travels in a header, never in the URL, and the same code runs in browsers
7
+ * and Node.
11
8
  *
12
- * For production environments with sensitive data, consider:
13
- * - Using cookie-based authentication instead
14
- * - Implementing a WebSocket-based alternative
15
- * - Using short-lived tokens that expire quickly
16
- * - Ensuring all connections use HTTPS
17
- *
18
- * CREDENTIAL ROTATION: the stream endpoint authenticates the JWT it finds in
19
- * the URL, and the backend revokes the previous JWT on every session refresh.
20
- * A `token` captured once therefore goes dead the moment the session rotates
21
- * (about every 25 minutes in the browser apps); pass a `tokenProvider` and it
22
- * is consulted on every connect — including automatic reconnects — instead.
9
+ * CREDENTIAL ROTATION: the backend revokes the previous JWT on every session
10
+ * refresh. A `token` captured once therefore goes dead the moment the session
11
+ * rotates (about every 25 minutes in the browser apps); pass a `tokenProvider`
12
+ * and it is consulted on every connect, including automatic reconnects.
23
13
  */
24
14
  import type { TokenProvider } from './graphql/client';
25
15
  export interface SSEConfig {
@@ -27,8 +17,8 @@ export interface SSEConfig {
27
17
  credentials?: 'include' | 'same-origin' | 'omit';
28
18
  headers?: Record<string, string>;
29
19
  /**
30
- * Static JWT captured at construction. Fine for long-lived API keys and
31
- * server-side flows; browser sessions should use `tokenProvider`.
20
+ * Static credential captured at construction: an API key or a JWT. Fine for
21
+ * API keys and server-side flows; browser sessions should use `tokenProvider`.
32
22
  */
33
23
  token?: string;
34
24
  /**
@@ -62,7 +52,8 @@ export declare enum EventType {
62
52
  }
63
53
  export declare class SSEClient {
64
54
  private config;
65
- private eventSource?;
55
+ private connection?;
56
+ private opened;
66
57
  private reconnectAttempts;
67
58
  private lastEventId?;
68
59
  private closed;
@@ -70,6 +61,14 @@ export declare class SSEClient {
70
61
  constructor(config: SSEConfig);
71
62
  connect(operationId: string, fromSequence?: number): Promise<void>;
72
63
  private open;
64
+ /**
65
+ * A connect that never opened. The first connect reports it to the caller; a
66
+ * reconnect retries what could pass, such as a 503 during a deploy, and
67
+ * otherwise tells the listeners, since no caller is waiting on it.
68
+ */
69
+ private failToOpen;
70
+ private readStream;
71
+ private dispatch;
73
72
  /**
74
73
  * Credential for one connect attempt: the `tokenProvider` result when one
75
74
  * is configured (`null`/`undefined` connects unauthenticated), otherwise
@@ -15,8 +15,18 @@ var EventType;
15
15
  EventType["HEARTBEAT"] = "heartbeat";
16
16
  EventType["QUEUE_UPDATE"] = "queue_update";
17
17
  })(EventType || (exports.EventType = EventType = {}));
18
+ const CONNECT_TIMEOUT_MS = 10000;
19
+ /** Names this client emits itself, which a stream must not be able to trigger. */
20
+ const CLIENT_EVENTS = new Set([
21
+ 'connected',
22
+ 'closed',
23
+ 'reconnecting',
24
+ 'max_retries_exceeded',
25
+ 'parse_error',
26
+ ]);
18
27
  class SSEClient {
19
28
  constructor(config) {
29
+ this.opened = false;
20
30
  this.reconnectAttempts = 0;
21
31
  this.closed = false;
22
32
  this.listeners = new Map();
@@ -28,90 +38,131 @@ class SSEClient {
28
38
  };
29
39
  }
30
40
  async connect(operationId, fromSequence = 0) {
41
+ this.closed = false;
31
42
  return this.open(operationId, fromSequence, false);
32
43
  }
33
44
  async open(operationId, fromSequence, reconnect) {
34
45
  // Resolved per attempt so a rotated JWT is picked up by every connect,
35
46
  // not just the first one after construction.
36
47
  const token = await this.resolveToken();
37
- // A close() during the backoff or the token lookup ends a reconnect.
38
- if (reconnect && this.closed)
39
- return;
40
- return new Promise((resolve, reject) => {
41
- let url = `${this.config.baseUrl}/v1/operations/${(0, client_1.pathSegment)(operationId, 'operationId')}/stream?from_sequence=${encodeURIComponent(String(fromSequence))}`;
42
- // Add JWT token as query parameter if provided
43
- // WARNING: EventSource API doesn't support custom headers, so tokens are passed via query param
44
- // This has security implications - see class documentation
45
- if (token) {
46
- url += `&token=${encodeURIComponent(token)}`;
47
- }
48
- // Never leave a previous source running beside its replacement: two
49
- // live streams deliver every event twice.
50
- this.eventSource?.close();
51
- const eventSource = new EventSource(url, {
52
- withCredentials: this.config.credentials === 'include',
53
- });
54
- this.eventSource = eventSource;
55
- let opened = false;
56
- const connectionTimeout = setTimeout(() => {
57
- if (!opened) {
58
- reject(new Error('SSE connection timed out before opening'));
59
- this.close();
60
- }
61
- }, 10000);
62
- eventSource.onopen = () => {
63
- opened = true;
64
- clearTimeout(connectionTimeout);
65
- this.reconnectAttempts = 0;
66
- this.emit('connected', null);
67
- resolve();
68
- };
69
- eventSource.onerror = (error) => {
70
- if (this.eventSource !== eventSource)
71
- return;
72
- const serverError = readServerError(error);
73
- if (serverError) {
74
- // The server's own `event: error` — the per-user connection cap, an
75
- // unknown or foreign operation, a failed stream — ends the stream
76
- // for good. Reconnecting would only repeat it (and, since the
77
- // stream opens first, reset the retry budget each time).
78
- clearTimeout(connectionTimeout);
79
- this.emit('error', serverError);
80
- this.close();
81
- if (!opened) {
82
- reject(new Error(serverError.error));
83
- }
84
- return;
85
- }
86
- if (!opened) {
87
- // Failed before the stream ever opened. Browser EventSource doesn't
88
- // expose the HTTP status, but a CLOSED readyState at this point
89
- // means a non-retryable response (commonly 401/403/404). Reject
90
- // the initial promise so callers surface a clear error instead of
91
- // waiting out the 10s connectionTimeout or spinning retries that
92
- // can never satisfy this promise.
93
- clearTimeout(connectionTimeout);
94
- const nonRetryable = eventSource.readyState === EventSource.CLOSED;
95
- this.close();
96
- reject(new Error(nonRetryable
97
- ? 'SSE connection failed before open (likely auth/not-found; EventSource hides the HTTP status)'
98
- : 'SSE connection error before open'));
99
- return;
100
- }
101
- if (!this.closed) {
102
- this.handleError(error, operationId, fromSequence);
103
- }
104
- };
105
- eventSource.onmessage = (event) => {
106
- this.handleMessage(event);
107
- };
108
- // Set up specific event listeners
109
- Object.values(EventType).forEach((eventType) => {
110
- eventSource.addEventListener(eventType, (event) => {
111
- this.handleTypedEvent(eventType, event);
112
- });
48
+ // A close() during the backoff or the token lookup ends the attempt.
49
+ if (this.closed) {
50
+ if (reconnect)
51
+ return;
52
+ throw new Error('SSE stream closed before opening');
53
+ }
54
+ const url = `${this.config.baseUrl}/v1/operations/${(0, client_1.pathSegment)(operationId, 'operationId')}/stream?from_sequence=${encodeURIComponent(String(fromSequence))}`;
55
+ // Accept is the only stream header the API's CORS policy needs; `cache`
56
+ // below stands in for Cache-Control, which the preflight would refuse.
57
+ const headers = new Headers({ ...this.config.headers, Accept: 'text/event-stream' });
58
+ if (token)
59
+ (0, client_1.applyAuthHeader)(headers, token);
60
+ // Never leave a previous stream running beside its replacement: two live
61
+ // streams deliver every event twice.
62
+ this.connection?.abort();
63
+ const connection = new AbortController();
64
+ this.connection = connection;
65
+ this.opened = false;
66
+ let timedOut = false;
67
+ const connectionTimeout = setTimeout(() => {
68
+ timedOut = true;
69
+ connection.abort();
70
+ }, CONNECT_TIMEOUT_MS);
71
+ let response;
72
+ try {
73
+ response = await fetch(url, {
74
+ headers,
75
+ cache: 'no-store',
76
+ signal: connection.signal,
77
+ ...(this.config.credentials ? { credentials: this.config.credentials } : {}),
113
78
  });
79
+ }
80
+ catch (error) {
81
+ clearTimeout(connectionTimeout);
82
+ const message = timedOut
83
+ ? 'SSE connection timed out before opening'
84
+ : `SSE connection error before open: ${error instanceof Error ? error.message : String(error)}`;
85
+ return this.failToOpen(connection, new Error(message), true, operationId, fromSequence, reconnect);
86
+ }
87
+ clearTimeout(connectionTimeout);
88
+ if (!response.ok || !response.body) {
89
+ const retryable = response.status === 429 || response.status >= 500;
90
+ return this.failToOpen(connection, new Error(`SSE connection failed: HTTP ${response.status}${await readDetail(response)}`), retryable, operationId, fromSequence, reconnect);
91
+ }
92
+ if (this.connection !== connection)
93
+ return;
94
+ this.opened = true;
95
+ this.emit('connected', null);
96
+ // Callers attach their listeners when connect() resolves, so reading waits
97
+ // a tick: an event that is already buffered must not be delivered to nobody.
98
+ const body = response.body;
99
+ setTimeout(() => {
100
+ void this.readStream(body, connection, operationId, fromSequence);
101
+ }, 0);
102
+ }
103
+ /**
104
+ * A connect that never opened. The first connect reports it to the caller; a
105
+ * reconnect retries what could pass, such as a 503 during a deploy, and
106
+ * otherwise tells the listeners, since no caller is waiting on it.
107
+ */
108
+ failToOpen(connection, error, retryable, operationId, fromSequence, reconnect) {
109
+ if (this.connection !== connection) {
110
+ if (!reconnect)
111
+ throw new Error('SSE stream closed before opening');
112
+ return;
113
+ }
114
+ if (!reconnect) {
115
+ this.close();
116
+ throw error;
117
+ }
118
+ if (retryable) {
119
+ this.handleError(error, operationId, fromSequence);
120
+ return;
121
+ }
122
+ this.emit('error', { error: error.message });
123
+ this.close();
124
+ }
125
+ async readStream(body, connection, operationId, fromSequence) {
126
+ const reader = body.getReader();
127
+ const decoder = new TextDecoder();
128
+ const parser = new SSEParser((event) => {
129
+ if (this.connection === connection)
130
+ this.dispatch(event);
114
131
  });
132
+ let failure;
133
+ try {
134
+ for (;;) {
135
+ const { done, value } = await reader.read();
136
+ if (done)
137
+ break;
138
+ parser.feed(decoder.decode(value, { stream: true }));
139
+ if (this.connection !== connection)
140
+ break;
141
+ }
142
+ }
143
+ catch (error) {
144
+ failure = error;
145
+ }
146
+ reader.cancel().catch(() => { });
147
+ // Still current means the server went away without saying it was finished.
148
+ if (this.connection === connection && !this.closed) {
149
+ this.handleError(failure ?? new Error('SSE stream ended before the operation finished'), operationId, fromSequence);
150
+ }
151
+ }
152
+ dispatch(event) {
153
+ if (event.type === 'message') {
154
+ this.handleMessage(event);
155
+ }
156
+ else if (event.type === 'error') {
157
+ // The server's own `event: error` — the per-user connection cap, an
158
+ // unknown or foreign operation, a failed stream — ends the stream for
159
+ // good. Reconnecting would only repeat it.
160
+ this.emit('error', readServerError(event.data));
161
+ this.close();
162
+ }
163
+ else if (event.type !== 'keepalive' && !CLIENT_EVENTS.has(event.type)) {
164
+ this.handleTypedEvent(event.type, event);
165
+ }
115
166
  }
116
167
  /**
117
168
  * Credential for one connect attempt: the `tokenProvider` result when one
@@ -156,11 +207,16 @@ class SSEClient {
156
207
  try {
157
208
  const data = JSON.parse(event.data);
158
209
  this.lastEventId = event.lastEventId;
210
+ // Only a real event shows the stream got anywhere. Resetting when a
211
+ // stream opens would let one that opens and ends retry forever.
212
+ this.reconnectAttempts = 0;
159
213
  this.emit(eventType, data);
160
- // Check for completion events
214
+ // `stream_end` covers an operation that paused: nothing more arrives
215
+ // until a resume, so reconnecting would only replay it.
161
216
  if (eventType === EventType.OPERATION_COMPLETED ||
162
217
  eventType === EventType.OPERATION_ERROR ||
163
- eventType === EventType.OPERATION_CANCELLED) {
218
+ eventType === EventType.OPERATION_CANCELLED ||
219
+ eventType === 'stream_end') {
164
220
  this.close();
165
221
  }
166
222
  }
@@ -168,12 +224,12 @@ class SSEClient {
168
224
  this.emit('parse_error', { error, rawData: event.data });
169
225
  }
170
226
  }
171
- async handleError(error, operationId, fromSequence) {
227
+ handleError(error, operationId, fromSequence) {
172
228
  if (this.closed)
173
229
  return;
174
- // Close the failed source now: a browser EventSource retries on its own,
175
- // and that retry would run alongside the reconnect scheduled below.
176
- this.eventSource?.close();
230
+ this.connection?.abort();
231
+ this.connection = undefined;
232
+ this.opened = false;
177
233
  if (this.reconnectAttempts < this.config.maxRetries) {
178
234
  this.reconnectAttempts++;
179
235
  const delay = this.config.retryDelay * Math.pow(2, this.reconnectAttempts - 1);
@@ -186,8 +242,10 @@ class SSEClient {
186
242
  if (this.closed)
187
243
  return;
188
244
  const resumeFrom = this.lastEventId ? parseInt(this.lastEventId) + 1 : fromSequence;
189
- this.open(operationId, resumeFrom, true).catch(() => {
190
- // Error handled in connect
245
+ this.open(operationId, resumeFrom, true).catch((err) => {
246
+ // A throwing tokenProvider: there is no caller left to reject.
247
+ this.emit('error', { error: err instanceof Error ? err.message : String(err) });
248
+ this.close();
191
249
  });
192
250
  }, delay);
193
251
  }
@@ -216,33 +274,87 @@ class SSEClient {
216
274
  }
217
275
  close() {
218
276
  this.closed = true;
219
- if (this.eventSource) {
220
- this.eventSource.close();
221
- this.eventSource = undefined;
222
- }
277
+ this.connection?.abort();
278
+ this.connection = undefined;
279
+ this.opened = false;
223
280
  this.emit('closed', null);
224
281
  this.listeners.clear();
225
282
  }
226
283
  isConnected() {
227
- return this.eventSource !== undefined && this.eventSource.readyState === EventSource.OPEN;
284
+ return this.opened;
228
285
  }
229
286
  }
230
287
  exports.SSEClient = SSEClient;
231
- /**
232
- * The payload of a server-sent `event: error`, or null for a transport
233
- * error. A named `error` event reaches `onerror` as a `MessageEvent`
234
- * carrying the server's JSON (`{"error": "..."}`); a dropped connection
235
- * arrives as a bare `Event` with no data.
236
- */
237
- function readServerError(event) {
238
- if (typeof event?.data !== 'string' || event.data === '')
239
- return null;
288
+ /** The payload of a server-sent `event: error`, normalised to carry `error`. */
289
+ function readServerError(raw) {
240
290
  try {
241
- const data = JSON.parse(event.data);
291
+ const data = JSON.parse(raw);
242
292
  const message = data?.error ?? data?.message ?? data?.detail;
243
- return { ...(typeof data === 'object' ? data : {}), error: String(message ?? event.data) };
293
+ return { ...(typeof data === 'object' ? data : {}), error: String(message ?? raw) };
294
+ }
295
+ catch {
296
+ return { error: raw };
297
+ }
298
+ }
299
+ /** The API's `detail` from a refused connect, as a suffix for the error message. */
300
+ async function readDetail(response) {
301
+ try {
302
+ const body = await response.text();
303
+ try {
304
+ const detail = JSON.parse(body)?.detail;
305
+ if (detail)
306
+ return ` ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`;
307
+ }
308
+ catch {
309
+ // Not JSON; fall through to the raw text.
310
+ }
311
+ return body ? ` ${body.slice(0, 200)}` : '';
244
312
  }
245
313
  catch {
246
- return { error: event.data };
314
+ return '';
315
+ }
316
+ }
317
+ /** The `text/event-stream` format, fed in chunks that can split anywhere. */
318
+ class SSEParser {
319
+ constructor(onEvent) {
320
+ this.onEvent = onEvent;
321
+ this.buffer = '';
322
+ this.type = '';
323
+ this.data = [];
324
+ this.lastEventId = '';
325
+ }
326
+ feed(text) {
327
+ this.buffer += text;
328
+ // A trailing CR may be half of a CRLF split across chunks, so it waits.
329
+ const heldCR = this.buffer.endsWith('\r');
330
+ const lines = (heldCR ? this.buffer.slice(0, -1) : this.buffer).split(/\r\n|\n|\r/);
331
+ this.buffer = (lines.pop() ?? '') + (heldCR ? '\r' : '');
332
+ for (const line of lines)
333
+ this.readLine(line);
334
+ }
335
+ readLine(line) {
336
+ if (line === '') {
337
+ if (this.data.length > 0) {
338
+ this.onEvent({
339
+ type: this.type || 'message',
340
+ data: this.data.join('\n'),
341
+ lastEventId: this.lastEventId,
342
+ });
343
+ }
344
+ this.type = '';
345
+ this.data = [];
346
+ return;
347
+ }
348
+ if (line.startsWith(':'))
349
+ return;
350
+ const colon = line.indexOf(':');
351
+ const field = colon === -1 ? line : line.slice(0, colon);
352
+ const value = colon === -1 ? '' : line.slice(colon + 1).replace(/^ /, '');
353
+ if (field === 'event')
354
+ this.type = value;
355
+ else if (field === 'data')
356
+ this.data.push(value);
357
+ else if (field === 'id' && !value.includes('\0'))
358
+ this.lastEventId = value;
247
359
  }
248
360
  }