@panyam/servicekit-client 0.0.6 → 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/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
- createMockWSPair
1009
+ createMockSSEPair,
1010
+ createMockWSPair,
1011
+ createParser
535
1012
  };