@panyam/servicekit-client 0.0.6 → 0.1.9
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/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 +478 -1
- 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 +13 -7
- package/src/DESIGN.md +132 -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,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC;IACxC,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,IAAI,CAAC,GAAW,EAAE,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O;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,19 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@panyam/servicekit-client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "TypeScript client for
|
|
3
|
+
"version": "0.1.9",
|
|
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",
|
|
8
8
|
"browser": "dist/servicekit-client.browser.js",
|
|
9
9
|
"files": [
|
|
10
10
|
"dist",
|
|
11
|
-
"src"
|
|
11
|
+
"src",
|
|
12
|
+
"!src/**/__tests__",
|
|
13
|
+
"!src/**/*.test.ts"
|
|
12
14
|
],
|
|
13
15
|
"scripts": {
|
|
14
|
-
"build": "tsc && npm run build:esm && npm run build:browser",
|
|
16
|
+
"build": "tsc -p tsconfig.build.json && npm run build:esm && npm run build:browser",
|
|
15
17
|
"build:esm": "esbuild src/index.ts --bundle --format=esm --outfile=dist/index.mjs",
|
|
16
18
|
"build:browser": "esbuild src/index.ts --bundle --format=iife --global-name=ServiceKit --outfile=dist/servicekit-client.browser.js",
|
|
19
|
+
"test": "vitest run",
|
|
17
20
|
"clean": "rm -rf dist",
|
|
18
21
|
"prepublishOnly": "npm run build"
|
|
19
22
|
},
|
|
@@ -21,6 +24,8 @@
|
|
|
21
24
|
"grpc",
|
|
22
25
|
"websocket",
|
|
23
26
|
"streaming",
|
|
27
|
+
"sse",
|
|
28
|
+
"server-sent-events",
|
|
24
29
|
"protobuf",
|
|
25
30
|
"typescript",
|
|
26
31
|
"servicekit"
|
|
@@ -29,12 +34,13 @@
|
|
|
29
34
|
"license": "MIT",
|
|
30
35
|
"repository": {
|
|
31
36
|
"type": "git",
|
|
32
|
-
"url": "https://github.com/panyam/servicekit.git",
|
|
37
|
+
"url": "git+https://github.com/panyam/servicekit.git",
|
|
33
38
|
"directory": "clients/typescript"
|
|
34
39
|
},
|
|
35
40
|
"devDependencies": {
|
|
36
|
-
"esbuild": "^0.
|
|
37
|
-
"typescript": "^5.3.0"
|
|
41
|
+
"esbuild": "^0.27.0",
|
|
42
|
+
"typescript": "^5.3.0",
|
|
43
|
+
"vitest": "^4.1.2"
|
|
38
44
|
},
|
|
39
45
|
"engines": {
|
|
40
46
|
"node": ">=16.0.0"
|
package/src/DESIGN.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
---
|
|
2
|
+
package: servicekit-typescript-client
|
|
3
|
+
purpose: TypeScript client library for ServiceKit's WebSocket, gRPC-over-WebSocket, SSE, and streamable-HTTP transports, mirroring the server's transport/codec split.
|
|
4
|
+
last_rebuilt: 04f5d50ab9801bba49c428990700c9aded8b119b
|
|
5
|
+
depends_on:
|
|
6
|
+
entities:
|
|
7
|
+
- name: BaseWSClient
|
|
8
|
+
kind: class
|
|
9
|
+
role: Low-level WebSocket client with automatic ping/pong heartbeat and codec-driven data framing.
|
|
10
|
+
why: Control messages (ping/pong/error) are always JSON at the transport layer even when data uses a binary codec; pings are auto-answered without surfacing pong handling to callers.
|
|
11
|
+
- name: GRPCWSClient
|
|
12
|
+
kind: class
|
|
13
|
+
role: Wraps BaseWSClient to speak the grpcws envelope protocol (data/error/stream_end inbound; data/end_send/cancel outbound).
|
|
14
|
+
why: Adds half-close (endSend) and cancel semantics for the three gRPC streaming patterns; envelope wrap/unwrap is hidden so consumers only see application payloads.
|
|
15
|
+
- name: TypedGRPCWSClient
|
|
16
|
+
kind: class
|
|
17
|
+
role: Generic compile-time-typed facade over GRPCWSClient parameterized by TIn/TOut.
|
|
18
|
+
why: Pure type safety — it casts unknown to TOut on receive (protobuf JSON is assumed to match the TS type), adding no runtime behavior.
|
|
19
|
+
- name: SSEClient
|
|
20
|
+
kind: class
|
|
21
|
+
role: Server-Sent Events client for SSEServe endpoints, built on fetch + ReadableStream.
|
|
22
|
+
why: Deliberately avoids native EventSource because that is GET-only and cannot send custom headers; this enables auth tokens, POST, and Last-Event-ID reconnection tracking.
|
|
23
|
+
- name: StreamableClient
|
|
24
|
+
kind: class
|
|
25
|
+
role: Client for StreamableServe endpoints implementing MCP's POST-that-optionally-streams pattern.
|
|
26
|
+
why: A single POST may return application/json (returns parsed TOut) or text/event-stream (dispatches via callbacks, returns undefined) — branch is decided by response Content-Type, not the caller.
|
|
27
|
+
- name: Codec
|
|
28
|
+
kind: interface
|
|
29
|
+
role: Encode/decode contract for business data messages (string or ArrayBuffer).
|
|
30
|
+
why: Only covers data messages; control frames bypass the codec entirely, keeping the transport protocol codec-agnostic.
|
|
31
|
+
- name: JSONCodec
|
|
32
|
+
kind: class
|
|
33
|
+
role: Default codec; JSON-stringify/parse, handling both text and ArrayBuffer inbound.
|
|
34
|
+
why: Matches the server's JSONCodec so the default client works out of the box with no configuration.
|
|
35
|
+
- name: BinaryCodec
|
|
36
|
+
kind: class
|
|
37
|
+
role: Codec wrapping user-supplied protobuf encode/decode functions for binary frames.
|
|
38
|
+
why: Library-agnostic (bufbuild, ts-proto, protobuf-ts); slices the returned buffer to a real ArrayBuffer to avoid SharedArrayBuffer/byteOffset issues.
|
|
39
|
+
- name: ControlMessage
|
|
40
|
+
kind: interface
|
|
41
|
+
role: The JSON envelope shape ({type, data?, error?, pingId?}) for all WS protocol frames.
|
|
42
|
+
why: Single optional-field struct covers every MessageType, so parsing is one type guard on the `type` field.
|
|
43
|
+
- name: MessageType
|
|
44
|
+
kind: type
|
|
45
|
+
role: Union of envelope type tags (data | error | stream_end | ping | pong | cancel | end_send).
|
|
46
|
+
why: Documents the full grpcws wire vocabulary in one place; the source of truth for both directions.
|
|
47
|
+
- name: ReadyState
|
|
48
|
+
kind: const
|
|
49
|
+
role: Frozen object of WebSocket readyState constants (CONNECTING/OPEN/CLOSING/CLOSED).
|
|
50
|
+
why: Avoids depending on the global WebSocket constructor's static constants, which are absent when a mock WebSocket is injected.
|
|
51
|
+
- name: ClientOptions
|
|
52
|
+
kind: interface
|
|
53
|
+
role: Constructor options for the WS clients (autoPong, WebSocket, codec).
|
|
54
|
+
why: WebSocket is injectable specifically so tests (and Node) can supply a fake constructor — the basis of createMock().
|
|
55
|
+
- name: ReadyStateType
|
|
56
|
+
kind: type
|
|
57
|
+
role: Value-union type derived from the ReadyState const.
|
|
58
|
+
why: Lets readyState be typed without re-listing the numeric literals.
|
|
59
|
+
- name: MessageHandler
|
|
60
|
+
kind: type
|
|
61
|
+
role: Generic data-message callback type `(data: T) => void`.
|
|
62
|
+
why: Shared handler signature across all clients for consistent event wiring.
|
|
63
|
+
- name: ErrorHandler
|
|
64
|
+
kind: type
|
|
65
|
+
role: Error callback type `(error: string) => void`.
|
|
66
|
+
why: Errors are surfaced as strings (not Error objects) uniformly across transports.
|
|
67
|
+
- name: VoidHandler
|
|
68
|
+
kind: type
|
|
69
|
+
role: No-arg callback type for close/streamEnd/done events.
|
|
70
|
+
why: One alias for all lifecycle-completion callbacks.
|
|
71
|
+
- name: SSEClientOptions
|
|
72
|
+
kind: interface
|
|
73
|
+
role: Options for SSEClient (fetch, headers, lastEventId).
|
|
74
|
+
why: fetch is injectable for Node/testing; lastEventId seeds the Last-Event-ID reconnect header.
|
|
75
|
+
- name: StreamableClientOptions
|
|
76
|
+
kind: interface
|
|
77
|
+
role: Options for StreamableClient (fetch, headers).
|
|
78
|
+
why: Same fetch DI pattern as SSEClient for testability.
|
|
79
|
+
- name: createParser
|
|
80
|
+
kind: func
|
|
81
|
+
role: Factory for a WHATWG-compliant SSE line parser with feed()/reset().
|
|
82
|
+
why: Vendored from eventsource-parser v3.0.6 (MIT) rather than depended on — the SSE spec is frozen (2015) so there is no maintenance risk and one fewer runtime dependency.
|
|
83
|
+
- name: EventSourceParser
|
|
84
|
+
kind: interface
|
|
85
|
+
role: Parser instance shape returned by createParser.
|
|
86
|
+
why: reset() must be called between reconnections to clear partial-line and event state.
|
|
87
|
+
- name: EventSourceMessage
|
|
88
|
+
kind: interface
|
|
89
|
+
role: A parsed SSE event ({event?, id?, data}).
|
|
90
|
+
why: Multi-line data fields are joined with "\n"; absent event/id are undefined (browsers would default event to "message").
|
|
91
|
+
- name: ParserCallbacks
|
|
92
|
+
kind: interface
|
|
93
|
+
role: Callback bag for createParser (onEvent/onRetry/onComment/onError).
|
|
94
|
+
why: Comments (keepalives) only fire if onComment is provided, letting consumers silently drop them.
|
|
95
|
+
- name: ParseError
|
|
96
|
+
kind: class
|
|
97
|
+
role: Error type for SSE parse failures (invalid-retry, unknown-field).
|
|
98
|
+
why: Carries field/value/line context for diagnostics rather than a bare message.
|
|
99
|
+
- name: ErrorType
|
|
100
|
+
kind: type
|
|
101
|
+
role: Union of SSE parse error categories.
|
|
102
|
+
why: Distinguishes recoverable unknown-field from invalid-retry without string matching.
|
|
103
|
+
- name: createMockWSPair
|
|
104
|
+
kind: func
|
|
105
|
+
role: Factory returning a fake WebSocket constructor + MockWSController for testing any BaseWSClient-based client.
|
|
106
|
+
why: Operates at the raw transport level (no protocol awareness) and re-captures the socket on each connect() so the controller always targets the latest connection.
|
|
107
|
+
- name: MockWSController
|
|
108
|
+
kind: interface
|
|
109
|
+
role: Test harness to drive a mock WebSocket (open/message/error/close, inspect sentRaw).
|
|
110
|
+
why: Raw-frame level by design; protocol-aware mocking is layered on top in GRPCWSClient.createMock.
|
|
111
|
+
- name: createMockSSEPair
|
|
112
|
+
kind: func
|
|
113
|
+
role: Factory returning a fake fetch + MockSSEController that serves a controllable SSE stream.
|
|
114
|
+
why: Formats payloads as proper SSE wire text and captures request url/method/headers/body for assertions.
|
|
115
|
+
- name: MockSSEController
|
|
116
|
+
kind: interface
|
|
117
|
+
role: Test harness to push SSE events (message/event/event-with-id/comment/close) and inspect the captured request.
|
|
118
|
+
why: Protocol-level (auto-formats SSE frames) so tests assert on application data, not wire syntax.
|
|
119
|
+
- name: MockController
|
|
120
|
+
kind: interface
|
|
121
|
+
role: Protocol-aware mock controller for GRPCWSClient (envelope wrap/unwrap built in).
|
|
122
|
+
why: sentMessages returns already-unwrapped data payloads so tests never touch the {type:"data"} envelope.
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
Architecture: the package deliberately mirrors the server's two-layer split — a transport layer (connection + always-JSON control frames) under a codec layer (business data). Three WebSocket clients form a stack: `BaseWSClient` (raw, for JSONConn servers) → `GRPCWSClient` (envelope protocol) → `TypedGRPCWSClient` (compile-time types only). Two HTTP-stream clients (`SSEClient`, `StreamableClient`) share the vendored `sse-parser` and the injectable-`fetch` DI pattern.
|
|
126
|
+
|
|
127
|
+
Key non-obvious decisions:
|
|
128
|
+
- Native `EventSource` is intentionally not used (GET-only, no custom headers); SSE/streamable clients use `fetch` + `ReadableStream`.
|
|
129
|
+
- The SSE parser is vendored, not depended upon, because the SSE spec is frozen.
|
|
130
|
+
- All clients take an injectable transport (`WebSocket` or `fetch`) purely to enable the static `createMock()` helpers; mock controllers come in two flavors — raw-transport (`MockWSController`, `MockSSEController`) and protocol-aware (`MockController`, and SSE's auto-formatting).
|
|
131
|
+
- `AbortError` is swallowed in stream readers because it is the expected signal from `close()`.
|
|
132
|
+
- `ReadyState` is a local const rather than the WebSocket static so injected mocks need not reimplement those statics.
|
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';
|