@panyam/servicekit-client 0.0.7 → 0.1.10

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.mjs CHANGED
@@ -687,7 +687,7 @@ function createMockSSEPair(contentType = "text/event-stream") {
687
687
  streamController.enqueue(encoder.encode(text));
688
688
  }
689
689
  };
690
- const mockFetch = async (input, init) => {
690
+ const mockFetch = (async (input, init) => {
691
691
  capturedUrl = typeof input === "string" ? input : input.toString();
692
692
  capturedMethod = init?.method ?? "GET";
693
693
  capturedBody = typeof init?.body === "string" ? init.body : void 0;
@@ -714,7 +714,7 @@ function createMockSSEPair(contentType = "text/event-stream") {
714
714
  status: 200,
715
715
  headers: { "Content-Type": contentType }
716
716
  });
717
- };
717
+ });
718
718
  const controller = {
719
719
  simulateMessage(data) {
720
720
  enqueue(`data: ${JSON.stringify(data)}
@@ -724,7 +724,7 @@ var ServiceKit = (() => {
724
724
  streamController.enqueue(encoder.encode(text));
725
725
  }
726
726
  };
727
- const mockFetch = async (input, init) => {
727
+ const mockFetch = (async (input, init) => {
728
728
  capturedUrl = typeof input === "string" ? input : input.toString();
729
729
  capturedMethod = init?.method ?? "GET";
730
730
  capturedBody = typeof init?.body === "string" ? init.body : void 0;
@@ -751,7 +751,7 @@ var ServiceKit = (() => {
751
751
  status: 200,
752
752
  headers: { "Content-Type": contentType }
753
753
  });
754
- };
754
+ });
755
755
  const controller = {
756
756
  simulateMessage(data) {
757
757
  enqueue(`data: ${JSON.stringify(data)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@panyam/servicekit-client",
3
- "version": "0.0.7",
3
+ "version": "0.1.10",
4
4
  "description": "TypeScript client for ServiceKit WebSocket and SSE protocols",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -8,8 +8,18 @@
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
  ],
15
+ "scripts": {
16
+ "build": "tsc -p tsconfig.build.json && npm run build:esm && npm run build:browser",
17
+ "build:esm": "esbuild src/index.ts --bundle --format=esm --outfile=dist/index.mjs",
18
+ "build:browser": "esbuild src/index.ts --bundle --format=iife --global-name=ServiceKit --outfile=dist/servicekit-client.browser.js",
19
+ "test": "vitest run",
20
+ "clean": "rm -rf dist",
21
+ "prepublishOnly": "npm run build"
22
+ },
13
23
  "keywords": [
14
24
  "grpc",
15
25
  "websocket",
@@ -24,22 +34,15 @@
24
34
  "license": "MIT",
25
35
  "repository": {
26
36
  "type": "git",
27
- "url": "https://github.com/panyam/servicekit.git",
37
+ "url": "git+https://github.com/panyam/servicekit.git",
28
38
  "directory": "clients/typescript"
29
39
  },
30
40
  "devDependencies": {
31
- "esbuild": "^0.24.0",
41
+ "esbuild": "^0.28.2",
32
42
  "typescript": "^5.3.0",
33
43
  "vitest": "^4.1.2"
34
44
  },
35
45
  "engines": {
36
46
  "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"
44
47
  }
45
- }
48
+ }
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.
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=sse.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sse.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/sse.test.ts"],"names":[],"mappings":""}
@@ -1,286 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const vitest_1 = require("vitest");
4
- const sse_parser_1 = require("../sse-parser");
5
- const sse_client_1 = require("../sse-client");
6
- const streamable_client_1 = require("../streamable-client");
7
- const sse_mock_1 = require("../sse-mock");
8
- // ============================================================================
9
- // SSE Parser Tests
10
- // ============================================================================
11
- (0, vitest_1.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
- (0, vitest_1.it)('parses basic data event', () => {
17
- const events = [];
18
- const parser = (0, sse_parser_1.createParser)({ onEvent: (e) => events.push(e) });
19
- parser.feed('data: {"msg":"hello"}\n\n');
20
- (0, vitest_1.expect)(events).toHaveLength(1);
21
- (0, vitest_1.expect)(events[0].data).toBe('{"msg":"hello"}');
22
- (0, vitest_1.expect)(events[0].event).toBeUndefined();
23
- });
24
- /**
25
- * Verifies named event parsing: "event:" field sets the event type,
26
- * which clients use with EventSource.addEventListener(type, handler).
27
- */
28
- (0, vitest_1.it)('parses named event', () => {
29
- const events = [];
30
- const parser = (0, sse_parser_1.createParser)({ onEvent: (e) => events.push(e) });
31
- parser.feed('event: update\ndata: {"version":3}\n\n');
32
- (0, vitest_1.expect)(events).toHaveLength(1);
33
- (0, vitest_1.expect)(events[0].event).toBe('update');
34
- (0, vitest_1.expect)(events[0].data).toBe('{"version":3}');
35
- });
36
- /**
37
- * Verifies "id:" field tracking: the parser passes the id through to
38
- * the event, enabling Last-Event-ID reconnection support.
39
- */
40
- (0, vitest_1.it)('parses event with id', () => {
41
- const events = [];
42
- const parser = (0, sse_parser_1.createParser)({ onEvent: (e) => events.push(e) });
43
- parser.feed('id: 42\nevent: msg\ndata: hello\n\n');
44
- (0, vitest_1.expect)(events[0].id).toBe('42');
45
- (0, vitest_1.expect)(events[0].event).toBe('msg');
46
- });
47
- /**
48
- * Verifies multi-line data handling: per WHATWG SSE spec, multiple
49
- * "data:" lines are joined with "\n" characters.
50
- */
51
- (0, vitest_1.it)('joins multi-line data with newlines', () => {
52
- const events = [];
53
- const parser = (0, sse_parser_1.createParser)({ onEvent: (e) => events.push(e) });
54
- parser.feed('data: line1\ndata: line2\ndata: line3\n\n');
55
- (0, vitest_1.expect)(events[0].data).toBe('line1\nline2\nline3');
56
- });
57
- /**
58
- * Verifies that SSE comments (lines starting with ":") are passed to
59
- * the onComment callback but do NOT fire onEvent. This is how servers
60
- * send keepalive signals.
61
- */
62
- (0, vitest_1.it)('ignores comments, does not fire onEvent', () => {
63
- const events = [];
64
- const comments = [];
65
- const parser = (0, sse_parser_1.createParser)({
66
- onEvent: (e) => events.push(e),
67
- onComment: (c) => comments.push(c),
68
- });
69
- parser.feed(': keepalive\n\n');
70
- parser.feed('data: real\n\n');
71
- (0, vitest_1.expect)(events).toHaveLength(1);
72
- (0, vitest_1.expect)(events[0].data).toBe('real');
73
- (0, vitest_1.expect)(comments).toEqual(['keepalive']);
74
- });
75
- /**
76
- * Verifies CRLF line ending handling: per WHATWG spec, SSE must support
77
- * CR+LF, LF, and CR as line terminators.
78
- */
79
- (0, vitest_1.it)('handles CRLF line endings', () => {
80
- const events = [];
81
- const parser = (0, sse_parser_1.createParser)({ onEvent: (e) => events.push(e) });
82
- parser.feed('data: hello\r\n\r\n');
83
- (0, vitest_1.expect)(events).toHaveLength(1);
84
- (0, vitest_1.expect)(events[0].data).toBe('hello');
85
- });
86
- /**
87
- * Verifies UTF-8 BOM stripping: the parser removes the BOM from the
88
- * first chunk per WHATWG spec requirement.
89
- */
90
- (0, vitest_1.it)('strips UTF-8 BOM from first chunk', () => {
91
- const events = [];
92
- const parser = (0, sse_parser_1.createParser)({ onEvent: (e) => events.push(e) });
93
- parser.feed('\xEF\xBB\xBFdata: hello\n\n');
94
- (0, vitest_1.expect)(events).toHaveLength(1);
95
- (0, vitest_1.expect)(events[0].data).toBe('hello');
96
- });
97
- /**
98
- * Verifies that data split across multiple feed() calls is correctly
99
- * buffered and parsed when the terminating blank line arrives.
100
- */
101
- (0, vitest_1.it)('handles chunked data across feed calls', () => {
102
- const events = [];
103
- const parser = (0, sse_parser_1.createParser)({ onEvent: (e) => events.push(e) });
104
- parser.feed('data: hel');
105
- parser.feed('lo\n\n');
106
- (0, vitest_1.expect)(events).toHaveLength(1);
107
- (0, vitest_1.expect)(events[0].data).toBe('hello');
108
- });
109
- });
110
- // ============================================================================
111
- // SSEClient Tests
112
- // ============================================================================
113
- (0, vitest_1.describe)('SSEClient', () => {
114
- /**
115
- * Verifies that SSEClient connects via mock fetch, receives data events,
116
- * and dispatches them to the onMessage handler with parsed JSON.
117
- */
118
- (0, vitest_1.it)('connects and receives messages', async () => {
119
- const { client, controller } = sse_client_1.SSEClient.createMock();
120
- const received = [];
121
- client.onMessage = (data) => received.push(data);
122
- await client.connect('http://test/events');
123
- (0, vitest_1.expect)(client.isConnected).toBe(true);
124
- controller.simulateMessage({ greeting: 'hello' });
125
- controller.simulateClose();
126
- // Wait for async stream processing
127
- await new Promise((r) => setTimeout(r, 10));
128
- (0, vitest_1.expect)(received).toHaveLength(1);
129
- (0, vitest_1.expect)(received[0]).toEqual({ greeting: 'hello' });
130
- });
131
- /**
132
- * Verifies that named events (with "event:" field) are dispatched to
133
- * the onEvent handler with the event type and parsed data.
134
- */
135
- (0, vitest_1.it)('dispatches named events to onEvent', async () => {
136
- const { client, controller } = sse_client_1.SSEClient.createMock();
137
- const events = [];
138
- client.onEvent = (type, data) => events.push({ type, data });
139
- await client.connect('http://test/events');
140
- controller.simulateEvent('update', { version: 3 });
141
- controller.simulateClose();
142
- await new Promise((r) => setTimeout(r, 10));
143
- (0, vitest_1.expect)(events).toHaveLength(1);
144
- (0, vitest_1.expect)(events[0].type).toBe('update');
145
- (0, vitest_1.expect)(events[0].data).toEqual({ version: 3 });
146
- });
147
- /**
148
- * Verifies that keepalive comments (": keepalive") are silently consumed
149
- * and do NOT trigger onMessage or onEvent.
150
- */
151
- (0, vitest_1.it)('filters keepalive comments', async () => {
152
- const { client, controller } = sse_client_1.SSEClient.createMock();
153
- const received = [];
154
- client.onMessage = (data) => received.push(data);
155
- await client.connect('http://test/events');
156
- controller.simulateComment('keepalive');
157
- controller.simulateMessage({ real: true });
158
- controller.simulateClose();
159
- await new Promise((r) => setTimeout(r, 10));
160
- (0, vitest_1.expect)(received).toHaveLength(1);
161
- (0, vitest_1.expect)(received[0]).toEqual({ real: true });
162
- });
163
- /**
164
- * Verifies that the "id:" field from events is tracked in lastEventId,
165
- * enabling reconnection via the Last-Event-ID header.
166
- */
167
- (0, vitest_1.it)('tracks lastEventId from events', async () => {
168
- const { client, controller } = sse_client_1.SSEClient.createMock();
169
- await client.connect('http://test/events');
170
- (0, vitest_1.expect)(client.lastEventId).toBeUndefined();
171
- controller.simulateEventWithId('msg', 'evt-99', { data: 'test' });
172
- controller.simulateClose();
173
- await new Promise((r) => setTimeout(r, 10));
174
- (0, vitest_1.expect)(client.lastEventId).toBe('evt-99');
175
- });
176
- /**
177
- * Verifies that close() fires the onClose handler.
178
- */
179
- (0, vitest_1.it)('fires onClose when stream ends', async () => {
180
- const { client, controller } = sse_client_1.SSEClient.createMock();
181
- let closed = false;
182
- client.onClose = () => { closed = true; };
183
- await client.connect('http://test/events');
184
- controller.simulateClose();
185
- await new Promise((r) => setTimeout(r, 10));
186
- (0, vitest_1.expect)(closed).toBe(true);
187
- (0, vitest_1.expect)(client.isConnected).toBe(false);
188
- });
189
- /**
190
- * Verifies that createMock captures the request URL and headers
191
- * for test assertions.
192
- */
193
- (0, vitest_1.it)('createMock captures request details', async () => {
194
- const { fetch, controller } = (0, sse_mock_1.createMockSSEPair)();
195
- const client = new sse_client_1.SSEClient({
196
- fetch,
197
- headers: { Authorization: 'Bearer token123' },
198
- });
199
- await client.connect('http://test/events');
200
- controller.simulateClose();
201
- (0, vitest_1.expect)(controller.receivedUrl).toBe('http://test/events');
202
- (0, vitest_1.expect)(controller.receivedHeaders['Authorization']).toBe('Bearer token123');
203
- await new Promise((r) => setTimeout(r, 10));
204
- });
205
- });
206
- // ============================================================================
207
- // StreamableClient Tests
208
- // ============================================================================
209
- (0, vitest_1.describe)('StreamableClient', () => {
210
- /**
211
- * Verifies that when the server responds with application/json,
212
- * StreamableClient parses the JSON body and returns it directly.
213
- * This is the synchronous (non-streaming) path.
214
- */
215
- (0, vitest_1.it)('returns parsed JSON for application/json response', async () => {
216
- const { fetch } = (0, sse_mock_1.createMockSSEPair)('application/json');
217
- const client = new streamable_client_1.StreamableClient({ fetch });
218
- // Override the mock to return JSON instead of a stream
219
- const jsonFetch = (async (_url, _init) => {
220
- return new Response(JSON.stringify({ result: 'ok' }), {
221
- status: 200,
222
- headers: { 'Content-Type': 'application/json' },
223
- });
224
- });
225
- const jsonClient = new streamable_client_1.StreamableClient({
226
- fetch: jsonFetch,
227
- });
228
- const result = await jsonClient.post('http://test/rpc', { method: 'getUser' });
229
- (0, vitest_1.expect)(result).toEqual({ result: 'ok' });
230
- });
231
- /**
232
- * Verifies that when the server responds with text/event-stream,
233
- * StreamableClient streams events via onMessage/onEvent callbacks
234
- * and calls onDone when the stream completes.
235
- */
236
- (0, vitest_1.it)('streams SSE events for text/event-stream response', async () => {
237
- const { fetch, controller } = (0, sse_mock_1.createMockSSEPair)('text/event-stream');
238
- const client = new streamable_client_1.StreamableClient({ fetch });
239
- const events = [];
240
- let done = false;
241
- client.onMessage = (data) => events.push(data);
242
- client.onDone = () => { done = true; };
243
- const postPromise = client.post('http://test/rpc', { method: 'longOp' });
244
- // Give the fetch a moment to resolve
245
- await new Promise((r) => setTimeout(r, 10));
246
- controller.simulateMessage({ progress: 50 });
247
- controller.simulateMessage({ progress: 100 });
248
- controller.simulateClose();
249
- await postPromise;
250
- (0, vitest_1.expect)(events).toHaveLength(2);
251
- (0, vitest_1.expect)(events[0]).toEqual({ progress: 50 });
252
- (0, vitest_1.expect)(events[1]).toEqual({ progress: 100 });
253
- (0, vitest_1.expect)(done).toBe(true);
254
- });
255
- /**
256
- * Verifies that onDone fires when the SSE stream ends, even if
257
- * no events were received.
258
- */
259
- (0, vitest_1.it)('fires onDone when stream completes', async () => {
260
- const { fetch, controller } = (0, sse_mock_1.createMockSSEPair)('text/event-stream');
261
- const client = new streamable_client_1.StreamableClient({ fetch });
262
- let done = false;
263
- client.onDone = () => { done = true; };
264
- const postPromise = client.post('http://test/rpc', {});
265
- await new Promise((r) => setTimeout(r, 10));
266
- controller.simulateClose();
267
- await postPromise;
268
- (0, vitest_1.expect)(done).toBe(true);
269
- });
270
- /**
271
- * Verifies that StreamableClient sends the request body as JSON
272
- * and includes proper headers (Content-Type, Accept).
273
- */
274
- (0, vitest_1.it)('sends POST with correct headers and body', async () => {
275
- const { fetch, controller } = (0, sse_mock_1.createMockSSEPair)('text/event-stream');
276
- const client = new streamable_client_1.StreamableClient({ fetch });
277
- const postPromise = client.post('http://test/rpc', { method: 'test', id: 42 });
278
- await new Promise((r) => setTimeout(r, 10));
279
- controller.simulateClose();
280
- await postPromise;
281
- (0, vitest_1.expect)(controller.receivedMethod).toBe('POST');
282
- (0, vitest_1.expect)(controller.receivedBody).toBe('{"method":"test","id":42}');
283
- (0, vitest_1.expect)(controller.receivedHeaders['Content-Type']).toBe('application/json');
284
- });
285
- });
286
- //# sourceMappingURL=sse.test.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"sse.test.js","sourceRoot":"","sources":["../../src/__tests__/sse.test.ts"],"names":[],"mappings":";;AAAA,mCAAkD;AAClD,8CAAiE;AACjE,8CAA0C;AAC1C,4DAAwD;AACxD,0CAAgD;AAEhD,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E,IAAA,iBAAQ,EAAC,WAAW,EAAE,GAAG,EAAE;IACzB;;;OAGG;IACH,IAAA,WAAE,EAAC,yBAAyB,EAAE,GAAG,EAAE;QACjC,MAAM,MAAM,GAAyB,EAAE,CAAC;QACxC,MAAM,MAAM,GAAG,IAAA,yBAAY,EAAC,EAAE,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QAEhE,MAAM,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC;QAEzC,IAAA,eAAM,EAAC,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;QAC/B,IAAA,eAAM,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;QAC/C,IAAA,eAAM,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,aAAa,EAAE,CAAC;IAC1C,CAAC,CAAC,CAAC;IAEH;;;OAGG;IACH,IAAA,WAAE,EAAC,oBAAoB,EAAE,GAAG,EAAE;QAC5B,MAAM,MAAM,GAAyB,EAAE,CAAC;QACxC,MAAM,MAAM,GAAG,IAAA,yBAAY,EAAC,EAAE,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QAEhE,M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{ 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
- });