@panyam/servicekit-client 0.0.5 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/sse.test.d.ts +2 -0
- package/dist/__tests__/sse.test.d.ts.map +1 -0
- package/dist/__tests__/sse.test.js +286 -0
- package/dist/__tests__/sse.test.js.map +1 -0
- package/dist/index.d.ts +12 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1012 -0
- package/dist/servicekit-client.browser.js +478 -1
- package/dist/sse-client.d.ts +117 -0
- package/dist/sse-client.d.ts.map +1 -0
- package/dist/sse-client.js +188 -0
- package/dist/sse-client.js.map +1 -0
- package/dist/sse-mock.d.ts +57 -0
- package/dist/sse-mock.d.ts.map +1 -0
- package/dist/sse-mock.js +108 -0
- package/dist/sse-mock.js.map +1 -0
- package/dist/sse-parser.d.ts +64 -0
- package/dist/sse-parser.d.ts.map +1 -0
- package/dist/sse-parser.js +174 -0
- package/dist/sse-parser.js.map +1 -0
- package/dist/streamable-client.d.ts +80 -0
- package/dist/streamable-client.d.ts.map +1 -0
- package/dist/streamable-client.js +142 -0
- package/dist/streamable-client.js.map +1 -0
- package/package.json +14 -10
- package/src/__tests__/sse.test.ts +358 -0
- package/src/index.ts +22 -3
- package/src/sse-client.ts +232 -0
- package/src/sse-mock.ts +159 -0
- package/src/sse-parser.ts +243 -0
- package/src/streamable-client.ts +171 -0
|
@@ -25,9 +25,14 @@ var ServiceKit = (() => {
|
|
|
25
25
|
BinaryCodec: () => BinaryCodec,
|
|
26
26
|
GRPCWSClient: () => GRPCWSClient,
|
|
27
27
|
JSONCodec: () => JSONCodec,
|
|
28
|
+
ParseError: () => ParseError,
|
|
28
29
|
ReadyState: () => ReadyState,
|
|
30
|
+
SSEClient: () => SSEClient,
|
|
31
|
+
StreamableClient: () => StreamableClient,
|
|
29
32
|
TypedGRPCWSClient: () => TypedGRPCWSClient,
|
|
30
|
-
|
|
33
|
+
createMockSSEPair: () => createMockSSEPair,
|
|
34
|
+
createMockWSPair: () => createMockWSPair,
|
|
35
|
+
createParser: () => createParser
|
|
31
36
|
});
|
|
32
37
|
|
|
33
38
|
// src/types.ts
|
|
@@ -556,5 +561,477 @@ var ServiceKit = (() => {
|
|
|
556
561
|
};
|
|
557
562
|
}
|
|
558
563
|
};
|
|
564
|
+
|
|
565
|
+
// src/sse-parser.ts
|
|
566
|
+
var ParseError = class extends Error {
|
|
567
|
+
constructor(message, options) {
|
|
568
|
+
super(message);
|
|
569
|
+
this.name = "ParseError";
|
|
570
|
+
this.type = options.type;
|
|
571
|
+
this.field = options.field;
|
|
572
|
+
this.value = options.value;
|
|
573
|
+
this.line = options.line;
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
function noop(_arg) {
|
|
577
|
+
}
|
|
578
|
+
function createParser(callbacks) {
|
|
579
|
+
if (typeof callbacks === "function") {
|
|
580
|
+
throw new TypeError(
|
|
581
|
+
"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
|
|
585
|
+
let incompleteLine = "";
|
|
586
|
+
let isFirstChunk = true;
|
|
587
|
+
let id;
|
|
588
|
+
let data = "";
|
|
589
|
+
let eventType = "";
|
|
590
|
+
function feed(newChunk) {
|
|
591
|
+
const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk;
|
|
592
|
+
const [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
|
|
593
|
+
for (const line of complete) {
|
|
594
|
+
parseLine(line);
|
|
595
|
+
}
|
|
596
|
+
incompleteLine = incomplete;
|
|
597
|
+
isFirstChunk = false;
|
|
598
|
+
}
|
|
599
|
+
function parseLine(line) {
|
|
600
|
+
if (line === "") {
|
|
601
|
+
dispatchEvent();
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
if (line.startsWith(":")) {
|
|
605
|
+
if (onComment) {
|
|
606
|
+
onComment(line.slice(line.startsWith(": ") ? 2 : 1));
|
|
607
|
+
}
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
const fieldSeparatorIndex = line.indexOf(":");
|
|
611
|
+
if (fieldSeparatorIndex !== -1) {
|
|
612
|
+
const field = line.slice(0, fieldSeparatorIndex);
|
|
613
|
+
const offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1;
|
|
614
|
+
const value = line.slice(fieldSeparatorIndex + offset);
|
|
615
|
+
processField(field, value, line);
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
processField(line, "", line);
|
|
619
|
+
}
|
|
620
|
+
function processField(field, value, line) {
|
|
621
|
+
switch (field) {
|
|
622
|
+
case "event":
|
|
623
|
+
eventType = value;
|
|
624
|
+
break;
|
|
625
|
+
case "data":
|
|
626
|
+
data = `${data}${value}
|
|
627
|
+
`;
|
|
628
|
+
break;
|
|
629
|
+
case "id":
|
|
630
|
+
id = value.includes("\0") ? void 0 : value;
|
|
631
|
+
break;
|
|
632
|
+
case "retry":
|
|
633
|
+
if (/^\d+$/.test(value)) {
|
|
634
|
+
onRetry(parseInt(value, 10));
|
|
635
|
+
} else {
|
|
636
|
+
onError(
|
|
637
|
+
new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
638
|
+
type: "invalid-retry",
|
|
639
|
+
value,
|
|
640
|
+
line
|
|
641
|
+
})
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
break;
|
|
645
|
+
default:
|
|
646
|
+
onError(
|
|
647
|
+
new ParseError(
|
|
648
|
+
`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
|
|
649
|
+
{ type: "unknown-field", field, value, line }
|
|
650
|
+
)
|
|
651
|
+
);
|
|
652
|
+
break;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
function dispatchEvent() {
|
|
656
|
+
const shouldDispatch = data.length > 0;
|
|
657
|
+
if (shouldDispatch) {
|
|
658
|
+
onEvent({
|
|
659
|
+
id,
|
|
660
|
+
event: eventType || void 0,
|
|
661
|
+
data: data.endsWith("\n") ? data.slice(0, -1) : data
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
id = void 0;
|
|
665
|
+
data = "";
|
|
666
|
+
eventType = "";
|
|
667
|
+
}
|
|
668
|
+
function reset(options = {}) {
|
|
669
|
+
if (incompleteLine && options.consume) {
|
|
670
|
+
parseLine(incompleteLine);
|
|
671
|
+
}
|
|
672
|
+
isFirstChunk = true;
|
|
673
|
+
id = void 0;
|
|
674
|
+
data = "";
|
|
675
|
+
eventType = "";
|
|
676
|
+
incompleteLine = "";
|
|
677
|
+
}
|
|
678
|
+
return { feed, reset };
|
|
679
|
+
}
|
|
680
|
+
function splitLines(chunk) {
|
|
681
|
+
const lines = [];
|
|
682
|
+
let incompleteLine = "";
|
|
683
|
+
let searchIndex = 0;
|
|
684
|
+
while (searchIndex < chunk.length) {
|
|
685
|
+
const crIndex = chunk.indexOf("\r", searchIndex);
|
|
686
|
+
const lfIndex = chunk.indexOf("\n", searchIndex);
|
|
687
|
+
let lineEnd = -1;
|
|
688
|
+
if (crIndex !== -1 && lfIndex !== -1) {
|
|
689
|
+
lineEnd = Math.min(crIndex, lfIndex);
|
|
690
|
+
} else if (crIndex !== -1) {
|
|
691
|
+
if (crIndex === chunk.length - 1) {
|
|
692
|
+
lineEnd = -1;
|
|
693
|
+
} else {
|
|
694
|
+
lineEnd = crIndex;
|
|
695
|
+
}
|
|
696
|
+
} else if (lfIndex !== -1) {
|
|
697
|
+
lineEnd = lfIndex;
|
|
698
|
+
}
|
|
699
|
+
if (lineEnd === -1) {
|
|
700
|
+
incompleteLine = chunk.slice(searchIndex);
|
|
701
|
+
break;
|
|
702
|
+
} else {
|
|
703
|
+
const line = chunk.slice(searchIndex, lineEnd);
|
|
704
|
+
lines.push(line);
|
|
705
|
+
searchIndex = lineEnd + 1;
|
|
706
|
+
if (chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === "\n") {
|
|
707
|
+
searchIndex++;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
return [lines, incompleteLine];
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// src/sse-mock.ts
|
|
715
|
+
function createMockSSEPair(contentType = "text/event-stream") {
|
|
716
|
+
let streamController = null;
|
|
717
|
+
let capturedUrl;
|
|
718
|
+
let capturedHeaders = {};
|
|
719
|
+
let capturedMethod;
|
|
720
|
+
let capturedBody;
|
|
721
|
+
const encoder = new TextEncoder();
|
|
722
|
+
const enqueue = (text) => {
|
|
723
|
+
if (streamController) {
|
|
724
|
+
streamController.enqueue(encoder.encode(text));
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
const mockFetch = async (input, init) => {
|
|
728
|
+
capturedUrl = typeof input === "string" ? input : input.toString();
|
|
729
|
+
capturedMethod = init?.method ?? "GET";
|
|
730
|
+
capturedBody = typeof init?.body === "string" ? init.body : void 0;
|
|
731
|
+
capturedHeaders = {};
|
|
732
|
+
if (init?.headers) {
|
|
733
|
+
if (init.headers instanceof Headers) {
|
|
734
|
+
init.headers.forEach((v, k) => {
|
|
735
|
+
capturedHeaders[k] = v;
|
|
736
|
+
});
|
|
737
|
+
} else if (Array.isArray(init.headers)) {
|
|
738
|
+
for (const [k, v] of init.headers) {
|
|
739
|
+
capturedHeaders[k] = v;
|
|
740
|
+
}
|
|
741
|
+
} else {
|
|
742
|
+
capturedHeaders = { ...init.headers };
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
const body = new ReadableStream({
|
|
746
|
+
start(controller2) {
|
|
747
|
+
streamController = controller2;
|
|
748
|
+
}
|
|
749
|
+
});
|
|
750
|
+
return new Response(body, {
|
|
751
|
+
status: 200,
|
|
752
|
+
headers: { "Content-Type": contentType }
|
|
753
|
+
});
|
|
754
|
+
};
|
|
755
|
+
const controller = {
|
|
756
|
+
simulateMessage(data) {
|
|
757
|
+
enqueue(`data: ${JSON.stringify(data)}
|
|
758
|
+
|
|
759
|
+
`);
|
|
760
|
+
},
|
|
761
|
+
simulateEvent(event, data) {
|
|
762
|
+
enqueue(`event: ${event}
|
|
763
|
+
data: ${JSON.stringify(data)}
|
|
764
|
+
|
|
765
|
+
`);
|
|
766
|
+
},
|
|
767
|
+
simulateEventWithId(event, id, data) {
|
|
768
|
+
enqueue(`event: ${event}
|
|
769
|
+
id: ${id}
|
|
770
|
+
data: ${JSON.stringify(data)}
|
|
771
|
+
|
|
772
|
+
`);
|
|
773
|
+
},
|
|
774
|
+
simulateComment(text) {
|
|
775
|
+
enqueue(`: ${text}
|
|
776
|
+
|
|
777
|
+
`);
|
|
778
|
+
},
|
|
779
|
+
simulateClose() {
|
|
780
|
+
if (streamController) {
|
|
781
|
+
streamController.close();
|
|
782
|
+
streamController = null;
|
|
783
|
+
}
|
|
784
|
+
},
|
|
785
|
+
get receivedUrl() {
|
|
786
|
+
return capturedUrl;
|
|
787
|
+
},
|
|
788
|
+
get receivedHeaders() {
|
|
789
|
+
return capturedHeaders;
|
|
790
|
+
},
|
|
791
|
+
get receivedMethod() {
|
|
792
|
+
return capturedMethod;
|
|
793
|
+
},
|
|
794
|
+
get receivedBody() {
|
|
795
|
+
return capturedBody;
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
return { fetch: mockFetch, controller };
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// src/sse-client.ts
|
|
802
|
+
var SSEClient = class _SSEClient {
|
|
803
|
+
constructor(options = {}) {
|
|
804
|
+
this._connected = false;
|
|
805
|
+
this._abortController = null;
|
|
806
|
+
/** Called when an unnamed data event is received (no "event:" field). */
|
|
807
|
+
this.onMessage = () => {
|
|
808
|
+
};
|
|
809
|
+
/** Called when a named event is received (has "event:" field). */
|
|
810
|
+
this.onEvent = () => {
|
|
811
|
+
};
|
|
812
|
+
/** Called when the SSE stream closes (server closes or network error). */
|
|
813
|
+
this.onClose = () => {
|
|
814
|
+
};
|
|
815
|
+
/** Called when an error occurs (fetch failure, parse error). */
|
|
816
|
+
this.onError = () => {
|
|
817
|
+
};
|
|
818
|
+
this._fetch = options.fetch ?? globalThis.fetch;
|
|
819
|
+
this._headers = options.headers ?? {};
|
|
820
|
+
this._lastEventId = options.lastEventId;
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* Connect to an SSE endpoint.
|
|
824
|
+
*
|
|
825
|
+
* @param url The HTTP URL to connect to
|
|
826
|
+
* @returns Promise that resolves when the connection is established (headers received)
|
|
827
|
+
* @throws Error if the response is not 200 or not text/event-stream
|
|
828
|
+
*/
|
|
829
|
+
async connect(url) {
|
|
830
|
+
const headers = { ...this._headers };
|
|
831
|
+
if (this._lastEventId) {
|
|
832
|
+
headers["Last-Event-ID"] = this._lastEventId;
|
|
833
|
+
}
|
|
834
|
+
this._abortController = new AbortController();
|
|
835
|
+
const response = await this._fetch(url, {
|
|
836
|
+
headers,
|
|
837
|
+
signal: this._abortController.signal
|
|
838
|
+
});
|
|
839
|
+
if (!response.ok) {
|
|
840
|
+
throw new Error(`SSE connection failed: HTTP ${response.status}`);
|
|
841
|
+
}
|
|
842
|
+
const contentType = response.headers.get("Content-Type") ?? "";
|
|
843
|
+
if (!contentType.includes("text/event-stream")) {
|
|
844
|
+
throw new Error(`Expected text/event-stream, got ${contentType}`);
|
|
845
|
+
}
|
|
846
|
+
if (!response.body) {
|
|
847
|
+
throw new Error("Response has no body");
|
|
848
|
+
}
|
|
849
|
+
this._connected = true;
|
|
850
|
+
this._readStream(response.body);
|
|
851
|
+
}
|
|
852
|
+
/**
|
|
853
|
+
* Close the SSE connection.
|
|
854
|
+
* Aborts the underlying fetch request and fires onClose.
|
|
855
|
+
*/
|
|
856
|
+
close() {
|
|
857
|
+
if (this._abortController) {
|
|
858
|
+
this._abortController.abort();
|
|
859
|
+
this._abortController = null;
|
|
860
|
+
}
|
|
861
|
+
if (this._connected) {
|
|
862
|
+
this._connected = false;
|
|
863
|
+
this.onClose();
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
/** Whether the client is currently connected to an SSE stream. */
|
|
867
|
+
get isConnected() {
|
|
868
|
+
return this._connected;
|
|
869
|
+
}
|
|
870
|
+
/** The last event ID received from the server (for reconnection). */
|
|
871
|
+
get lastEventId() {
|
|
872
|
+
return this._lastEventId;
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* Create a mock SSEClient + controller pair for testing.
|
|
876
|
+
*
|
|
877
|
+
* @example
|
|
878
|
+
* ```typescript
|
|
879
|
+
* const { client, controller } = SSEClient.createMock();
|
|
880
|
+
* client.onMessage = (data) => received.push(data);
|
|
881
|
+
* await client.connect('http://test/events');
|
|
882
|
+
* controller.simulateMessage({ hello: 'world' });
|
|
883
|
+
* controller.simulateClose();
|
|
884
|
+
* ```
|
|
885
|
+
*/
|
|
886
|
+
static createMock() {
|
|
887
|
+
const { fetch, controller } = createMockSSEPair();
|
|
888
|
+
const client = new _SSEClient({ fetch });
|
|
889
|
+
return { client, controller };
|
|
890
|
+
}
|
|
891
|
+
/** Read the SSE stream and dispatch events via the parser. */
|
|
892
|
+
async _readStream(body) {
|
|
893
|
+
const reader = body.getReader();
|
|
894
|
+
const decoder = new TextDecoder();
|
|
895
|
+
const parser = createParser({
|
|
896
|
+
onEvent: (event) => {
|
|
897
|
+
if (event.id !== void 0) {
|
|
898
|
+
this._lastEventId = event.id;
|
|
899
|
+
}
|
|
900
|
+
let parsed;
|
|
901
|
+
try {
|
|
902
|
+
parsed = JSON.parse(event.data);
|
|
903
|
+
} catch {
|
|
904
|
+
parsed = event.data;
|
|
905
|
+
}
|
|
906
|
+
if (event.event) {
|
|
907
|
+
this.onEvent(event.event, parsed);
|
|
908
|
+
} else {
|
|
909
|
+
this.onMessage(parsed);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
// Comments (keepalive) are silently consumed — no handler needed
|
|
913
|
+
});
|
|
914
|
+
try {
|
|
915
|
+
while (true) {
|
|
916
|
+
const { done, value } = await reader.read();
|
|
917
|
+
if (done) break;
|
|
918
|
+
parser.feed(decoder.decode(value, { stream: true }));
|
|
919
|
+
}
|
|
920
|
+
} catch (err) {
|
|
921
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
this.onError(String(err));
|
|
925
|
+
} finally {
|
|
926
|
+
if (this._connected) {
|
|
927
|
+
this._connected = false;
|
|
928
|
+
this.onClose();
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
|
|
934
|
+
// src/streamable-client.ts
|
|
935
|
+
var StreamableClient = class {
|
|
936
|
+
constructor(options = {}) {
|
|
937
|
+
this._abortController = null;
|
|
938
|
+
/** Called when an unnamed data event is received during streaming. */
|
|
939
|
+
this.onMessage = () => {
|
|
940
|
+
};
|
|
941
|
+
/** Called when a named event is received during streaming. */
|
|
942
|
+
this.onEvent = () => {
|
|
943
|
+
};
|
|
944
|
+
/** Called when the SSE stream completes (channel closed by server). */
|
|
945
|
+
this.onDone = () => {
|
|
946
|
+
};
|
|
947
|
+
/** Called when an error occurs. */
|
|
948
|
+
this.onError = () => {
|
|
949
|
+
};
|
|
950
|
+
this._fetch = options.fetch ?? globalThis.fetch;
|
|
951
|
+
this._headers = options.headers ?? {};
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* POST a request to a StreamableServe endpoint.
|
|
955
|
+
*
|
|
956
|
+
* Returns the parsed response for JSON responses, or undefined for
|
|
957
|
+
* streaming responses (events dispatched via callbacks).
|
|
958
|
+
*
|
|
959
|
+
* @param url The endpoint URL
|
|
960
|
+
* @param body The request body (JSON-serialized)
|
|
961
|
+
* @returns Parsed response (JSON path) or undefined (streaming path)
|
|
962
|
+
*/
|
|
963
|
+
async post(url, body) {
|
|
964
|
+
this._abortController = new AbortController();
|
|
965
|
+
const response = await this._fetch(url, {
|
|
966
|
+
method: "POST",
|
|
967
|
+
headers: {
|
|
968
|
+
"Content-Type": "application/json",
|
|
969
|
+
Accept: "text/event-stream, application/json",
|
|
970
|
+
...this._headers
|
|
971
|
+
},
|
|
972
|
+
body: JSON.stringify(body),
|
|
973
|
+
signal: this._abortController.signal
|
|
974
|
+
});
|
|
975
|
+
if (!response.ok) {
|
|
976
|
+
throw new Error(`Request failed: HTTP ${response.status}`);
|
|
977
|
+
}
|
|
978
|
+
const contentType = response.headers.get("Content-Type") ?? "";
|
|
979
|
+
if (contentType.includes("application/json")) {
|
|
980
|
+
const result = await response.json();
|
|
981
|
+
return result;
|
|
982
|
+
}
|
|
983
|
+
if (contentType.includes("text/event-stream")) {
|
|
984
|
+
if (!response.body) {
|
|
985
|
+
throw new Error("Streaming response has no body");
|
|
986
|
+
}
|
|
987
|
+
await this._readStream(response.body);
|
|
988
|
+
return void 0;
|
|
989
|
+
}
|
|
990
|
+
throw new Error(`Unexpected Content-Type: ${contentType}`);
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Abort the current request/stream.
|
|
994
|
+
*/
|
|
995
|
+
close() {
|
|
996
|
+
if (this._abortController) {
|
|
997
|
+
this._abortController.abort();
|
|
998
|
+
this._abortController = null;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
/** Read an SSE stream and dispatch events. */
|
|
1002
|
+
async _readStream(body) {
|
|
1003
|
+
const reader = body.getReader();
|
|
1004
|
+
const decoder = new TextDecoder();
|
|
1005
|
+
const parser = createParser({
|
|
1006
|
+
onEvent: (event) => {
|
|
1007
|
+
let parsed;
|
|
1008
|
+
try {
|
|
1009
|
+
parsed = JSON.parse(event.data);
|
|
1010
|
+
} catch {
|
|
1011
|
+
parsed = event.data;
|
|
1012
|
+
}
|
|
1013
|
+
if (event.event) {
|
|
1014
|
+
this.onEvent(event.event, parsed);
|
|
1015
|
+
} else {
|
|
1016
|
+
this.onMessage(parsed);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
});
|
|
1020
|
+
try {
|
|
1021
|
+
while (true) {
|
|
1022
|
+
const { done, value } = await reader.read();
|
|
1023
|
+
if (done) break;
|
|
1024
|
+
parser.feed(decoder.decode(value, { stream: true }));
|
|
1025
|
+
}
|
|
1026
|
+
} catch (err) {
|
|
1027
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
this.onError(String(err));
|
|
1031
|
+
} finally {
|
|
1032
|
+
this.onDone();
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
559
1036
|
return __toCommonJS(index_exports);
|
|
560
1037
|
})();
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSEClient — Server-Sent Events client for ServiceKit SSEServe endpoints.
|
|
3
|
+
*
|
|
4
|
+
* Uses `fetch` + `ReadableStream` for SSE consumption (not the browser's
|
|
5
|
+
* native `EventSource`, which is GET-only and doesn't support custom headers).
|
|
6
|
+
*
|
|
7
|
+
* Follows the same patterns as BaseWSClient:
|
|
8
|
+
* - Event handler properties (onMessage, onError, onClose)
|
|
9
|
+
* - Dependency injection for fetch (SSEClientOptions.fetch)
|
|
10
|
+
* - Static createMock() for testing
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* const client = new SSEClient<MyEvent>();
|
|
15
|
+
* client.onMessage = (data) => console.log('Received:', data);
|
|
16
|
+
* client.onEvent = (type, data) => console.log('Event:', type, data);
|
|
17
|
+
* await client.connect('http://localhost:8080/events');
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
import type { MessageHandler, ErrorHandler, VoidHandler } from './types';
|
|
21
|
+
import { MockSSEController } from './sse-mock';
|
|
22
|
+
/**
|
|
23
|
+
* Options for configuring SSEClient.
|
|
24
|
+
*/
|
|
25
|
+
export interface SSEClientOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Custom fetch implementation (for Node.js or testing).
|
|
28
|
+
* Default: globalThis.fetch
|
|
29
|
+
*/
|
|
30
|
+
fetch?: typeof globalThis.fetch;
|
|
31
|
+
/**
|
|
32
|
+
* HTTP headers to include in the SSE request.
|
|
33
|
+
* Useful for authentication tokens.
|
|
34
|
+
*/
|
|
35
|
+
headers?: Record<string, string>;
|
|
36
|
+
/**
|
|
37
|
+
* Initial Last-Event-ID for reconnection.
|
|
38
|
+
* If set, the client sends this as the Last-Event-ID header on connect.
|
|
39
|
+
*/
|
|
40
|
+
lastEventId?: string;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* SSE client for long-lived server-sent event streams.
|
|
44
|
+
*
|
|
45
|
+
* Connects to SSEServe endpoints via HTTP GET, parses the SSE stream using
|
|
46
|
+
* a vendored WHATWG-compliant parser, and dispatches events to handlers.
|
|
47
|
+
*
|
|
48
|
+
* Features:
|
|
49
|
+
* - Custom headers (auth tokens) — unlike native EventSource
|
|
50
|
+
* - POST support — unlike native EventSource
|
|
51
|
+
* - Keepalive comments silently consumed
|
|
52
|
+
* - Last-Event-ID tracking for reconnection
|
|
53
|
+
* - Mock utilities for testing (SSEClient.createMock())
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```typescript
|
|
57
|
+
* const client = new SSEClient<{ status: string }>();
|
|
58
|
+
* client.onMessage = (data) => console.log(data.status);
|
|
59
|
+
* client.onEvent = (type, data) => console.log(type, data);
|
|
60
|
+
* client.onClose = () => console.log('Stream ended');
|
|
61
|
+
* await client.connect('http://localhost:8080/events', {
|
|
62
|
+
* headers: { Authorization: 'Bearer token' },
|
|
63
|
+
* });
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
export declare class SSEClient<O = unknown> {
|
|
67
|
+
private _fetch;
|
|
68
|
+
private _headers;
|
|
69
|
+
private _lastEventId;
|
|
70
|
+
private _connected;
|
|
71
|
+
private _abortController;
|
|
72
|
+
/** Called when an unnamed data event is received (no "event:" field). */
|
|
73
|
+
onMessage: MessageHandler<O>;
|
|
74
|
+
/** Called when a named event is received (has "event:" field). */
|
|
75
|
+
onEvent: (event: string, data: O) => void;
|
|
76
|
+
/** Called when the SSE stream closes (server closes or network error). */
|
|
77
|
+
onClose: VoidHandler;
|
|
78
|
+
/** Called when an error occurs (fetch failure, parse error). */
|
|
79
|
+
onError: ErrorHandler;
|
|
80
|
+
constructor(options?: SSEClientOptions);
|
|
81
|
+
/**
|
|
82
|
+
* Connect to an SSE endpoint.
|
|
83
|
+
*
|
|
84
|
+
* @param url The HTTP URL to connect to
|
|
85
|
+
* @returns Promise that resolves when the connection is established (headers received)
|
|
86
|
+
* @throws Error if the response is not 200 or not text/event-stream
|
|
87
|
+
*/
|
|
88
|
+
connect(url: string): Promise<void>;
|
|
89
|
+
/**
|
|
90
|
+
* Close the SSE connection.
|
|
91
|
+
* Aborts the underlying fetch request and fires onClose.
|
|
92
|
+
*/
|
|
93
|
+
close(): void;
|
|
94
|
+
/** Whether the client is currently connected to an SSE stream. */
|
|
95
|
+
get isConnected(): boolean;
|
|
96
|
+
/** The last event ID received from the server (for reconnection). */
|
|
97
|
+
get lastEventId(): string | undefined;
|
|
98
|
+
/**
|
|
99
|
+
* Create a mock SSEClient + controller pair for testing.
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* ```typescript
|
|
103
|
+
* const { client, controller } = SSEClient.createMock();
|
|
104
|
+
* client.onMessage = (data) => received.push(data);
|
|
105
|
+
* await client.connect('http://test/events');
|
|
106
|
+
* controller.simulateMessage({ hello: 'world' });
|
|
107
|
+
* controller.simulateClose();
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
static createMock<O = unknown>(): {
|
|
111
|
+
client: SSEClient<O>;
|
|
112
|
+
controller: MockSSEController;
|
|
113
|
+
};
|
|
114
|
+
/** Read the SSE stream and dispatch events via the parser. */
|
|
115
|
+
private _readStream;
|
|
116
|
+
}
|
|
117
|
+
//# sourceMappingURL=sse-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse-client.d.ts","sourceRoot":"","sources":["../src/sse-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAEzE,OAAO,EAAqB,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAElE;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAEhC;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAEjC;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,SAAS,CAAC,CAAC,GAAG,OAAO;IAChC,OAAO,CAAC,MAAM,CAA0B;IACxC,OAAO,CAAC,QAAQ,CAAyB;IACzC,OAAO,CAAC,YAAY,CAAqB;IACzC,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,gBAAgB,CAAgC;IAExD,yEAAyE;IAClE,SAAS,EAAE,cAAc,CAAC,CAAC,CAAC,CAAY;IAE/C,kEAAkE;IAC3D,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,KAAK,IAAI,CAAY;IAE5D,0EAA0E;IACnE,OAAO,EAAE,WAAW,CAAY;IAEvC,gEAAgE;IACzD,OAAO,EAAE,YAAY,CAAY;gBAE5B,OAAO,GAAE,gBAAqB;IAM1C;;;;;;OAMG;IACG,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAgCzC;;;OAGG;IACH,KAAK,IAAI,IAAI;IAWb,kEAAkE;IAClE,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED,qEAAqE;IACrE,IAAI,WAAW,IAAI,MAAM,GAAG,SAAS,CAEpC;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,UAAU,CAAC,CAAC,GAAG,OAAO,KAAK;QAChC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;QACrB,UAAU,EAAE,iBAAiB,CAAC;KAC/B;IAMD,8DAA8D;YAChD,WAAW;CAiD1B"}
|