@panyam/servicekit-client 0.0.5 → 0.0.7
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/dist/__tests__/sse.test.d.ts +2 -0
- package/dist/__tests__/sse.test.d.ts.map +1 -0
- package/dist/__tests__/sse.test.js +286 -0
- package/dist/__tests__/sse.test.js.map +1 -0
- package/dist/index.d.ts +12 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1012 -0
- package/dist/servicekit-client.browser.js +478 -1
- package/dist/sse-client.d.ts +117 -0
- package/dist/sse-client.d.ts.map +1 -0
- package/dist/sse-client.js +188 -0
- package/dist/sse-client.js.map +1 -0
- package/dist/sse-mock.d.ts +57 -0
- package/dist/sse-mock.d.ts.map +1 -0
- package/dist/sse-mock.js +108 -0
- package/dist/sse-mock.js.map +1 -0
- package/dist/sse-parser.d.ts +64 -0
- package/dist/sse-parser.d.ts.map +1 -0
- package/dist/sse-parser.js +174 -0
- package/dist/sse-parser.js.map +1 -0
- package/dist/streamable-client.d.ts +80 -0
- package/dist/streamable-client.d.ts.map +1 -0
- package/dist/streamable-client.js +142 -0
- package/dist/streamable-client.js.map +1 -0
- package/package.json +14 -10
- package/src/__tests__/sse.test.ts +358 -0
- package/src/index.ts +22 -3
- package/src/sse-client.ts +232 -0
- package/src/sse-mock.ts +159 -0
- package/src/sse-parser.ts +243 -0
- package/src/streamable-client.ts +171 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1012 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
var ReadyState = {
|
|
3
|
+
CONNECTING: 0,
|
|
4
|
+
OPEN: 1,
|
|
5
|
+
CLOSING: 2,
|
|
6
|
+
CLOSED: 3
|
|
7
|
+
};
|
|
8
|
+
var JSONCodec = class {
|
|
9
|
+
decode(data) {
|
|
10
|
+
if (typeof data === "string") {
|
|
11
|
+
return JSON.parse(data);
|
|
12
|
+
}
|
|
13
|
+
const text = new TextDecoder().decode(data);
|
|
14
|
+
return JSON.parse(text);
|
|
15
|
+
}
|
|
16
|
+
encode(msg) {
|
|
17
|
+
return JSON.stringify(msg);
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
var BinaryCodec = class {
|
|
21
|
+
constructor(decodeFunc, encodeFunc) {
|
|
22
|
+
this.decodeFunc = decodeFunc;
|
|
23
|
+
this.encodeFunc = encodeFunc;
|
|
24
|
+
}
|
|
25
|
+
decode(data) {
|
|
26
|
+
if (typeof data === "string") {
|
|
27
|
+
throw new Error("BinaryCodec received text data, expected binary");
|
|
28
|
+
}
|
|
29
|
+
return this.decodeFunc(data);
|
|
30
|
+
}
|
|
31
|
+
encode(msg) {
|
|
32
|
+
const encoded = this.encodeFunc(msg);
|
|
33
|
+
return encoded.buffer.slice(encoded.byteOffset, encoded.byteOffset + encoded.byteLength);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// src/base-client.ts
|
|
38
|
+
var BaseWSClient = class {
|
|
39
|
+
constructor(options = {}) {
|
|
40
|
+
this.ws = null;
|
|
41
|
+
/** Called when a data message is received (decoded by codec) */
|
|
42
|
+
this.onMessage = () => {
|
|
43
|
+
};
|
|
44
|
+
/** Called when a ping is received (after auto-pong if enabled) */
|
|
45
|
+
this.onPing = () => {
|
|
46
|
+
};
|
|
47
|
+
/** Called when the connection closes */
|
|
48
|
+
this.onClose = () => {
|
|
49
|
+
};
|
|
50
|
+
/** Called when a WebSocket error occurs */
|
|
51
|
+
this.onError = () => {
|
|
52
|
+
};
|
|
53
|
+
this._autoPong = options.autoPong ?? true;
|
|
54
|
+
this._WebSocket = options.WebSocket ?? globalThis.WebSocket;
|
|
55
|
+
this._codec = options.codec ?? new JSONCodec();
|
|
56
|
+
}
|
|
57
|
+
/** Get the codec used for encoding/decoding data messages */
|
|
58
|
+
get codec() {
|
|
59
|
+
return this._codec;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Connect to a WebSocket server.
|
|
63
|
+
* @param url The WebSocket URL to connect to
|
|
64
|
+
* @returns Promise that resolves when connected
|
|
65
|
+
*/
|
|
66
|
+
connect(url) {
|
|
67
|
+
return new Promise((resolve, reject) => {
|
|
68
|
+
if (this.ws && this.ws.readyState === ReadyState.OPEN) {
|
|
69
|
+
resolve();
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
this.ws = new this._WebSocket(url);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
reject(error);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
this.ws.binaryType = "arraybuffer";
|
|
79
|
+
this.ws.onopen = () => {
|
|
80
|
+
resolve();
|
|
81
|
+
};
|
|
82
|
+
this.ws.onerror = (event) => {
|
|
83
|
+
const errorMsg = "WebSocket error";
|
|
84
|
+
this.onError(errorMsg);
|
|
85
|
+
reject(new Error(errorMsg));
|
|
86
|
+
};
|
|
87
|
+
this.ws.onclose = () => {
|
|
88
|
+
this.onClose();
|
|
89
|
+
};
|
|
90
|
+
this.ws.onmessage = (event) => {
|
|
91
|
+
this.handleRawMessage(event.data);
|
|
92
|
+
};
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Send a data message to the server using the configured codec.
|
|
97
|
+
* @param data The data to send (will be encoded by codec)
|
|
98
|
+
*/
|
|
99
|
+
send(data) {
|
|
100
|
+
if (!this.ws || this.ws.readyState !== ReadyState.OPEN) {
|
|
101
|
+
throw new Error("WebSocket is not connected");
|
|
102
|
+
}
|
|
103
|
+
const encoded = this._codec.encode(data);
|
|
104
|
+
this.ws.send(encoded);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Send a raw message to the server (bypasses codec).
|
|
108
|
+
* Useful for control messages like pong.
|
|
109
|
+
* @param message The raw string or ArrayBuffer to send
|
|
110
|
+
*/
|
|
111
|
+
sendRaw(message) {
|
|
112
|
+
if (!this.ws || this.ws.readyState !== ReadyState.OPEN) {
|
|
113
|
+
throw new Error("WebSocket is not connected");
|
|
114
|
+
}
|
|
115
|
+
this.ws.send(message);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Close the WebSocket connection.
|
|
119
|
+
*/
|
|
120
|
+
close() {
|
|
121
|
+
if (this.ws) {
|
|
122
|
+
this.ws.close();
|
|
123
|
+
this.ws = null;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Check if the client is connected.
|
|
128
|
+
*/
|
|
129
|
+
get isConnected() {
|
|
130
|
+
return this.ws !== null && this.ws.readyState === ReadyState.OPEN;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Get the WebSocket ready state.
|
|
134
|
+
*/
|
|
135
|
+
get readyState() {
|
|
136
|
+
return this.ws?.readyState ?? ReadyState.CLOSED;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Handle incoming raw message data.
|
|
140
|
+
* - Text frames: Check for control messages (ping), then decode with codec
|
|
141
|
+
* - Binary frames: Decode directly with codec
|
|
142
|
+
*
|
|
143
|
+
* Control messages (ping/pong/error) are always JSON text frames,
|
|
144
|
+
* regardless of what codec is used for data messages.
|
|
145
|
+
*/
|
|
146
|
+
handleRawMessage(data) {
|
|
147
|
+
if (data instanceof ArrayBuffer) {
|
|
148
|
+
try {
|
|
149
|
+
const decoded = this._codec.decode(data);
|
|
150
|
+
this.onMessage(decoded);
|
|
151
|
+
} catch (err) {
|
|
152
|
+
this.onError(`Failed to decode binary message: ${err}`);
|
|
153
|
+
}
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
let parsed;
|
|
157
|
+
try {
|
|
158
|
+
parsed = JSON.parse(data);
|
|
159
|
+
} catch {
|
|
160
|
+
try {
|
|
161
|
+
const decoded = this._codec.decode(data);
|
|
162
|
+
this.onMessage(decoded);
|
|
163
|
+
} catch (err) {
|
|
164
|
+
this.onError(`Failed to decode text message: ${err}`);
|
|
165
|
+
}
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (this.isPingMessage(parsed)) {
|
|
169
|
+
const pingId = parsed.pingId;
|
|
170
|
+
if (this._autoPong && pingId !== void 0) {
|
|
171
|
+
this.sendPong(pingId);
|
|
172
|
+
}
|
|
173
|
+
this.onPing(pingId ?? 0);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const decoded = this._codec.decode(data);
|
|
178
|
+
this.onMessage(decoded);
|
|
179
|
+
} catch (err) {
|
|
180
|
+
this.onError(`Failed to decode message: ${err}`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Check if a message is a ping message.
|
|
185
|
+
* Pings are always JSON with type: "ping".
|
|
186
|
+
*/
|
|
187
|
+
isPingMessage(msg) {
|
|
188
|
+
return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "ping";
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Send a pong response.
|
|
192
|
+
* Pongs are always JSON, bypassing the codec.
|
|
193
|
+
*/
|
|
194
|
+
sendPong(pingId) {
|
|
195
|
+
this.sendRaw(JSON.stringify({ type: "pong", pingId }));
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
// src/mock.ts
|
|
200
|
+
function createMockWSPair() {
|
|
201
|
+
let ws = null;
|
|
202
|
+
class MockWebSocket {
|
|
203
|
+
constructor(_url) {
|
|
204
|
+
this.readyState = ReadyState.CONNECTING;
|
|
205
|
+
this.binaryType = "";
|
|
206
|
+
this.onopen = null;
|
|
207
|
+
this.onmessage = null;
|
|
208
|
+
this.onerror = null;
|
|
209
|
+
this.onclose = null;
|
|
210
|
+
this._sent = [];
|
|
211
|
+
ws = this;
|
|
212
|
+
}
|
|
213
|
+
send(data) {
|
|
214
|
+
this._sent.push(data);
|
|
215
|
+
}
|
|
216
|
+
close() {
|
|
217
|
+
this.readyState = ReadyState.CLOSED;
|
|
218
|
+
this.onclose?.({});
|
|
219
|
+
}
|
|
220
|
+
get sentRaw() {
|
|
221
|
+
return this._sent;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const assertConnected = (method) => {
|
|
225
|
+
if (!ws) throw new Error(`Call client.connect() before ${method}()`);
|
|
226
|
+
};
|
|
227
|
+
const controller = {
|
|
228
|
+
get sentRaw() {
|
|
229
|
+
return ws?.sentRaw ?? [];
|
|
230
|
+
},
|
|
231
|
+
simulateOpen() {
|
|
232
|
+
assertConnected("simulateOpen");
|
|
233
|
+
ws.readyState = ReadyState.OPEN;
|
|
234
|
+
ws.onopen?.({});
|
|
235
|
+
},
|
|
236
|
+
simulateRawMessage(data) {
|
|
237
|
+
assertConnected("simulateRawMessage");
|
|
238
|
+
ws.onmessage?.({ data });
|
|
239
|
+
},
|
|
240
|
+
simulateWsError() {
|
|
241
|
+
assertConnected("simulateWsError");
|
|
242
|
+
ws.onerror?.({});
|
|
243
|
+
},
|
|
244
|
+
simulateClose(code) {
|
|
245
|
+
assertConnected("simulateClose");
|
|
246
|
+
ws.readyState = ReadyState.CLOSED;
|
|
247
|
+
ws.onclose?.({});
|
|
248
|
+
},
|
|
249
|
+
get readyState() {
|
|
250
|
+
return ws?.readyState ?? ReadyState.CLOSED;
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
return {
|
|
254
|
+
WebSocket: MockWebSocket,
|
|
255
|
+
controller
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// src/grpcws-client.ts
|
|
260
|
+
var GRPCWSClient = class _GRPCWSClient {
|
|
261
|
+
constructor(options = {}) {
|
|
262
|
+
/** Called when a data message is received */
|
|
263
|
+
this.onMessage = () => {
|
|
264
|
+
};
|
|
265
|
+
/** Called when the stream ends normally */
|
|
266
|
+
this.onStreamEnd = () => {
|
|
267
|
+
};
|
|
268
|
+
/** Called when the server sends an error */
|
|
269
|
+
this.onError = () => {
|
|
270
|
+
};
|
|
271
|
+
/** Called when the connection closes */
|
|
272
|
+
this.onClose = () => {
|
|
273
|
+
};
|
|
274
|
+
/** Called when a ping is received */
|
|
275
|
+
this.onPing = () => {
|
|
276
|
+
};
|
|
277
|
+
this.base = new BaseWSClient(options);
|
|
278
|
+
this.setupBaseHandlers();
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Connect to a grpcws WebSocket server.
|
|
282
|
+
* @param url The WebSocket URL to connect to
|
|
283
|
+
* @returns Promise that resolves when connected
|
|
284
|
+
*/
|
|
285
|
+
connect(url) {
|
|
286
|
+
return this.base.connect(url);
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Send data to the server.
|
|
290
|
+
* The data is wrapped in a {type: "data", data: ...} envelope.
|
|
291
|
+
* @param data The data payload to send
|
|
292
|
+
*/
|
|
293
|
+
send(data) {
|
|
294
|
+
const envelope = {
|
|
295
|
+
type: "data",
|
|
296
|
+
data
|
|
297
|
+
};
|
|
298
|
+
this.base.send(envelope);
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Signal that the client is done sending (half-close).
|
|
302
|
+
* Used in client streaming and bidirectional streaming to indicate
|
|
303
|
+
* the client won't send any more messages.
|
|
304
|
+
*/
|
|
305
|
+
endSend() {
|
|
306
|
+
this.base.send({ type: "end_send" });
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Cancel the stream.
|
|
310
|
+
* Signals to the server that the client wants to terminate the stream.
|
|
311
|
+
*/
|
|
312
|
+
cancel() {
|
|
313
|
+
this.base.send({ type: "cancel" });
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Close the WebSocket connection.
|
|
317
|
+
*/
|
|
318
|
+
close() {
|
|
319
|
+
this.base.close();
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Check if the client is connected.
|
|
323
|
+
*/
|
|
324
|
+
get isConnected() {
|
|
325
|
+
return this.base.isConnected;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Get the WebSocket ready state.
|
|
329
|
+
*/
|
|
330
|
+
get readyState() {
|
|
331
|
+
return this.base.readyState;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Create a mock client + controller pair for testing.
|
|
335
|
+
*
|
|
336
|
+
* Returns a pre-wired GRPCWSClient backed by a fake WebSocket, so
|
|
337
|
+
* consumers don't need to mock WebSocket internals or know about the
|
|
338
|
+
* servicekit envelope protocol.
|
|
339
|
+
*
|
|
340
|
+
* @example
|
|
341
|
+
* ```typescript
|
|
342
|
+
* const { client, controller } = GRPCWSClient.createMock();
|
|
343
|
+
*
|
|
344
|
+
* client.onMessage = (data) => { handle(data); };
|
|
345
|
+
* client.connect('ws://test');
|
|
346
|
+
* controller.simulateOpen();
|
|
347
|
+
*
|
|
348
|
+
* controller.simulateMessage({ event: { case: 'roomJoined', value: {} } });
|
|
349
|
+
* expect(controller.sentMessages).toHaveLength(0);
|
|
350
|
+
*
|
|
351
|
+
* client.send({ action: { case: 'join' } });
|
|
352
|
+
* expect(controller.sentMessages[0]).toMatchObject({ action: { case: 'join' } });
|
|
353
|
+
* ```
|
|
354
|
+
*/
|
|
355
|
+
static createMock() {
|
|
356
|
+
const { WebSocket, controller: wsCtrl } = createMockWSPair();
|
|
357
|
+
const client = new _GRPCWSClient({ WebSocket });
|
|
358
|
+
const controller = {
|
|
359
|
+
get sentMessages() {
|
|
360
|
+
const messages = [];
|
|
361
|
+
for (const raw of wsCtrl.sentRaw) {
|
|
362
|
+
try {
|
|
363
|
+
const parsed = JSON.parse(raw);
|
|
364
|
+
if (parsed.type === "data") {
|
|
365
|
+
messages.push(parsed.data);
|
|
366
|
+
}
|
|
367
|
+
} catch {
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return messages;
|
|
371
|
+
},
|
|
372
|
+
simulateOpen() {
|
|
373
|
+
wsCtrl.simulateOpen();
|
|
374
|
+
},
|
|
375
|
+
simulateMessage(data) {
|
|
376
|
+
wsCtrl.simulateRawMessage(JSON.stringify({ type: "data", data }));
|
|
377
|
+
},
|
|
378
|
+
simulateError(message) {
|
|
379
|
+
wsCtrl.simulateRawMessage(
|
|
380
|
+
JSON.stringify({ type: "error", error: message ?? "Mock error" })
|
|
381
|
+
);
|
|
382
|
+
},
|
|
383
|
+
simulateClose(code) {
|
|
384
|
+
wsCtrl.simulateClose(code);
|
|
385
|
+
},
|
|
386
|
+
get readyState() {
|
|
387
|
+
return wsCtrl.readyState;
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
return { client, controller };
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Set up handlers on the base client to process grpcws envelope messages.
|
|
394
|
+
*/
|
|
395
|
+
setupBaseHandlers() {
|
|
396
|
+
this.base.onMessage = (msg) => {
|
|
397
|
+
this.handleEnvelopeMessage(msg);
|
|
398
|
+
};
|
|
399
|
+
this.base.onClose = () => {
|
|
400
|
+
this.onClose();
|
|
401
|
+
};
|
|
402
|
+
this.base.onError = (error) => {
|
|
403
|
+
this.onError(error);
|
|
404
|
+
};
|
|
405
|
+
this.base.onPing = (pingId) => {
|
|
406
|
+
this.onPing(pingId);
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Handle an incoming envelope message.
|
|
411
|
+
*/
|
|
412
|
+
handleEnvelopeMessage(msg) {
|
|
413
|
+
if (!this.isControlMessage(msg)) {
|
|
414
|
+
console.warn("Received non-envelope message:", msg);
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
const controlMsg = msg;
|
|
418
|
+
switch (controlMsg.type) {
|
|
419
|
+
case "data":
|
|
420
|
+
this.onMessage(controlMsg.data);
|
|
421
|
+
break;
|
|
422
|
+
case "stream_end":
|
|
423
|
+
this.onStreamEnd();
|
|
424
|
+
break;
|
|
425
|
+
case "error":
|
|
426
|
+
this.onError(controlMsg.error ?? "Unknown error");
|
|
427
|
+
break;
|
|
428
|
+
default:
|
|
429
|
+
console.warn("Unknown message type:", controlMsg.type);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Check if a message is a valid control message.
|
|
434
|
+
*/
|
|
435
|
+
isControlMessage(msg) {
|
|
436
|
+
return typeof msg === "object" && msg !== null && "type" in msg && typeof msg.type === "string";
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
// src/typed-client.ts
|
|
441
|
+
var TypedGRPCWSClient = class {
|
|
442
|
+
constructor(options = {}) {
|
|
443
|
+
/** Called when a typed message is received */
|
|
444
|
+
this.onMessage = () => {
|
|
445
|
+
};
|
|
446
|
+
/** Called when the stream ends normally */
|
|
447
|
+
this.onStreamEnd = () => {
|
|
448
|
+
};
|
|
449
|
+
/** Called when the server sends an error */
|
|
450
|
+
this.onError = () => {
|
|
451
|
+
};
|
|
452
|
+
/** Called when the connection closes */
|
|
453
|
+
this.onClose = () => {
|
|
454
|
+
};
|
|
455
|
+
/** Called when a ping is received */
|
|
456
|
+
this.onPing = () => {
|
|
457
|
+
};
|
|
458
|
+
this.client = new GRPCWSClient(options);
|
|
459
|
+
this.setupHandlers();
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Connect to a grpcws WebSocket server.
|
|
463
|
+
* @param url The WebSocket URL to connect to
|
|
464
|
+
* @returns Promise that resolves when connected
|
|
465
|
+
*/
|
|
466
|
+
connect(url) {
|
|
467
|
+
return this.client.connect(url);
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Send a typed message to the server.
|
|
471
|
+
* @param data The typed data payload to send
|
|
472
|
+
*/
|
|
473
|
+
send(data) {
|
|
474
|
+
this.client.send(data);
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Signal that the client is done sending (half-close).
|
|
478
|
+
*/
|
|
479
|
+
endSend() {
|
|
480
|
+
this.client.endSend();
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* Cancel the stream.
|
|
484
|
+
*/
|
|
485
|
+
cancel() {
|
|
486
|
+
this.client.cancel();
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Close the WebSocket connection.
|
|
490
|
+
*/
|
|
491
|
+
close() {
|
|
492
|
+
this.client.close();
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Check if the client is connected.
|
|
496
|
+
*/
|
|
497
|
+
get isConnected() {
|
|
498
|
+
return this.client.isConnected;
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Get the WebSocket ready state.
|
|
502
|
+
*/
|
|
503
|
+
get readyState() {
|
|
504
|
+
return this.client.readyState;
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Set up handlers to forward events with proper typing.
|
|
508
|
+
*/
|
|
509
|
+
setupHandlers() {
|
|
510
|
+
this.client.onMessage = (data) => {
|
|
511
|
+
this.onMessage(data);
|
|
512
|
+
};
|
|
513
|
+
this.client.onStreamEnd = () => {
|
|
514
|
+
this.onStreamEnd();
|
|
515
|
+
};
|
|
516
|
+
this.client.onError = (error) => {
|
|
517
|
+
this.onError(error);
|
|
518
|
+
};
|
|
519
|
+
this.client.onClose = () => {
|
|
520
|
+
this.onClose();
|
|
521
|
+
};
|
|
522
|
+
this.client.onPing = (pingId) => {
|
|
523
|
+
this.onPing(pingId);
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
// src/sse-parser.ts
|
|
529
|
+
var ParseError = class extends Error {
|
|
530
|
+
constructor(message, options) {
|
|
531
|
+
super(message);
|
|
532
|
+
this.name = "ParseError";
|
|
533
|
+
this.type = options.type;
|
|
534
|
+
this.field = options.field;
|
|
535
|
+
this.value = options.value;
|
|
536
|
+
this.line = options.line;
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
function noop(_arg) {
|
|
540
|
+
}
|
|
541
|
+
function createParser(callbacks) {
|
|
542
|
+
if (typeof callbacks === "function") {
|
|
543
|
+
throw new TypeError(
|
|
544
|
+
"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
|
|
548
|
+
let incompleteLine = "";
|
|
549
|
+
let isFirstChunk = true;
|
|
550
|
+
let id;
|
|
551
|
+
let data = "";
|
|
552
|
+
let eventType = "";
|
|
553
|
+
function feed(newChunk) {
|
|
554
|
+
const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk;
|
|
555
|
+
const [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
|
|
556
|
+
for (const line of complete) {
|
|
557
|
+
parseLine(line);
|
|
558
|
+
}
|
|
559
|
+
incompleteLine = incomplete;
|
|
560
|
+
isFirstChunk = false;
|
|
561
|
+
}
|
|
562
|
+
function parseLine(line) {
|
|
563
|
+
if (line === "") {
|
|
564
|
+
dispatchEvent();
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
if (line.startsWith(":")) {
|
|
568
|
+
if (onComment) {
|
|
569
|
+
onComment(line.slice(line.startsWith(": ") ? 2 : 1));
|
|
570
|
+
}
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
const fieldSeparatorIndex = line.indexOf(":");
|
|
574
|
+
if (fieldSeparatorIndex !== -1) {
|
|
575
|
+
const field = line.slice(0, fieldSeparatorIndex);
|
|
576
|
+
const offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1;
|
|
577
|
+
const value = line.slice(fieldSeparatorIndex + offset);
|
|
578
|
+
processField(field, value, line);
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
processField(line, "", line);
|
|
582
|
+
}
|
|
583
|
+
function processField(field, value, line) {
|
|
584
|
+
switch (field) {
|
|
585
|
+
case "event":
|
|
586
|
+
eventType = value;
|
|
587
|
+
break;
|
|
588
|
+
case "data":
|
|
589
|
+
data = `${data}${value}
|
|
590
|
+
`;
|
|
591
|
+
break;
|
|
592
|
+
case "id":
|
|
593
|
+
id = value.includes("\0") ? void 0 : value;
|
|
594
|
+
break;
|
|
595
|
+
case "retry":
|
|
596
|
+
if (/^\d+$/.test(value)) {
|
|
597
|
+
onRetry(parseInt(value, 10));
|
|
598
|
+
} else {
|
|
599
|
+
onError(
|
|
600
|
+
new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
601
|
+
type: "invalid-retry",
|
|
602
|
+
value,
|
|
603
|
+
line
|
|
604
|
+
})
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
break;
|
|
608
|
+
default:
|
|
609
|
+
onError(
|
|
610
|
+
new ParseError(
|
|
611
|
+
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
|
|
612
|
+
{ type: "unknown-field", field, value, line }
|
|
613
|
+
)
|
|
614
|
+
);
|
|
615
|
+
break;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
function dispatchEvent() {
|
|
619
|
+
const shouldDispatch = data.length > 0;
|
|
620
|
+
if (shouldDispatch) {
|
|
621
|
+
onEvent({
|
|
622
|
+
id,
|
|
623
|
+
event: eventType || void 0,
|
|
624
|
+
data: data.endsWith("\n") ? data.slice(0, -1) : data
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
id = void 0;
|
|
628
|
+
data = "";
|
|
629
|
+
eventType = "";
|
|
630
|
+
}
|
|
631
|
+
function reset(options = {}) {
|
|
632
|
+
if (incompleteLine && options.consume) {
|
|
633
|
+
parseLine(incompleteLine);
|
|
634
|
+
}
|
|
635
|
+
isFirstChunk = true;
|
|
636
|
+
id = void 0;
|
|
637
|
+
data = "";
|
|
638
|
+
eventType = "";
|
|
639
|
+
incompleteLine = "";
|
|
640
|
+
}
|
|
641
|
+
return { feed, reset };
|
|
642
|
+
}
|
|
643
|
+
function splitLines(chunk) {
|
|
644
|
+
const lines = [];
|
|
645
|
+
let incompleteLine = "";
|
|
646
|
+
let searchIndex = 0;
|
|
647
|
+
while (searchIndex < chunk.length) {
|
|
648
|
+
const crIndex = chunk.indexOf("\r", searchIndex);
|
|
649
|
+
const lfIndex = chunk.indexOf("\n", searchIndex);
|
|
650
|
+
let lineEnd = -1;
|
|
651
|
+
if (crIndex !== -1 && lfIndex !== -1) {
|
|
652
|
+
lineEnd = Math.min(crIndex, lfIndex);
|
|
653
|
+
} else if (crIndex !== -1) {
|
|
654
|
+
if (crIndex === chunk.length - 1) {
|
|
655
|
+
lineEnd = -1;
|
|
656
|
+
} else {
|
|
657
|
+
lineEnd = crIndex;
|
|
658
|
+
}
|
|
659
|
+
} else if (lfIndex !== -1) {
|
|
660
|
+
lineEnd = lfIndex;
|
|
661
|
+
}
|
|
662
|
+
if (lineEnd === -1) {
|
|
663
|
+
incompleteLine = chunk.slice(searchIndex);
|
|
664
|
+
break;
|
|
665
|
+
} else {
|
|
666
|
+
const line = chunk.slice(searchIndex, lineEnd);
|
|
667
|
+
lines.push(line);
|
|
668
|
+
searchIndex = lineEnd + 1;
|
|
669
|
+
if (chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === "\n") {
|
|
670
|
+
searchIndex++;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
return [lines, incompleteLine];
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// src/sse-mock.ts
|
|
678
|
+
function createMockSSEPair(contentType = "text/event-stream") {
|
|
679
|
+
let streamController = null;
|
|
680
|
+
let capturedUrl;
|
|
681
|
+
let capturedHeaders = {};
|
|
682
|
+
let capturedMethod;
|
|
683
|
+
let capturedBody;
|
|
684
|
+
const encoder = new TextEncoder();
|
|
685
|
+
const enqueue = (text) => {
|
|
686
|
+
if (streamController) {
|
|
687
|
+
streamController.enqueue(encoder.encode(text));
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
const mockFetch = async (input, init) => {
|
|
691
|
+
capturedUrl = typeof input === "string" ? input : input.toString();
|
|
692
|
+
capturedMethod = init?.method ?? "GET";
|
|
693
|
+
capturedBody = typeof init?.body === "string" ? init.body : void 0;
|
|
694
|
+
capturedHeaders = {};
|
|
695
|
+
if (init?.headers) {
|
|
696
|
+
if (init.headers instanceof Headers) {
|
|
697
|
+
init.headers.forEach((v, k) => {
|
|
698
|
+
capturedHeaders[k] = v;
|
|
699
|
+
});
|
|
700
|
+
} else if (Array.isArray(init.headers)) {
|
|
701
|
+
for (const [k, v] of init.headers) {
|
|
702
|
+
capturedHeaders[k] = v;
|
|
703
|
+
}
|
|
704
|
+
} else {
|
|
705
|
+
capturedHeaders = { ...init.headers };
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const body = new ReadableStream({
|
|
709
|
+
start(controller2) {
|
|
710
|
+
streamController = controller2;
|
|
711
|
+
}
|
|
712
|
+
});
|
|
713
|
+
return new Response(body, {
|
|
714
|
+
status: 200,
|
|
715
|
+
headers: { "Content-Type": contentType }
|
|
716
|
+
});
|
|
717
|
+
};
|
|
718
|
+
const controller = {
|
|
719
|
+
simulateMessage(data) {
|
|
720
|
+
enqueue(`data: ${JSON.stringify(data)}
|
|
721
|
+
|
|
722
|
+
`);
|
|
723
|
+
},
|
|
724
|
+
simulateEvent(event, data) {
|
|
725
|
+
enqueue(`event: ${event}
|
|
726
|
+
data: ${JSON.stringify(data)}
|
|
727
|
+
|
|
728
|
+
`);
|
|
729
|
+
},
|
|
730
|
+
simulateEventWithId(event, id, data) {
|
|
731
|
+
enqueue(`event: ${event}
|
|
732
|
+
id: ${id}
|
|
733
|
+
data: ${JSON.stringify(data)}
|
|
734
|
+
|
|
735
|
+
`);
|
|
736
|
+
},
|
|
737
|
+
simulateComment(text) {
|
|
738
|
+
enqueue(`: ${text}
|
|
739
|
+
|
|
740
|
+
`);
|
|
741
|
+
},
|
|
742
|
+
simulateClose() {
|
|
743
|
+
if (streamController) {
|
|
744
|
+
streamController.close();
|
|
745
|
+
streamController = null;
|
|
746
|
+
}
|
|
747
|
+
},
|
|
748
|
+
get receivedUrl() {
|
|
749
|
+
return capturedUrl;
|
|
750
|
+
},
|
|
751
|
+
get receivedHeaders() {
|
|
752
|
+
return capturedHeaders;
|
|
753
|
+
},
|
|
754
|
+
get receivedMethod() {
|
|
755
|
+
return capturedMethod;
|
|
756
|
+
},
|
|
757
|
+
get receivedBody() {
|
|
758
|
+
return capturedBody;
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
return { fetch: mockFetch, controller };
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// src/sse-client.ts
|
|
765
|
+
var SSEClient = class _SSEClient {
|
|
766
|
+
constructor(options = {}) {
|
|
767
|
+
this._connected = false;
|
|
768
|
+
this._abortController = null;
|
|
769
|
+
/** Called when an unnamed data event is received (no "event:" field). */
|
|
770
|
+
this.onMessage = () => {
|
|
771
|
+
};
|
|
772
|
+
/** Called when a named event is received (has "event:" field). */
|
|
773
|
+
this.onEvent = () => {
|
|
774
|
+
};
|
|
775
|
+
/** Called when the SSE stream closes (server closes or network error). */
|
|
776
|
+
this.onClose = () => {
|
|
777
|
+
};
|
|
778
|
+
/** Called when an error occurs (fetch failure, parse error). */
|
|
779
|
+
this.onError = () => {
|
|
780
|
+
};
|
|
781
|
+
this._fetch = options.fetch ?? globalThis.fetch;
|
|
782
|
+
this._headers = options.headers ?? {};
|
|
783
|
+
this._lastEventId = options.lastEventId;
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Connect to an SSE endpoint.
|
|
787
|
+
*
|
|
788
|
+
* @param url The HTTP URL to connect to
|
|
789
|
+
* @returns Promise that resolves when the connection is established (headers received)
|
|
790
|
+
* @throws Error if the response is not 200 or not text/event-stream
|
|
791
|
+
*/
|
|
792
|
+
async connect(url) {
|
|
793
|
+
const headers = { ...this._headers };
|
|
794
|
+
if (this._lastEventId) {
|
|
795
|
+
headers["Last-Event-ID"] = this._lastEventId;
|
|
796
|
+
}
|
|
797
|
+
this._abortController = new AbortController();
|
|
798
|
+
const response = await this._fetch(url, {
|
|
799
|
+
headers,
|
|
800
|
+
signal: this._abortController.signal
|
|
801
|
+
});
|
|
802
|
+
if (!response.ok) {
|
|
803
|
+
throw new Error(`SSE connection failed: HTTP ${response.status}`);
|
|
804
|
+
}
|
|
805
|
+
const contentType = response.headers.get("Content-Type") ?? "";
|
|
806
|
+
if (!contentType.includes("text/event-stream")) {
|
|
807
|
+
throw new Error(`Expected text/event-stream, got ${contentType}`);
|
|
808
|
+
}
|
|
809
|
+
if (!response.body) {
|
|
810
|
+
throw new Error("Response has no body");
|
|
811
|
+
}
|
|
812
|
+
this._connected = true;
|
|
813
|
+
this._readStream(response.body);
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Close the SSE connection.
|
|
817
|
+
* Aborts the underlying fetch request and fires onClose.
|
|
818
|
+
*/
|
|
819
|
+
close() {
|
|
820
|
+
if (this._abortController) {
|
|
821
|
+
this._abortController.abort();
|
|
822
|
+
this._abortController = null;
|
|
823
|
+
}
|
|
824
|
+
if (this._connected) {
|
|
825
|
+
this._connected = false;
|
|
826
|
+
this.onClose();
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
/** Whether the client is currently connected to an SSE stream. */
|
|
830
|
+
get isConnected() {
|
|
831
|
+
return this._connected;
|
|
832
|
+
}
|
|
833
|
+
/** The last event ID received from the server (for reconnection). */
|
|
834
|
+
get lastEventId() {
|
|
835
|
+
return this._lastEventId;
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Create a mock SSEClient + controller pair for testing.
|
|
839
|
+
*
|
|
840
|
+
* @example
|
|
841
|
+
* ```typescript
|
|
842
|
+
* const { client, controller } = SSEClient.createMock();
|
|
843
|
+
* client.onMessage = (data) => received.push(data);
|
|
844
|
+
* await client.connect('http://test/events');
|
|
845
|
+
* controller.simulateMessage({ hello: 'world' });
|
|
846
|
+
* controller.simulateClose();
|
|
847
|
+
* ```
|
|
848
|
+
*/
|
|
849
|
+
static createMock() {
|
|
850
|
+
const { fetch, controller } = createMockSSEPair();
|
|
851
|
+
const client = new _SSEClient({ fetch });
|
|
852
|
+
return { client, controller };
|
|
853
|
+
}
|
|
854
|
+
/** Read the SSE stream and dispatch events via the parser. */
|
|
855
|
+
async _readStream(body) {
|
|
856
|
+
const reader = body.getReader();
|
|
857
|
+
const decoder = new TextDecoder();
|
|
858
|
+
const parser = createParser({
|
|
859
|
+
onEvent: (event) => {
|
|
860
|
+
if (event.id !== void 0) {
|
|
861
|
+
this._lastEventId = event.id;
|
|
862
|
+
}
|
|
863
|
+
let parsed;
|
|
864
|
+
try {
|
|
865
|
+
parsed = JSON.parse(event.data);
|
|
866
|
+
} catch {
|
|
867
|
+
parsed = event.data;
|
|
868
|
+
}
|
|
869
|
+
if (event.event) {
|
|
870
|
+
this.onEvent(event.event, parsed);
|
|
871
|
+
} else {
|
|
872
|
+
this.onMessage(parsed);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
// Comments (keepalive) are silently consumed — no handler needed
|
|
876
|
+
});
|
|
877
|
+
try {
|
|
878
|
+
while (true) {
|
|
879
|
+
const { done, value } = await reader.read();
|
|
880
|
+
if (done) break;
|
|
881
|
+
parser.feed(decoder.decode(value, { stream: true }));
|
|
882
|
+
}
|
|
883
|
+
} catch (err) {
|
|
884
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
this.onError(String(err));
|
|
888
|
+
} finally {
|
|
889
|
+
if (this._connected) {
|
|
890
|
+
this._connected = false;
|
|
891
|
+
this.onClose();
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
};
|
|
896
|
+
|
|
897
|
+
// src/streamable-client.ts
|
|
898
|
+
var StreamableClient = class {
|
|
899
|
+
constructor(options = {}) {
|
|
900
|
+
this._abortController = null;
|
|
901
|
+
/** Called when an unnamed data event is received during streaming. */
|
|
902
|
+
this.onMessage = () => {
|
|
903
|
+
};
|
|
904
|
+
/** Called when a named event is received during streaming. */
|
|
905
|
+
this.onEvent = () => {
|
|
906
|
+
};
|
|
907
|
+
/** Called when the SSE stream completes (channel closed by server). */
|
|
908
|
+
this.onDone = () => {
|
|
909
|
+
};
|
|
910
|
+
/** Called when an error occurs. */
|
|
911
|
+
this.onError = () => {
|
|
912
|
+
};
|
|
913
|
+
this._fetch = options.fetch ?? globalThis.fetch;
|
|
914
|
+
this._headers = options.headers ?? {};
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* POST a request to a StreamableServe endpoint.
|
|
918
|
+
*
|
|
919
|
+
* Returns the parsed response for JSON responses, or undefined for
|
|
920
|
+
* streaming responses (events dispatched via callbacks).
|
|
921
|
+
*
|
|
922
|
+
* @param url The endpoint URL
|
|
923
|
+
* @param body The request body (JSON-serialized)
|
|
924
|
+
* @returns Parsed response (JSON path) or undefined (streaming path)
|
|
925
|
+
*/
|
|
926
|
+
async post(url, body) {
|
|
927
|
+
this._abortController = new AbortController();
|
|
928
|
+
const response = await this._fetch(url, {
|
|
929
|
+
method: "POST",
|
|
930
|
+
headers: {
|
|
931
|
+
"Content-Type": "application/json",
|
|
932
|
+
Accept: "text/event-stream, application/json",
|
|
933
|
+
...this._headers
|
|
934
|
+
},
|
|
935
|
+
body: JSON.stringify(body),
|
|
936
|
+
signal: this._abortController.signal
|
|
937
|
+
});
|
|
938
|
+
if (!response.ok) {
|
|
939
|
+
throw new Error(`Request failed: HTTP ${response.status}`);
|
|
940
|
+
}
|
|
941
|
+
const contentType = response.headers.get("Content-Type") ?? "";
|
|
942
|
+
if (contentType.includes("application/json")) {
|
|
943
|
+
const result = await response.json();
|
|
944
|
+
return result;
|
|
945
|
+
}
|
|
946
|
+
if (contentType.includes("text/event-stream")) {
|
|
947
|
+
if (!response.body) {
|
|
948
|
+
throw new Error("Streaming response has no body");
|
|
949
|
+
}
|
|
950
|
+
await this._readStream(response.body);
|
|
951
|
+
return void 0;
|
|
952
|
+
}
|
|
953
|
+
throw new Error(`Unexpected Content-Type: ${contentType}`);
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Abort the current request/stream.
|
|
957
|
+
*/
|
|
958
|
+
close() {
|
|
959
|
+
if (this._abortController) {
|
|
960
|
+
this._abortController.abort();
|
|
961
|
+
this._abortController = null;
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
/** Read an SSE stream and dispatch events. */
|
|
965
|
+
async _readStream(body) {
|
|
966
|
+
const reader = body.getReader();
|
|
967
|
+
const decoder = new TextDecoder();
|
|
968
|
+
const parser = createParser({
|
|
969
|
+
onEvent: (event) => {
|
|
970
|
+
let parsed;
|
|
971
|
+
try {
|
|
972
|
+
parsed = JSON.parse(event.data);
|
|
973
|
+
} catch {
|
|
974
|
+
parsed = event.data;
|
|
975
|
+
}
|
|
976
|
+
if (event.event) {
|
|
977
|
+
this.onEvent(event.event, parsed);
|
|
978
|
+
} else {
|
|
979
|
+
this.onMessage(parsed);
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
});
|
|
983
|
+
try {
|
|
984
|
+
while (true) {
|
|
985
|
+
const { done, value } = await reader.read();
|
|
986
|
+
if (done) break;
|
|
987
|
+
parser.feed(decoder.decode(value, { stream: true }));
|
|
988
|
+
}
|
|
989
|
+
} catch (err) {
|
|
990
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
this.onError(String(err));
|
|
994
|
+
} finally {
|
|
995
|
+
this.onDone();
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
};
|
|
999
|
+
export {
|
|
1000
|
+
BaseWSClient,
|
|
1001
|
+
BinaryCodec,
|
|
1002
|
+
GRPCWSClient,
|
|
1003
|
+
JSONCodec,
|
|
1004
|
+
ParseError,
|
|
1005
|
+
ReadyState,
|
|
1006
|
+
SSEClient,
|
|
1007
|
+
StreamableClient,
|
|
1008
|
+
TypedGRPCWSClient,
|
|
1009
|
+
createMockSSEPair,
|
|
1010
|
+
createMockWSPair,
|
|
1011
|
+
createParser
|
|
1012
|
+
};
|