@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
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* StreamableClient — Client for ServiceKit StreamableServe endpoints.
|
|
3
|
+
*
|
|
4
|
+
* Supports the "POST-that-optionally-streams" pattern from MCP 2025-03-26:
|
|
5
|
+
* a single endpoint returns either a JSON response (application/json) or
|
|
6
|
+
* an SSE event stream (text/event-stream) based on the server's decision.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* const rpc = new StreamableClient<MyRequest, MyResponse>();
|
|
11
|
+
*
|
|
12
|
+
* // Single response (server returns application/json)
|
|
13
|
+
* const result = await rpc.post('http://localhost:8080/rpc', { method: 'getUser' });
|
|
14
|
+
* console.log(result); // MyResponse
|
|
15
|
+
*
|
|
16
|
+
* // Streaming response (server returns text/event-stream)
|
|
17
|
+
* rpc.onEvent = (type, data) => console.log('progress:', data);
|
|
18
|
+
* rpc.onDone = () => console.log('done');
|
|
19
|
+
* await rpc.post('http://localhost:8080/rpc', { method: 'longOp' });
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
import type { MessageHandler, ErrorHandler, VoidHandler } from './types';
|
|
23
|
+
/**
|
|
24
|
+
* Options for configuring StreamableClient.
|
|
25
|
+
*/
|
|
26
|
+
export interface StreamableClientOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Custom fetch implementation (for Node.js or testing).
|
|
29
|
+
* Default: globalThis.fetch
|
|
30
|
+
*/
|
|
31
|
+
fetch?: typeof globalThis.fetch;
|
|
32
|
+
/**
|
|
33
|
+
* HTTP headers to include in requests.
|
|
34
|
+
* Useful for authentication tokens.
|
|
35
|
+
*/
|
|
36
|
+
headers?: Record<string, string>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Client for StreamableServe endpoints that support both synchronous JSON
|
|
40
|
+
* responses and SSE event streaming from a single POST endpoint.
|
|
41
|
+
*
|
|
42
|
+
* The client POSTs a JSON request body and detects the response Content-Type:
|
|
43
|
+
* - `application/json` → parses body, returns as TOut
|
|
44
|
+
* - `text/event-stream` → streams events via onMessage/onEvent callbacks,
|
|
45
|
+
* calls onDone when complete, returns undefined
|
|
46
|
+
*
|
|
47
|
+
* @see https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http
|
|
48
|
+
*/
|
|
49
|
+
export declare class StreamableClient<TReq = unknown, TOut = unknown> {
|
|
50
|
+
private _fetch;
|
|
51
|
+
private _headers;
|
|
52
|
+
private _abortController;
|
|
53
|
+
/** Called when an unnamed data event is received during streaming. */
|
|
54
|
+
onMessage: MessageHandler<TOut>;
|
|
55
|
+
/** Called when a named event is received during streaming. */
|
|
56
|
+
onEvent: (event: string, data: TOut) => void;
|
|
57
|
+
/** Called when the SSE stream completes (channel closed by server). */
|
|
58
|
+
onDone: VoidHandler;
|
|
59
|
+
/** Called when an error occurs. */
|
|
60
|
+
onError: ErrorHandler;
|
|
61
|
+
constructor(options?: StreamableClientOptions);
|
|
62
|
+
/**
|
|
63
|
+
* POST a request to a StreamableServe endpoint.
|
|
64
|
+
*
|
|
65
|
+
* Returns the parsed response for JSON responses, or undefined for
|
|
66
|
+
* streaming responses (events dispatched via callbacks).
|
|
67
|
+
*
|
|
68
|
+
* @param url The endpoint URL
|
|
69
|
+
* @param body The request body (JSON-serialized)
|
|
70
|
+
* @returns Parsed response (JSON path) or undefined (streaming path)
|
|
71
|
+
*/
|
|
72
|
+
post(url: string, body: TReq): Promise<TOut | undefined>;
|
|
73
|
+
/**
|
|
74
|
+
* Abort the current request/stream.
|
|
75
|
+
*/
|
|
76
|
+
close(): void;
|
|
77
|
+
/** Read an SSE stream and dispatch events. */
|
|
78
|
+
private _readStream;
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=streamable-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"streamable-client.d.ts","sourceRoot":"","sources":["../src/streamable-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAGzE;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAEhC;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;;;;;;;;;GAUG;AACH,qBAAa,gBAAgB,CAAC,IAAI,GAAG,OAAO,EAAE,IAAI,GAAG,OAAO;IAC1D,OAAO,CAAC,MAAM,CAA0B;IACxC,OAAO,CAAC,QAAQ,CAAyB;IACzC,OAAO,CAAC,gBAAgB,CAAgC;IAExD,sEAAsE;IAC/D,SAAS,EAAE,cAAc,CAAC,IAAI,CAAC,CAAY;IAElD,8DAA8D;IACvD,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,KAAK,IAAI,CAAY;IAE/D,uEAAuE;IAChE,MAAM,EAAE,WAAW,CAAY;IAEtC,mCAAmC;IAC5B,OAAO,EAAE,YAAY,CAAY;gBAE5B,OAAO,GAAE,uBAA4B;IAKjD;;;;;;;;;OASG;IACG,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC;IAsC9D;;OAEG;IACH,KAAK,IAAI,IAAI;IAOb,8CAA8C;YAChC,WAAW;CAoC1B"}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* StreamableClient — Client for ServiceKit StreamableServe endpoints.
|
|
4
|
+
*
|
|
5
|
+
* Supports the "POST-that-optionally-streams" pattern from MCP 2025-03-26:
|
|
6
|
+
* a single endpoint returns either a JSON response (application/json) or
|
|
7
|
+
* an SSE event stream (text/event-stream) based on the server's decision.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* const rpc = new StreamableClient<MyRequest, MyResponse>();
|
|
12
|
+
*
|
|
13
|
+
* // Single response (server returns application/json)
|
|
14
|
+
* const result = await rpc.post('http://localhost:8080/rpc', { method: 'getUser' });
|
|
15
|
+
* console.log(result); // MyResponse
|
|
16
|
+
*
|
|
17
|
+
* // Streaming response (server returns text/event-stream)
|
|
18
|
+
* rpc.onEvent = (type, data) => console.log('progress:', data);
|
|
19
|
+
* rpc.onDone = () => console.log('done');
|
|
20
|
+
* await rpc.post('http://localhost:8080/rpc', { method: 'longOp' });
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.StreamableClient = void 0;
|
|
25
|
+
const sse_parser_1 = require("./sse-parser");
|
|
26
|
+
/**
|
|
27
|
+
* Client for StreamableServe endpoints that support both synchronous JSON
|
|
28
|
+
* responses and SSE event streaming from a single POST endpoint.
|
|
29
|
+
*
|
|
30
|
+
* The client POSTs a JSON request body and detects the response Content-Type:
|
|
31
|
+
* - `application/json` → parses body, returns as TOut
|
|
32
|
+
* - `text/event-stream` → streams events via onMessage/onEvent callbacks,
|
|
33
|
+
* calls onDone when complete, returns undefined
|
|
34
|
+
*
|
|
35
|
+
* @see https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http
|
|
36
|
+
*/
|
|
37
|
+
class StreamableClient {
|
|
38
|
+
constructor(options = {}) {
|
|
39
|
+
this._abortController = null;
|
|
40
|
+
/** Called when an unnamed data event is received during streaming. */
|
|
41
|
+
this.onMessage = () => { };
|
|
42
|
+
/** Called when a named event is received during streaming. */
|
|
43
|
+
this.onEvent = () => { };
|
|
44
|
+
/** Called when the SSE stream completes (channel closed by server). */
|
|
45
|
+
this.onDone = () => { };
|
|
46
|
+
/** Called when an error occurs. */
|
|
47
|
+
this.onError = () => { };
|
|
48
|
+
this._fetch = options.fetch ?? globalThis.fetch;
|
|
49
|
+
this._headers = options.headers ?? {};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* POST a request to a StreamableServe endpoint.
|
|
53
|
+
*
|
|
54
|
+
* Returns the parsed response for JSON responses, or undefined for
|
|
55
|
+
* streaming responses (events dispatched via callbacks).
|
|
56
|
+
*
|
|
57
|
+
* @param url The endpoint URL
|
|
58
|
+
* @param body The request body (JSON-serialized)
|
|
59
|
+
* @returns Parsed response (JSON path) or undefined (streaming path)
|
|
60
|
+
*/
|
|
61
|
+
async post(url, body) {
|
|
62
|
+
this._abortController = new AbortController();
|
|
63
|
+
const response = await this._fetch(url, {
|
|
64
|
+
method: 'POST',
|
|
65
|
+
headers: {
|
|
66
|
+
'Content-Type': 'application/json',
|
|
67
|
+
Accept: 'text/event-stream, application/json',
|
|
68
|
+
...this._headers,
|
|
69
|
+
},
|
|
70
|
+
body: JSON.stringify(body),
|
|
71
|
+
signal: this._abortController.signal,
|
|
72
|
+
});
|
|
73
|
+
if (!response.ok) {
|
|
74
|
+
throw new Error(`Request failed: HTTP ${response.status}`);
|
|
75
|
+
}
|
|
76
|
+
const contentType = response.headers.get('Content-Type') ?? '';
|
|
77
|
+
// JSON response path (synchronous)
|
|
78
|
+
if (contentType.includes('application/json')) {
|
|
79
|
+
const result = (await response.json());
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
// SSE streaming path
|
|
83
|
+
if (contentType.includes('text/event-stream')) {
|
|
84
|
+
if (!response.body) {
|
|
85
|
+
throw new Error('Streaming response has no body');
|
|
86
|
+
}
|
|
87
|
+
await this._readStream(response.body);
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
throw new Error(`Unexpected Content-Type: ${contentType}`);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Abort the current request/stream.
|
|
94
|
+
*/
|
|
95
|
+
close() {
|
|
96
|
+
if (this._abortController) {
|
|
97
|
+
this._abortController.abort();
|
|
98
|
+
this._abortController = null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** Read an SSE stream and dispatch events. */
|
|
102
|
+
async _readStream(body) {
|
|
103
|
+
const reader = body.getReader();
|
|
104
|
+
const decoder = new TextDecoder();
|
|
105
|
+
const parser = (0, sse_parser_1.createParser)({
|
|
106
|
+
onEvent: (event) => {
|
|
107
|
+
let parsed;
|
|
108
|
+
try {
|
|
109
|
+
parsed = JSON.parse(event.data);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
parsed = event.data;
|
|
113
|
+
}
|
|
114
|
+
if (event.event) {
|
|
115
|
+
this.onEvent(event.event, parsed);
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
this.onMessage(parsed);
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
try {
|
|
123
|
+
while (true) {
|
|
124
|
+
const { done, value } = await reader.read();
|
|
125
|
+
if (done)
|
|
126
|
+
break;
|
|
127
|
+
parser.feed(decoder.decode(value, { stream: true }));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
catch (err) {
|
|
131
|
+
if (err instanceof Error && err.name === 'AbortError') {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
this.onError(String(err));
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
this.onDone();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
exports.StreamableClient = StreamableClient;
|
|
142
|
+
//# sourceMappingURL=streamable-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"streamable-client.js","sourceRoot":"","sources":["../src/streamable-client.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAGH,6CAA4C;AAmB5C;;;;;;;;;;GAUG;AACH,MAAa,gBAAgB;IAiB3B,YAAY,UAAmC,EAAE;QAdzC,qBAAgB,GAA2B,IAAI,CAAC;QAExD,sEAAsE;QAC/D,cAAS,GAAyB,GAAG,EAAE,GAAE,CAAC,CAAC;QAElD,8DAA8D;QACvD,YAAO,GAAwC,GAAG,EAAE,GAAE,CAAC,CAAC;QAE/D,uEAAuE;QAChE,WAAM,GAAgB,GAAG,EAAE,GAAE,CAAC,CAAC;QAEtC,mCAAmC;QAC5B,YAAO,GAAiB,GAAG,EAAE,GAAE,CAAC,CAAC;QAGtC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,KAAK,IAAI,UAAU,CAAC,KAAK,CAAC;QAChD,IAA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;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,GAAG,YAAY,KAAK,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;gBACtD,OAAO;YACT,CAAC;YACD,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QAC5B,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,MAAM,EAAE,CAAC;QAChB,CAAC;IACH,CAAC;CACF;AArHD,4CAqHC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@panyam/servicekit-client",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "TypeScript client for
|
|
3
|
+
"version": "0.0.7",
|
|
4
|
+
"description": "TypeScript client for ServiceKit WebSocket and SSE protocols",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
7
7
|
"types": "dist/index.d.ts",
|
|
@@ -10,16 +10,12 @@
|
|
|
10
10
|
"dist",
|
|
11
11
|
"src"
|
|
12
12
|
],
|
|
13
|
-
"scripts": {
|
|
14
|
-
"build": "tsc && npm run build:browser",
|
|
15
|
-
"build:browser": "esbuild src/index.ts --bundle --format=iife --global-name=ServiceKit --outfile=dist/servicekit-client.browser.js",
|
|
16
|
-
"clean": "rm -rf dist",
|
|
17
|
-
"prepublishOnly": "npm run build"
|
|
18
|
-
},
|
|
19
13
|
"keywords": [
|
|
20
14
|
"grpc",
|
|
21
15
|
"websocket",
|
|
22
16
|
"streaming",
|
|
17
|
+
"sse",
|
|
18
|
+
"server-sent-events",
|
|
23
19
|
"protobuf",
|
|
24
20
|
"typescript",
|
|
25
21
|
"servicekit"
|
|
@@ -33,9 +29,17 @@
|
|
|
33
29
|
},
|
|
34
30
|
"devDependencies": {
|
|
35
31
|
"esbuild": "^0.24.0",
|
|
36
|
-
"typescript": "^5.3.0"
|
|
32
|
+
"typescript": "^5.3.0",
|
|
33
|
+
"vitest": "^4.1.2"
|
|
37
34
|
},
|
|
38
35
|
"engines": {
|
|
39
36
|
"node": ">=16.0.0"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsc && npm run build:esm && npm run build:browser",
|
|
40
|
+
"build:esm": "esbuild src/index.ts --bundle --format=esm --outfile=dist/index.mjs",
|
|
41
|
+
"build:browser": "esbuild src/index.ts --bundle --format=iife --global-name=ServiceKit --outfile=dist/servicekit-client.browser.js",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"clean": "rm -rf dist"
|
|
40
44
|
}
|
|
41
|
-
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { createParser, EventSourceMessage } from '../sse-parser';
|
|
3
|
+
import { SSEClient } from '../sse-client';
|
|
4
|
+
import { StreamableClient } from '../streamable-client';
|
|
5
|
+
import { createMockSSEPair } from '../sse-mock';
|
|
6
|
+
|
|
7
|
+
// ============================================================================
|
|
8
|
+
// SSE Parser Tests
|
|
9
|
+
// ============================================================================
|
|
10
|
+
|
|
11
|
+
describe('SSEParser', () => {
|
|
12
|
+
/**
|
|
13
|
+
* Verifies basic SSE data event parsing: a single "data:" line followed
|
|
14
|
+
* by a blank line should fire onEvent with the data content.
|
|
15
|
+
*/
|
|
16
|
+
it('parses basic data event', () => {
|
|
17
|
+
const events: EventSourceMessage[] = [];
|
|
18
|
+
const parser = createParser({ onEvent: (e) => events.push(e) });
|
|
19
|
+
|
|
20
|
+
parser.feed('data: {"msg":"hello"}\n\n');
|
|
21
|
+
|
|
22
|
+
expect(events).toHaveLength(1);
|
|
23
|
+
expect(events[0].data).toBe('{"msg":"hello"}');
|
|
24
|
+
expect(events[0].event).toBeUndefined();
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Verifies named event parsing: "event:" field sets the event type,
|
|
29
|
+
* which clients use with EventSource.addEventListener(type, handler).
|
|
30
|
+
*/
|
|
31
|
+
it('parses named event', () => {
|
|
32
|
+
const events: EventSourceMessage[] = [];
|
|
33
|
+
const parser = createParser({ onEvent: (e) => events.push(e) });
|
|
34
|
+
|
|
35
|
+
parser.feed('event: update\ndata: {"version":3}\n\n');
|
|
36
|
+
|
|
37
|
+
expect(events).toHaveLength(1);
|
|
38
|
+
expect(events[0].event).toBe('update');
|
|
39
|
+
expect(events[0].data).toBe('{"version":3}');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Verifies "id:" field tracking: the parser passes the id through to
|
|
44
|
+
* the event, enabling Last-Event-ID reconnection support.
|
|
45
|
+
*/
|
|
46
|
+
it('parses event with id', () => {
|
|
47
|
+
const events: EventSourceMessage[] = [];
|
|
48
|
+
const parser = createParser({ onEvent: (e) => events.push(e) });
|
|
49
|
+
|
|
50
|
+
parser.feed('id: 42\nevent: msg\ndata: hello\n\n');
|
|
51
|
+
|
|
52
|
+
expect(events[0].id).toBe('42');
|
|
53
|
+
expect(events[0].event).toBe('msg');
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Verifies multi-line data handling: per WHATWG SSE spec, multiple
|
|
58
|
+
* "data:" lines are joined with "\n" characters.
|
|
59
|
+
*/
|
|
60
|
+
it('joins multi-line data with newlines', () => {
|
|
61
|
+
const events: EventSourceMessage[] = [];
|
|
62
|
+
const parser = createParser({ onEvent: (e) => events.push(e) });
|
|
63
|
+
|
|
64
|
+
parser.feed('data: line1\ndata: line2\ndata: line3\n\n');
|
|
65
|
+
|
|
66
|
+
expect(events[0].data).toBe('line1\nline2\nline3');
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Verifies that SSE comments (lines starting with ":") are passed to
|
|
71
|
+
* the onComment callback but do NOT fire onEvent. This is how servers
|
|
72
|
+
* send keepalive signals.
|
|
73
|
+
*/
|
|
74
|
+
it('ignores comments, does not fire onEvent', () => {
|
|
75
|
+
const events: EventSourceMessage[] = [];
|
|
76
|
+
const comments: string[] = [];
|
|
77
|
+
const parser = createParser({
|
|
78
|
+
onEvent: (e) => events.push(e),
|
|
79
|
+
onComment: (c) => comments.push(c),
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
parser.feed(': keepalive\n\n');
|
|
83
|
+
parser.feed('data: real\n\n');
|
|
84
|
+
|
|
85
|
+
expect(events).toHaveLength(1);
|
|
86
|
+
expect(events[0].data).toBe('real');
|
|
87
|
+
expect(comments).toEqual(['keepalive']);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Verifies CRLF line ending handling: per WHATWG spec, SSE must support
|
|
92
|
+
* CR+LF, LF, and CR as line terminators.
|
|
93
|
+
*/
|
|
94
|
+
it('handles CRLF line endings', () => {
|
|
95
|
+
const events: EventSourceMessage[] = [];
|
|
96
|
+
const parser = createParser({ onEvent: (e) => events.push(e) });
|
|
97
|
+
|
|
98
|
+
parser.feed('data: hello\r\n\r\n');
|
|
99
|
+
|
|
100
|
+
expect(events).toHaveLength(1);
|
|
101
|
+
expect(events[0].data).toBe('hello');
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Verifies UTF-8 BOM stripping: the parser removes the BOM from the
|
|
106
|
+
* first chunk per WHATWG spec requirement.
|
|
107
|
+
*/
|
|
108
|
+
it('strips UTF-8 BOM from first chunk', () => {
|
|
109
|
+
const events: EventSourceMessage[] = [];
|
|
110
|
+
const parser = createParser({ onEvent: (e) => events.push(e) });
|
|
111
|
+
|
|
112
|
+
parser.feed('\xEF\xBB\xBFdata: hello\n\n');
|
|
113
|
+
|
|
114
|
+
expect(events).toHaveLength(1);
|
|
115
|
+
expect(events[0].data).toBe('hello');
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Verifies that data split across multiple feed() calls is correctly
|
|
120
|
+
* buffered and parsed when the terminating blank line arrives.
|
|
121
|
+
*/
|
|
122
|
+
it('handles chunked data across feed calls', () => {
|
|
123
|
+
const events: EventSourceMessage[] = [];
|
|
124
|
+
const parser = createParser({ onEvent: (e) => events.push(e) });
|
|
125
|
+
|
|
126
|
+
parser.feed('data: hel');
|
|
127
|
+
parser.feed('lo\n\n');
|
|
128
|
+
|
|
129
|
+
expect(events).toHaveLength(1);
|
|
130
|
+
expect(events[0].data).toBe('hello');
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
// ============================================================================
|
|
135
|
+
// SSEClient Tests
|
|
136
|
+
// ============================================================================
|
|
137
|
+
|
|
138
|
+
describe('SSEClient', () => {
|
|
139
|
+
/**
|
|
140
|
+
* Verifies that SSEClient connects via mock fetch, receives data events,
|
|
141
|
+
* and dispatches them to the onMessage handler with parsed JSON.
|
|
142
|
+
*/
|
|
143
|
+
it('connects and receives messages', async () => {
|
|
144
|
+
const { client, controller } = SSEClient.createMock();
|
|
145
|
+
const received: unknown[] = [];
|
|
146
|
+
client.onMessage = (data) => received.push(data);
|
|
147
|
+
|
|
148
|
+
await client.connect('http://test/events');
|
|
149
|
+
expect(client.isConnected).toBe(true);
|
|
150
|
+
|
|
151
|
+
controller.simulateMessage({ greeting: 'hello' });
|
|
152
|
+
controller.simulateClose();
|
|
153
|
+
|
|
154
|
+
// Wait for async stream processing
|
|
155
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
156
|
+
|
|
157
|
+
expect(received).toHaveLength(1);
|
|
158
|
+
expect(received[0]).toEqual({ greeting: 'hello' });
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Verifies that named events (with "event:" field) are dispatched to
|
|
163
|
+
* the onEvent handler with the event type and parsed data.
|
|
164
|
+
*/
|
|
165
|
+
it('dispatches named events to onEvent', async () => {
|
|
166
|
+
const { client, controller } = SSEClient.createMock();
|
|
167
|
+
const events: Array<{ type: string; data: unknown }> = [];
|
|
168
|
+
client.onEvent = (type, data) => events.push({ type, data });
|
|
169
|
+
|
|
170
|
+
await client.connect('http://test/events');
|
|
171
|
+
controller.simulateEvent('update', { version: 3 });
|
|
172
|
+
controller.simulateClose();
|
|
173
|
+
|
|
174
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
175
|
+
|
|
176
|
+
expect(events).toHaveLength(1);
|
|
177
|
+
expect(events[0].type).toBe('update');
|
|
178
|
+
expect(events[0].data).toEqual({ version: 3 });
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Verifies that keepalive comments (": keepalive") are silently consumed
|
|
183
|
+
* and do NOT trigger onMessage or onEvent.
|
|
184
|
+
*/
|
|
185
|
+
it('filters keepalive comments', async () => {
|
|
186
|
+
const { client, controller } = SSEClient.createMock();
|
|
187
|
+
const received: unknown[] = [];
|
|
188
|
+
client.onMessage = (data) => received.push(data);
|
|
189
|
+
|
|
190
|
+
await client.connect('http://test/events');
|
|
191
|
+
controller.simulateComment('keepalive');
|
|
192
|
+
controller.simulateMessage({ real: true });
|
|
193
|
+
controller.simulateClose();
|
|
194
|
+
|
|
195
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
196
|
+
|
|
197
|
+
expect(received).toHaveLength(1);
|
|
198
|
+
expect(received[0]).toEqual({ real: true });
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Verifies that the "id:" field from events is tracked in lastEventId,
|
|
203
|
+
* enabling reconnection via the Last-Event-ID header.
|
|
204
|
+
*/
|
|
205
|
+
it('tracks lastEventId from events', async () => {
|
|
206
|
+
const { client, controller } = SSEClient.createMock();
|
|
207
|
+
|
|
208
|
+
await client.connect('http://test/events');
|
|
209
|
+
expect(client.lastEventId).toBeUndefined();
|
|
210
|
+
|
|
211
|
+
controller.simulateEventWithId('msg', 'evt-99', { data: 'test' });
|
|
212
|
+
controller.simulateClose();
|
|
213
|
+
|
|
214
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
215
|
+
|
|
216
|
+
expect(client.lastEventId).toBe('evt-99');
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Verifies that close() fires the onClose handler.
|
|
221
|
+
*/
|
|
222
|
+
it('fires onClose when stream ends', async () => {
|
|
223
|
+
const { client, controller } = SSEClient.createMock();
|
|
224
|
+
let closed = false;
|
|
225
|
+
client.onClose = () => { closed = true; };
|
|
226
|
+
|
|
227
|
+
await client.connect('http://test/events');
|
|
228
|
+
controller.simulateClose();
|
|
229
|
+
|
|
230
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
231
|
+
|
|
232
|
+
expect(closed).toBe(true);
|
|
233
|
+
expect(client.isConnected).toBe(false);
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Verifies that createMock captures the request URL and headers
|
|
238
|
+
* for test assertions.
|
|
239
|
+
*/
|
|
240
|
+
it('createMock captures request details', async () => {
|
|
241
|
+
const { fetch, controller } = createMockSSEPair();
|
|
242
|
+
const client = new SSEClient({
|
|
243
|
+
fetch,
|
|
244
|
+
headers: { Authorization: 'Bearer token123' },
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
await client.connect('http://test/events');
|
|
248
|
+
controller.simulateClose();
|
|
249
|
+
|
|
250
|
+
expect(controller.receivedUrl).toBe('http://test/events');
|
|
251
|
+
expect(controller.receivedHeaders['Authorization']).toBe('Bearer token123');
|
|
252
|
+
|
|
253
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
// ============================================================================
|
|
258
|
+
// StreamableClient Tests
|
|
259
|
+
// ============================================================================
|
|
260
|
+
|
|
261
|
+
describe('StreamableClient', () => {
|
|
262
|
+
/**
|
|
263
|
+
* Verifies that when the server responds with application/json,
|
|
264
|
+
* StreamableClient parses the JSON body and returns it directly.
|
|
265
|
+
* This is the synchronous (non-streaming) path.
|
|
266
|
+
*/
|
|
267
|
+
it('returns parsed JSON for application/json response', async () => {
|
|
268
|
+
const { fetch } = createMockSSEPair('application/json');
|
|
269
|
+
const client = new StreamableClient<{ method: string }, { result: string }>({ fetch });
|
|
270
|
+
|
|
271
|
+
// Override the mock to return JSON instead of a stream
|
|
272
|
+
const jsonFetch = (async (_url: RequestInfo | URL, _init?: RequestInit) => {
|
|
273
|
+
return new Response(JSON.stringify({ result: 'ok' }), {
|
|
274
|
+
status: 200,
|
|
275
|
+
headers: { 'Content-Type': 'application/json' },
|
|
276
|
+
});
|
|
277
|
+
}) as typeof globalThis.fetch;
|
|
278
|
+
|
|
279
|
+
const jsonClient = new StreamableClient<{ method: string }, { result: string }>({
|
|
280
|
+
fetch: jsonFetch,
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
const result = await jsonClient.post('http://test/rpc', { method: 'getUser' });
|
|
284
|
+
|
|
285
|
+
expect(result).toEqual({ result: 'ok' });
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Verifies that when the server responds with text/event-stream,
|
|
290
|
+
* StreamableClient streams events via onMessage/onEvent callbacks
|
|
291
|
+
* and calls onDone when the stream completes.
|
|
292
|
+
*/
|
|
293
|
+
it('streams SSE events for text/event-stream response', async () => {
|
|
294
|
+
const { fetch, controller } = createMockSSEPair('text/event-stream');
|
|
295
|
+
const client = new StreamableClient<{ method: string }, { progress: number }>({ fetch });
|
|
296
|
+
|
|
297
|
+
const events: unknown[] = [];
|
|
298
|
+
let done = false;
|
|
299
|
+
client.onMessage = (data) => events.push(data);
|
|
300
|
+
client.onDone = () => { done = true; };
|
|
301
|
+
|
|
302
|
+
const postPromise = client.post('http://test/rpc', { method: 'longOp' });
|
|
303
|
+
|
|
304
|
+
// Give the fetch a moment to resolve
|
|
305
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
306
|
+
|
|
307
|
+
controller.simulateMessage({ progress: 50 });
|
|
308
|
+
controller.simulateMessage({ progress: 100 });
|
|
309
|
+
controller.simulateClose();
|
|
310
|
+
|
|
311
|
+
await postPromise;
|
|
312
|
+
|
|
313
|
+
expect(events).toHaveLength(2);
|
|
314
|
+
expect(events[0]).toEqual({ progress: 50 });
|
|
315
|
+
expect(events[1]).toEqual({ progress: 100 });
|
|
316
|
+
expect(done).toBe(true);
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Verifies that onDone fires when the SSE stream ends, even if
|
|
321
|
+
* no events were received.
|
|
322
|
+
*/
|
|
323
|
+
it('fires onDone when stream completes', async () => {
|
|
324
|
+
const { fetch, controller } = createMockSSEPair('text/event-stream');
|
|
325
|
+
const client = new StreamableClient({ fetch });
|
|
326
|
+
|
|
327
|
+
let done = false;
|
|
328
|
+
client.onDone = () => { done = true; };
|
|
329
|
+
|
|
330
|
+
const postPromise = client.post('http://test/rpc', {});
|
|
331
|
+
|
|
332
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
333
|
+
controller.simulateClose();
|
|
334
|
+
|
|
335
|
+
await postPromise;
|
|
336
|
+
|
|
337
|
+
expect(done).toBe(true);
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Verifies that StreamableClient sends the request body as JSON
|
|
342
|
+
* and includes proper headers (Content-Type, Accept).
|
|
343
|
+
*/
|
|
344
|
+
it('sends POST with correct headers and body', async () => {
|
|
345
|
+
const { fetch, controller } = createMockSSEPair('text/event-stream');
|
|
346
|
+
const client = new StreamableClient({ fetch });
|
|
347
|
+
|
|
348
|
+
const postPromise = client.post('http://test/rpc', { method: 'test', id: 42 });
|
|
349
|
+
|
|
350
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
351
|
+
controller.simulateClose();
|
|
352
|
+
await postPromise;
|
|
353
|
+
|
|
354
|
+
expect(controller.receivedMethod).toBe('POST');
|
|
355
|
+
expect(controller.receivedBody).toBe('{"method":"test","id":42}');
|
|
356
|
+
expect(controller.receivedHeaders['Content-Type']).toBe('application/json');
|
|
357
|
+
});
|
|
358
|
+
});
|
package/src/index.ts
CHANGED
|
@@ -1,23 +1,28 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @panyam/servicekit-client
|
|
3
3
|
*
|
|
4
|
-
* TypeScript client library for ServiceKit WebSocket protocols.
|
|
4
|
+
* TypeScript client library for ServiceKit WebSocket and SSE protocols.
|
|
5
5
|
*
|
|
6
6
|
* ## Architecture
|
|
7
7
|
*
|
|
8
8
|
* The client mirrors the server-side architecture with two layers:
|
|
9
|
-
* - **Transport layer**: Handles WebSocket connection, ping/pong heartbeats
|
|
9
|
+
* - **Transport layer**: Handles WebSocket/SSE connection, ping/pong heartbeats
|
|
10
10
|
* - **Codec layer**: Handles encoding/decoding of data messages
|
|
11
11
|
*
|
|
12
12
|
* Control messages (ping, pong, error) are always JSON at the transport layer,
|
|
13
13
|
* while data messages use the configured codec (JSON, binary protobuf, etc.).
|
|
14
14
|
*
|
|
15
|
-
* ## Clients
|
|
15
|
+
* ## WebSocket Clients
|
|
16
16
|
*
|
|
17
17
|
* - `BaseWSClient`: Low-level WebSocket with auto ping/pong (for http/JSONConn)
|
|
18
18
|
* - `GRPCWSClient`: gRPC-style streaming with envelope protocol (for grpcws)
|
|
19
19
|
* - `TypedGRPCWSClient`: Type-safe wrapper for GRPCWSClient
|
|
20
20
|
*
|
|
21
|
+
* ## SSE Clients
|
|
22
|
+
*
|
|
23
|
+
* - `SSEClient`: Server-Sent Events client (for http/SSEServe endpoints)
|
|
24
|
+
* - `StreamableClient`: POST-that-optionally-streams (for http/StreamableServe)
|
|
25
|
+
*
|
|
21
26
|
* ## Codecs
|
|
22
27
|
*
|
|
23
28
|
* - `JSONCodec`: Default, matches server-side JSONCodec
|
|
@@ -80,5 +85,19 @@ export { BaseWSClient } from './base-client';
|
|
|
80
85
|
export { GRPCWSClient, MockController } from './grpcws-client';
|
|
81
86
|
export { TypedGRPCWSClient } from './typed-client';
|
|
82
87
|
|
|
88
|
+
// SSE Clients
|
|
89
|
+
export { SSEClient, SSEClientOptions } from './sse-client';
|
|
90
|
+
export { StreamableClient, StreamableClientOptions } from './streamable-client';
|
|
91
|
+
|
|
92
|
+
// SSE Parser (vendored from eventsource-parser, MIT)
|
|
93
|
+
export {
|
|
94
|
+
createParser,
|
|
95
|
+
EventSourceMessage,
|
|
96
|
+
EventSourceParser,
|
|
97
|
+
ParserCallbacks,
|
|
98
|
+
ParseError,
|
|
99
|
+
} from './sse-parser';
|
|
100
|
+
|
|
83
101
|
// Test utilities
|
|
84
102
|
export { createMockWSPair, MockWSController } from './mock';
|
|
103
|
+
export { createMockSSEPair, MockSSEController } from './sse-mock';
|