@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
package/dist/index.d.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
|
|
@@ -63,5 +68,9 @@ export { MessageType, ControlMessage, ReadyState, ReadyStateType, ClientOptions,
|
|
|
63
68
|
export { BaseWSClient } from './base-client';
|
|
64
69
|
export { GRPCWSClient, MockController } from './grpcws-client';
|
|
65
70
|
export { TypedGRPCWSClient } from './typed-client';
|
|
71
|
+
export { SSEClient, SSEClientOptions } from './sse-client';
|
|
72
|
+
export { StreamableClient, StreamableClientOptions } from './streamable-client';
|
|
73
|
+
export { createParser, EventSourceMessage, EventSourceParser, ParserCallbacks, ParseError, } from './sse-parser';
|
|
66
74
|
export { createMockWSPair, MockWSController } from './mock';
|
|
75
|
+
export { createMockSSEPair, MockSSEController } from './sse-mock';
|
|
67
76
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiEG;AAGH,OAAO,EACL,WAAW,EACX,cAAc,EACd,UAAU,EACV,cAAc,EACd,aAAa,EACb,KAAK,EACL,SAAS,EACT,WAAW,EACX,cAAc,EACd,YAAY,EACZ,WAAW,GACZ,MAAM,SAAS,CAAC;AAGjB,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAGnD,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAGhF,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,iBAAiB,EACjB,eAAe,EACf,UAAU,GACX,MAAM,cAAc,CAAC;AAGtB,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -2,23 +2,28 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* @panyam/servicekit-client
|
|
4
4
|
*
|
|
5
|
-
* TypeScript client library for ServiceKit WebSocket protocols.
|
|
5
|
+
* TypeScript client library for ServiceKit WebSocket and SSE protocols.
|
|
6
6
|
*
|
|
7
7
|
* ## Architecture
|
|
8
8
|
*
|
|
9
9
|
* The client mirrors the server-side architecture with two layers:
|
|
10
|
-
* - **Transport layer**: Handles WebSocket connection, ping/pong heartbeats
|
|
10
|
+
* - **Transport layer**: Handles WebSocket/SSE connection, ping/pong heartbeats
|
|
11
11
|
* - **Codec layer**: Handles encoding/decoding of data messages
|
|
12
12
|
*
|
|
13
13
|
* Control messages (ping, pong, error) are always JSON at the transport layer,
|
|
14
14
|
* while data messages use the configured codec (JSON, binary protobuf, etc.).
|
|
15
15
|
*
|
|
16
|
-
* ## Clients
|
|
16
|
+
* ## WebSocket Clients
|
|
17
17
|
*
|
|
18
18
|
* - `BaseWSClient`: Low-level WebSocket with auto ping/pong (for http/JSONConn)
|
|
19
19
|
* - `GRPCWSClient`: gRPC-style streaming with envelope protocol (for grpcws)
|
|
20
20
|
* - `TypedGRPCWSClient`: Type-safe wrapper for GRPCWSClient
|
|
21
21
|
*
|
|
22
|
+
* ## SSE Clients
|
|
23
|
+
*
|
|
24
|
+
* - `SSEClient`: Server-Sent Events client (for http/SSEServe endpoints)
|
|
25
|
+
* - `StreamableClient`: POST-that-optionally-streams (for http/StreamableServe)
|
|
26
|
+
*
|
|
22
27
|
* ## Codecs
|
|
23
28
|
*
|
|
24
29
|
* - `JSONCodec`: Default, matches server-side JSONCodec
|
|
@@ -61,7 +66,7 @@
|
|
|
61
66
|
* @packageDocumentation
|
|
62
67
|
*/
|
|
63
68
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
64
|
-
exports.createMockWSPair = exports.TypedGRPCWSClient = exports.GRPCWSClient = exports.BaseWSClient = exports.BinaryCodec = exports.JSONCodec = exports.ReadyState = void 0;
|
|
69
|
+
exports.createMockSSEPair = exports.createMockWSPair = exports.ParseError = exports.createParser = exports.StreamableClient = exports.SSEClient = exports.TypedGRPCWSClient = exports.GRPCWSClient = exports.BaseWSClient = exports.BinaryCodec = exports.JSONCodec = exports.ReadyState = void 0;
|
|
65
70
|
// Types and Codecs
|
|
66
71
|
var types_1 = require("./types");
|
|
67
72
|
Object.defineProperty(exports, "ReadyState", { enumerable: true, get: function () { return types_1.ReadyState; } });
|
|
@@ -74,7 +79,18 @@ var grpcws_client_1 = require("./grpcws-client");
|
|
|
74
79
|
Object.defineProperty(exports, "GRPCWSClient", { enumerable: true, get: function () { return grpcws_client_1.GRPCWSClient; } });
|
|
75
80
|
var typed_client_1 = require("./typed-client");
|
|
76
81
|
Object.defineProperty(exports, "TypedGRPCWSClient", { enumerable: true, get: function () { return typed_client_1.TypedGRPCWSClient; } });
|
|
82
|
+
// SSE Clients
|
|
83
|
+
var sse_client_1 = require("./sse-client");
|
|
84
|
+
Object.defineProperty(exports, "SSEClient", { enumerable: true, get: function () { return sse_client_1.SSEClient; } });
|
|
85
|
+
var streamable_client_1 = require("./streamable-client");
|
|
86
|
+
Object.defineProperty(exports, "StreamableClient", { enumerable: true, get: function () { return streamable_client_1.StreamableClient; } });
|
|
87
|
+
// SSE Parser (vendored from eventsource-parser, MIT)
|
|
88
|
+
var sse_parser_1 = require("./sse-parser");
|
|
89
|
+
Object.defineProperty(exports, "createParser", { enumerable: true, get: function () { return sse_parser_1.createParser; } });
|
|
90
|
+
Object.defineProperty(exports, "ParseError", { enumerable: true, get: function () { return sse_parser_1.ParseError; } });
|
|
77
91
|
// Test utilities
|
|
78
92
|
var mock_1 = require("./mock");
|
|
79
93
|
Object.defineProperty(exports, "createMockWSPair", { enumerable: true, get: function () { return mock_1.createMockWSPair; } });
|
|
94
|
+
var sse_mock_1 = require("./sse-mock");
|
|
95
|
+
Object.defineProperty(exports, "createMockSSEPair", { enumerable: true, get: function () { return sse_mock_1.createMockSSEPair; } });
|
|
80
96
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiEG;;;AAEH,mBAAmB;AACnB,iCAYiB;AATf,mGAAA,UAAU,OAAA;AAIV,kGAAA,SAAS,OAAA;AACT,oGAAA,WAAW,OAAA;AAMb,UAAU;AACV,6CAA6C;AAApC,2GAAA,YAAY,OAAA;AACrB,iDAA+D;AAAtD,6GAAA,YAAY,OAAA;AACrB,+CAAmD;AAA1C,iHAAA,iBAAiB,OAAA;AAE1B,cAAc;AACd,2CAA2D;AAAlD,uGAAA,SAAS,OAAA;AAClB,yDAAgF;AAAvE,qHAAA,gBAAgB,OAAA;AAEzB,qDAAqD;AACrD,2CAMsB;AALpB,0GAAA,YAAY,OAAA;AAIZ,wGAAA,UAAU,OAAA;AAGZ,iBAAiB;AACjB,+BAA4D;AAAnD,wGAAA,gBAAgB,OAAA;AACzB,uCAAkE;AAAzD,6GAAA,iBAAiB,OAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -524,12 +524,489 @@ var TypedGRPCWSClient = class {
|
|
|
524
524
|
};
|
|
525
525
|
}
|
|
526
526
|
};
|
|
527
|
+
|
|
528
|
+
// src/sse-parser.ts
|
|
529
|
+
var ParseError = class extends Error {
|
|
530
|
+
constructor(message, options) {
|
|
531
|
+
super(message);
|
|
532
|
+
this.name = "ParseError";
|
|
533
|
+
this.type = options.type;
|
|
534
|
+
this.field = options.field;
|
|
535
|
+
this.value = options.value;
|
|
536
|
+
this.line = options.line;
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
function noop(_arg) {
|
|
540
|
+
}
|
|
541
|
+
function createParser(callbacks) {
|
|
542
|
+
if (typeof callbacks === "function") {
|
|
543
|
+
throw new TypeError(
|
|
544
|
+
"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
|
|
548
|
+
let incompleteLine = "";
|
|
549
|
+
let isFirstChunk = true;
|
|
550
|
+
let id;
|
|
551
|
+
let data = "";
|
|
552
|
+
let eventType = "";
|
|
553
|
+
function feed(newChunk) {
|
|
554
|
+
const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk;
|
|
555
|
+
const [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
|
|
556
|
+
for (const line of complete) {
|
|
557
|
+
parseLine(line);
|
|
558
|
+
}
|
|
559
|
+
incompleteLine = incomplete;
|
|
560
|
+
isFirstChunk = false;
|
|
561
|
+
}
|
|
562
|
+
function parseLine(line) {
|
|
563
|
+
if (line === "") {
|
|
564
|
+
dispatchEvent();
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
if (line.startsWith(":")) {
|
|
568
|
+
if (onComment) {
|
|
569
|
+
onComment(line.slice(line.startsWith(": ") ? 2 : 1));
|
|
570
|
+
}
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
const fieldSeparatorIndex = line.indexOf(":");
|
|
574
|
+
if (fieldSeparatorIndex !== -1) {
|
|
575
|
+
const field = line.slice(0, fieldSeparatorIndex);
|
|
576
|
+
const offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1;
|
|
577
|
+
const value = line.slice(fieldSeparatorIndex + offset);
|
|
578
|
+
processField(field, value, line);
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
processField(line, "", line);
|
|
582
|
+
}
|
|
583
|
+
function processField(field, value, line) {
|
|
584
|
+
switch (field) {
|
|
585
|
+
case "event":
|
|
586
|
+
eventType = value;
|
|
587
|
+
break;
|
|
588
|
+
case "data":
|
|
589
|
+
data = `${data}${value}
|
|
590
|
+
`;
|
|
591
|
+
break;
|
|
592
|
+
case "id":
|
|
593
|
+
id = value.includes("\0") ? void 0 : value;
|
|
594
|
+
break;
|
|
595
|
+
case "retry":
|
|
596
|
+
if (/^\d+$/.test(value)) {
|
|
597
|
+
onRetry(parseInt(value, 10));
|
|
598
|
+
} else {
|
|
599
|
+
onError(
|
|
600
|
+
new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
601
|
+
type: "invalid-retry",
|
|
602
|
+
value,
|
|
603
|
+
line
|
|
604
|
+
})
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
break;
|
|
608
|
+
default:
|
|
609
|
+
onError(
|
|
610
|
+
new ParseError(
|
|
611
|
+
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
|
|
612
|
+
{ type: "unknown-field", field, value, line }
|
|
613
|
+
)
|
|
614
|
+
);
|
|
615
|
+
break;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
function dispatchEvent() {
|
|
619
|
+
const shouldDispatch = data.length > 0;
|
|
620
|
+
if (shouldDispatch) {
|
|
621
|
+
onEvent({
|
|
622
|
+
id,
|
|
623
|
+
event: eventType || void 0,
|
|
624
|
+
data: data.endsWith("\n") ? data.slice(0, -1) : data
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
id = void 0;
|
|
628
|
+
data = "";
|
|
629
|
+
eventType = "";
|
|
630
|
+
}
|
|
631
|
+
function reset(options = {}) {
|
|
632
|
+
if (incompleteLine && options.consume) {
|
|
633
|
+
parseLine(incompleteLine);
|
|
634
|
+
}
|
|
635
|
+
isFirstChunk = true;
|
|
636
|
+
id = void 0;
|
|
637
|
+
data = "";
|
|
638
|
+
eventType = "";
|
|
639
|
+
incompleteLine = "";
|
|
640
|
+
}
|
|
641
|
+
return { feed, reset };
|
|
642
|
+
}
|
|
643
|
+
function splitLines(chunk) {
|
|
644
|
+
const lines = [];
|
|
645
|
+
let incompleteLine = "";
|
|
646
|
+
let searchIndex = 0;
|
|
647
|
+
while (searchIndex < chunk.length) {
|
|
648
|
+
const crIndex = chunk.indexOf("\r", searchIndex);
|
|
649
|
+
const lfIndex = chunk.indexOf("\n", searchIndex);
|
|
650
|
+
let lineEnd = -1;
|
|
651
|
+
if (crIndex !== -1 && lfIndex !== -1) {
|
|
652
|
+
lineEnd = Math.min(crIndex, lfIndex);
|
|
653
|
+
} else if (crIndex !== -1) {
|
|
654
|
+
if (crIndex === chunk.length - 1) {
|
|
655
|
+
lineEnd = -1;
|
|
656
|
+
} else {
|
|
657
|
+
lineEnd = crIndex;
|
|
658
|
+
}
|
|
659
|
+
} else if (lfIndex !== -1) {
|
|
660
|
+
lineEnd = lfIndex;
|
|
661
|
+
}
|
|
662
|
+
if (lineEnd === -1) {
|
|
663
|
+
incompleteLine = chunk.slice(searchIndex);
|
|
664
|
+
break;
|
|
665
|
+
} else {
|
|
666
|
+
const line = chunk.slice(searchIndex, lineEnd);
|
|
667
|
+
lines.push(line);
|
|
668
|
+
searchIndex = lineEnd + 1;
|
|
669
|
+
if (chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === "\n") {
|
|
670
|
+
searchIndex++;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
return [lines, incompleteLine];
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// src/sse-mock.ts
|
|
678
|
+
function createMockSSEPair(contentType = "text/event-stream") {
|
|
679
|
+
let streamController = null;
|
|
680
|
+
let capturedUrl;
|
|
681
|
+
let capturedHeaders = {};
|
|
682
|
+
let capturedMethod;
|
|
683
|
+
let capturedBody;
|
|
684
|
+
const encoder = new TextEncoder();
|
|
685
|
+
const enqueue = (text) => {
|
|
686
|
+
if (streamController) {
|
|
687
|
+
streamController.enqueue(encoder.encode(text));
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
const mockFetch = (async (input, init) => {
|
|
691
|
+
capturedUrl = typeof input === "string" ? input : input.toString();
|
|
692
|
+
capturedMethod = init?.method ?? "GET";
|
|
693
|
+
capturedBody = typeof init?.body === "string" ? init.body : void 0;
|
|
694
|
+
capturedHeaders = {};
|
|
695
|
+
if (init?.headers) {
|
|
696
|
+
if (init.headers instanceof Headers) {
|
|
697
|
+
init.headers.forEach((v, k) => {
|
|
698
|
+
capturedHeaders[k] = v;
|
|
699
|
+
});
|
|
700
|
+
} else if (Array.isArray(init.headers)) {
|
|
701
|
+
for (const [k, v] of init.headers) {
|
|
702
|
+
capturedHeaders[k] = v;
|
|
703
|
+
}
|
|
704
|
+
} else {
|
|
705
|
+
capturedHeaders = { ...init.headers };
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const body = new ReadableStream({
|
|
709
|
+
start(controller2) {
|
|
710
|
+
streamController = controller2;
|
|
711
|
+
}
|
|
712
|
+
});
|
|
713
|
+
return new Response(body, {
|
|
714
|
+
status: 200,
|
|
715
|
+
headers: { "Content-Type": contentType }
|
|
716
|
+
});
|
|
717
|
+
});
|
|
718
|
+
const controller = {
|
|
719
|
+
simulateMessage(data) {
|
|
720
|
+
enqueue(`data: ${JSON.stringify(data)}
|
|
721
|
+
|
|
722
|
+
`);
|
|
723
|
+
},
|
|
724
|
+
simulateEvent(event, data) {
|
|
725
|
+
enqueue(`event: ${event}
|
|
726
|
+
data: ${JSON.stringify(data)}
|
|
727
|
+
|
|
728
|
+
`);
|
|
729
|
+
},
|
|
730
|
+
simulateEventWithId(event, id, data) {
|
|
731
|
+
enqueue(`event: ${event}
|
|
732
|
+
id: ${id}
|
|
733
|
+
data: ${JSON.stringify(data)}
|
|
734
|
+
|
|
735
|
+
`);
|
|
736
|
+
},
|
|
737
|
+
simulateComment(text) {
|
|
738
|
+
enqueue(`: ${text}
|
|
739
|
+
|
|
740
|
+
`);
|
|
741
|
+
},
|
|
742
|
+
simulateClose() {
|
|
743
|
+
if (streamController) {
|
|
744
|
+
streamController.close();
|
|
745
|
+
streamController = null;
|
|
746
|
+
}
|
|
747
|
+
},
|
|
748
|
+
get receivedUrl() {
|
|
749
|
+
return capturedUrl;
|
|
750
|
+
},
|
|
751
|
+
get receivedHeaders() {
|
|
752
|
+
return capturedHeaders;
|
|
753
|
+
},
|
|
754
|
+
get receivedMethod() {
|
|
755
|
+
return capturedMethod;
|
|
756
|
+
},
|
|
757
|
+
get receivedBody() {
|
|
758
|
+
return capturedBody;
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
return { fetch: mockFetch, controller };
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// src/sse-client.ts
|
|
765
|
+
var SSEClient = class _SSEClient {
|
|
766
|
+
constructor(options = {}) {
|
|
767
|
+
this._connected = false;
|
|
768
|
+
this._abortController = null;
|
|
769
|
+
/** Called when an unnamed data event is received (no "event:" field). */
|
|
770
|
+
this.onMessage = () => {
|
|
771
|
+
};
|
|
772
|
+
/** Called when a named event is received (has "event:" field). */
|
|
773
|
+
this.onEvent = () => {
|
|
774
|
+
};
|
|
775
|
+
/** Called when the SSE stream closes (server closes or network error). */
|
|
776
|
+
this.onClose = () => {
|
|
777
|
+
};
|
|
778
|
+
/** Called when an error occurs (fetch failure, parse error). */
|
|
779
|
+
this.onError = () => {
|
|
780
|
+
};
|
|
781
|
+
this._fetch = options.fetch ?? globalThis.fetch;
|
|
782
|
+
this._headers = options.headers ?? {};
|
|
783
|
+
this._lastEventId = options.lastEventId;
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Connect to an SSE endpoint.
|
|
787
|
+
*
|
|
788
|
+
* @param url The HTTP URL to connect to
|
|
789
|
+
* @returns Promise that resolves when the connection is established (headers received)
|
|
790
|
+
* @throws Error if the response is not 200 or not text/event-stream
|
|
791
|
+
*/
|
|
792
|
+
async connect(url) {
|
|
793
|
+
const headers = { ...this._headers };
|
|
794
|
+
if (this._lastEventId) {
|
|
795
|
+
headers["Last-Event-ID"] = this._lastEventId;
|
|
796
|
+
}
|
|
797
|
+
this._abortController = new AbortController();
|
|
798
|
+
const response = await this._fetch(url, {
|
|
799
|
+
headers,
|
|
800
|
+
signal: this._abortController.signal
|
|
801
|
+
});
|
|
802
|
+
if (!response.ok) {
|
|
803
|
+
throw new Error(`SSE connection failed: HTTP ${response.status}`);
|
|
804
|
+
}
|
|
805
|
+
const contentType = response.headers.get("Content-Type") ?? "";
|
|
806
|
+
if (!contentType.includes("text/event-stream")) {
|
|
807
|
+
throw new Error(`Expected text/event-stream, got ${contentType}`);
|
|
808
|
+
}
|
|
809
|
+
if (!response.body) {
|
|
810
|
+
throw new Error("Response has no body");
|
|
811
|
+
}
|
|
812
|
+
this._connected = true;
|
|
813
|
+
this._readStream(response.body);
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Close the SSE connection.
|
|
817
|
+
* Aborts the underlying fetch request and fires onClose.
|
|
818
|
+
*/
|
|
819
|
+
close() {
|
|
820
|
+
if (this._abortController) {
|
|
821
|
+
this._abortController.abort();
|
|
822
|
+
this._abortController = null;
|
|
823
|
+
}
|
|
824
|
+
if (this._connected) {
|
|
825
|
+
this._connected = false;
|
|
826
|
+
this.onClose();
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
/** Whether the client is currently connected to an SSE stream. */
|
|
830
|
+
get isConnected() {
|
|
831
|
+
return this._connected;
|
|
832
|
+
}
|
|
833
|
+
/** The last event ID received from the server (for reconnection). */
|
|
834
|
+
get lastEventId() {
|
|
835
|
+
return this._lastEventId;
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Create a mock SSEClient + controller pair for testing.
|
|
839
|
+
*
|
|
840
|
+
* @example
|
|
841
|
+
* ```typescript
|
|
842
|
+
* const { client, controller } = SSEClient.createMock();
|
|
843
|
+
* client.onMessage = (data) => received.push(data);
|
|
844
|
+
* await client.connect('http://test/events');
|
|
845
|
+
* controller.simulateMessage({ hello: 'world' });
|
|
846
|
+
* controller.simulateClose();
|
|
847
|
+
* ```
|
|
848
|
+
*/
|
|
849
|
+
static createMock() {
|
|
850
|
+
const { fetch, controller } = createMockSSEPair();
|
|
851
|
+
const client = new _SSEClient({ fetch });
|
|
852
|
+
return { client, controller };
|
|
853
|
+
}
|
|
854
|
+
/** Read the SSE stream and dispatch events via the parser. */
|
|
855
|
+
async _readStream(body) {
|
|
856
|
+
const reader = body.getReader();
|
|
857
|
+
const decoder = new TextDecoder();
|
|
858
|
+
const parser = createParser({
|
|
859
|
+
onEvent: (event) => {
|
|
860
|
+
if (event.id !== void 0) {
|
|
861
|
+
this._lastEventId = event.id;
|
|
862
|
+
}
|
|
863
|
+
let parsed;
|
|
864
|
+
try {
|
|
865
|
+
parsed = JSON.parse(event.data);
|
|
866
|
+
} catch {
|
|
867
|
+
parsed = event.data;
|
|
868
|
+
}
|
|
869
|
+
if (event.event) {
|
|
870
|
+
this.onEvent(event.event, parsed);
|
|
871
|
+
} else {
|
|
872
|
+
this.onMessage(parsed);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
// Comments (keepalive) are silently consumed — no handler needed
|
|
876
|
+
});
|
|
877
|
+
try {
|
|
878
|
+
while (true) {
|
|
879
|
+
const { done, value } = await reader.read();
|
|
880
|
+
if (done) break;
|
|
881
|
+
parser.feed(decoder.decode(value, { stream: true }));
|
|
882
|
+
}
|
|
883
|
+
} catch (err) {
|
|
884
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
this.onError(String(err));
|
|
888
|
+
} finally {
|
|
889
|
+
if (this._connected) {
|
|
890
|
+
this._connected = false;
|
|
891
|
+
this.onClose();
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
};
|
|
896
|
+
|
|
897
|
+
// src/streamable-client.ts
|
|
898
|
+
var StreamableClient = class {
|
|
899
|
+
constructor(options = {}) {
|
|
900
|
+
this._abortController = null;
|
|
901
|
+
/** Called when an unnamed data event is received during streaming. */
|
|
902
|
+
this.onMessage = () => {
|
|
903
|
+
};
|
|
904
|
+
/** Called when a named event is received during streaming. */
|
|
905
|
+
this.onEvent = () => {
|
|
906
|
+
};
|
|
907
|
+
/** Called when the SSE stream completes (channel closed by server). */
|
|
908
|
+
this.onDone = () => {
|
|
909
|
+
};
|
|
910
|
+
/** Called when an error occurs. */
|
|
911
|
+
this.onError = () => {
|
|
912
|
+
};
|
|
913
|
+
this._fetch = options.fetch ?? globalThis.fetch;
|
|
914
|
+
this._headers = options.headers ?? {};
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* POST a request to a StreamableServe endpoint.
|
|
918
|
+
*
|
|
919
|
+
* Returns the parsed response for JSON responses, or undefined for
|
|
920
|
+
* streaming responses (events dispatched via callbacks).
|
|
921
|
+
*
|
|
922
|
+
* @param url The endpoint URL
|
|
923
|
+
* @param body The request body (JSON-serialized)
|
|
924
|
+
* @returns Parsed response (JSON path) or undefined (streaming path)
|
|
925
|
+
*/
|
|
926
|
+
async post(url, body) {
|
|
927
|
+
this._abortController = new AbortController();
|
|
928
|
+
const response = await this._fetch(url, {
|
|
929
|
+
method: "POST",
|
|
930
|
+
headers: {
|
|
931
|
+
"Content-Type": "application/json",
|
|
932
|
+
Accept: "text/event-stream, application/json",
|
|
933
|
+
...this._headers
|
|
934
|
+
},
|
|
935
|
+
body: JSON.stringify(body),
|
|
936
|
+
signal: this._abortController.signal
|
|
937
|
+
});
|
|
938
|
+
if (!response.ok) {
|
|
939
|
+
throw new Error(`Request failed: HTTP ${response.status}`);
|
|
940
|
+
}
|
|
941
|
+
const contentType = response.headers.get("Content-Type") ?? "";
|
|
942
|
+
if (contentType.includes("application/json")) {
|
|
943
|
+
const result = await response.json();
|
|
944
|
+
return result;
|
|
945
|
+
}
|
|
946
|
+
if (contentType.includes("text/event-stream")) {
|
|
947
|
+
if (!response.body) {
|
|
948
|
+
throw new Error("Streaming response has no body");
|
|
949
|
+
}
|
|
950
|
+
await this._readStream(response.body);
|
|
951
|
+
return void 0;
|
|
952
|
+
}
|
|
953
|
+
throw new Error(`Unexpected Content-Type: ${contentType}`);
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Abort the current request/stream.
|
|
957
|
+
*/
|
|
958
|
+
close() {
|
|
959
|
+
if (this._abortController) {
|
|
960
|
+
this._abortController.abort();
|
|
961
|
+
this._abortController = null;
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
/** Read an SSE stream and dispatch events. */
|
|
965
|
+
async _readStream(body) {
|
|
966
|
+
const reader = body.getReader();
|
|
967
|
+
const decoder = new TextDecoder();
|
|
968
|
+
const parser = createParser({
|
|
969
|
+
onEvent: (event) => {
|
|
970
|
+
let parsed;
|
|
971
|
+
try {
|
|
972
|
+
parsed = JSON.parse(event.data);
|
|
973
|
+
} catch {
|
|
974
|
+
parsed = event.data;
|
|
975
|
+
}
|
|
976
|
+
if (event.event) {
|
|
977
|
+
this.onEvent(event.event, parsed);
|
|
978
|
+
} else {
|
|
979
|
+
this.onMessage(parsed);
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
});
|
|
983
|
+
try {
|
|
984
|
+
while (true) {
|
|
985
|
+
const { done, value } = await reader.read();
|
|
986
|
+
if (done) break;
|
|
987
|
+
parser.feed(decoder.decode(value, { stream: true }));
|
|
988
|
+
}
|
|
989
|
+
} catch (err) {
|
|
990
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
this.onError(String(err));
|
|
994
|
+
} finally {
|
|
995
|
+
this.onDone();
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
};
|
|
527
999
|
export {
|
|
528
1000
|
BaseWSClient,
|
|
529
1001
|
BinaryCodec,
|
|
530
1002
|
GRPCWSClient,
|
|
531
1003
|
JSONCodec,
|
|
1004
|
+
ParseError,
|
|
532
1005
|
ReadyState,
|
|
1006
|
+
SSEClient,
|
|
1007
|
+
StreamableClient,
|
|
533
1008
|
TypedGRPCWSClient,
|
|
534
|
-
|
|
1009
|
+
createMockSSEPair,
|
|
1010
|
+
createMockWSPair,
|
|
1011
|
+
createParser
|
|
535
1012
|
};
|