@ahoo-wang/fetcher-eventstream 1.0.6 → 1.0.8

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.es.js CHANGED
@@ -1,5 +1,5 @@
1
- import { ContentTypeHeader as c, ContentTypeValues as d } from "@ahoo-wang/fetcher";
2
- class u {
1
+ import { CONTENT_TYPE_HEADER as T, ContentTypeValues as u } from "@ahoo-wang/fetcher";
2
+ class d {
3
3
  constructor() {
4
4
  this.buffer = "";
5
5
  }
@@ -34,35 +34,38 @@ class u {
34
34
  }
35
35
  }
36
36
  }
37
- class E extends TransformStream {
37
+ class m extends TransformStream {
38
38
  constructor() {
39
- super(new u());
39
+ super(new d());
40
40
  }
41
41
  }
42
- var T = /* @__PURE__ */ ((n) => (n.ID = "id", n.RETRY = "retry", n.EVENT = "event", n.DATA = "data", n))(T || {});
43
- function m(n, t, e) {
42
+ const c = class c {
43
+ };
44
+ c.ID = "id", c.RETRY = "retry", c.EVENT = "event", c.DATA = "data";
45
+ let i = c;
46
+ function h(n, t, e) {
44
47
  switch (n) {
45
- case "event":
48
+ case i.EVENT:
46
49
  e.event = t;
47
50
  break;
48
- case "data":
51
+ case i.DATA:
49
52
  e.data.push(t);
50
53
  break;
51
- case "id":
54
+ case i.ID:
52
55
  e.id = t;
53
56
  break;
54
- case "retry": {
57
+ case i.RETRY: {
55
58
  const r = parseInt(t, 10);
56
59
  isNaN(r) || (e.retry = r);
57
60
  break;
58
61
  }
59
62
  }
60
63
  }
61
- const a = "message";
62
- class v {
64
+ const o = "message";
65
+ class p {
63
66
  constructor() {
64
67
  this.currentEvent = {
65
- event: a,
68
+ event: o,
66
69
  id: void 0,
67
70
  retry: void 0,
68
71
  data: []
@@ -79,23 +82,23 @@ class v {
79
82
  try {
80
83
  if (t.trim() === "") {
81
84
  r.data.length > 0 && (e.enqueue({
82
- event: r.event || a,
85
+ event: r.event || o,
83
86
  data: r.data.join(`
84
87
  `),
85
88
  id: r.id || "",
86
89
  retry: r.retry
87
- }), r.event = a, r.data = []);
90
+ }), r.event = o, r.data = []);
88
91
  return;
89
92
  }
90
93
  if (t.startsWith(":"))
91
94
  return;
92
95
  const s = t.indexOf(":");
93
- let i, o;
94
- s === -1 ? (i = t.toLowerCase(), o = "") : (i = t.substring(0, s).toLowerCase(), o = t.substring(s + 1), o.startsWith(" ") && (o = o.substring(1))), i = i.trim(), o = o.trim(), m(i, o, r);
96
+ let f, a;
97
+ s === -1 ? (f = t.toLowerCase(), a = "") : (f = t.substring(0, s).toLowerCase(), a = t.substring(s + 1), a.startsWith(" ") && (a = a.substring(1))), f = f.trim(), a = a.trim(), h(f, a, r);
95
98
  } catch (s) {
96
99
  e.error(
97
100
  s instanceof Error ? s : new Error(String(s))
98
- ), r.event = a, r.id = void 0, r.retry = void 0, r.data = [];
101
+ ), r.event = o, r.id = void 0, r.retry = void 0, r.data = [];
99
102
  }
100
103
  }
101
104
  /**
@@ -107,7 +110,7 @@ class v {
107
110
  const e = this.currentEvent;
108
111
  try {
109
112
  e.data.length > 0 && t.enqueue({
110
- event: e.event || a,
113
+ event: e.event || o,
111
114
  data: e.data.join(`
112
115
  `),
113
116
  id: e.id || "",
@@ -118,21 +121,21 @@ class v {
118
121
  r instanceof Error ? r : new Error(String(r))
119
122
  );
120
123
  } finally {
121
- e.event = a, e.id = void 0, e.retry = void 0, e.data = [];
124
+ e.event = o, e.id = void 0, e.retry = void 0, e.data = [];
122
125
  }
123
126
  }
124
127
  }
125
- class p extends TransformStream {
128
+ class v extends TransformStream {
126
129
  constructor() {
127
- super(new v());
130
+ super(new p());
128
131
  }
129
132
  }
130
- function f(n) {
133
+ function E(n) {
131
134
  if (!n.body)
132
135
  throw new Error("Response body is null");
133
- return n.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new E()).pipeThrough(new p());
136
+ return n.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new m()).pipeThrough(new v());
134
137
  }
135
- class S {
138
+ class y {
136
139
  transform(t, e) {
137
140
  const r = JSON.parse(t.data);
138
141
  e.enqueue({
@@ -143,20 +146,20 @@ class S {
143
146
  });
144
147
  }
145
148
  }
146
- class h extends TransformStream {
149
+ class S extends TransformStream {
147
150
  constructor() {
148
- super(new S());
151
+ super(new y());
149
152
  }
150
153
  }
151
- function y(n) {
154
+ function b(n) {
152
155
  return n.pipeThrough(
153
- new h()
156
+ new S()
154
157
  );
155
158
  }
156
- const b = "EventStreamInterceptor", l = Number.MAX_SAFE_INTEGER - 1e3;
157
- class g {
159
+ const N = "EventStreamInterceptor", R = Number.MAX_SAFE_INTEGER - 1e3;
160
+ class w {
158
161
  constructor() {
159
- this.name = b, this.order = l;
162
+ this.name = N, this.order = R;
160
163
  }
161
164
  /**
162
165
  * Intercepts responses to add event stream capabilities.
@@ -180,21 +183,21 @@ class g {
180
183
  const e = t.response;
181
184
  if (!e)
182
185
  return;
183
- e.headers.get(c)?.includes(d.TEXT_EVENT_STREAM) && (e.eventStream = () => f(e), e.jsonEventStream = () => y(f(e)));
186
+ e.headers.get(T)?.includes(u.TEXT_EVENT_STREAM) && (e.eventStream = () => E(e), e.jsonEventStream = () => b(E(e)));
184
187
  }
185
188
  }
186
189
  export {
187
- b as EVENT_STREAM_INTERCEPTOR_NAME,
188
- l as EVENT_STREAM_INTERCEPTOR_ORDER,
189
- g as EventStreamInterceptor,
190
- S as JsonServerSentEventTransform,
191
- h as JsonServerSentEventTransformStream,
192
- T as ServerSentEventField,
193
- p as ServerSentEventTransformStream,
194
- v as ServerSentEventTransformer,
195
- E as TextLineTransformStream,
196
- u as TextLineTransformer,
197
- y as toJsonServerSentEventStream,
198
- f as toServerSentEventStream
190
+ N as EVENT_STREAM_INTERCEPTOR_NAME,
191
+ R as EVENT_STREAM_INTERCEPTOR_ORDER,
192
+ w as EventStreamInterceptor,
193
+ y as JsonServerSentEventTransform,
194
+ S as JsonServerSentEventTransformStream,
195
+ i as ServerSentEventFields,
196
+ v as ServerSentEventTransformStream,
197
+ p as ServerSentEventTransformer,
198
+ m as TextLineTransformStream,
199
+ d as TextLineTransformer,
200
+ b as toJsonServerSentEventStream,
201
+ E as toServerSentEventStream
199
202
  };
200
203
  //# sourceMappingURL=index.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/eventStreamInterceptor.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Transformer that splits text into lines.\n *\n * This transformer accumulates chunks of text and splits them by newline characters,\n * emitting each line as a separate chunk while preserving the remaining buffer\n * for the next chunk.\n */\nexport class TextLineTransformer implements Transformer<string, string> {\n private buffer = '';\n\n /**\n * Transform input string chunk by splitting it into lines.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<string>,\n ) {\n try {\n this.buffer += chunk;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() || '';\n\n for (const line of lines) {\n controller.enqueue(line);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n\n /**\n * Flush remaining buffer when the stream ends.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<string>) {\n try {\n // Only send when buffer is not empty, avoid sending meaningless empty lines\n if (this.buffer) {\n controller.enqueue(this.buffer);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n}\n\n/**\n * A TransformStream that splits text into lines.\n */\nexport class TextLineTransformStream extends TransformStream<string, string> {\n constructor() {\n super(new TextLineTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents a message sent in an event stream.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format}\n */\nexport interface ServerSentEvent {\n /** The event ID to set the EventSource object's last event ID value. */\n id?: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\nexport enum ServerSentEventField {\n ID = 'id',\n RETRY = 'retry',\n EVENT = 'event',\n DATA = 'data',\n}\n\n/**\n * Process field value\n * @param field Field name\n * @param value Field value\n * @param currentEvent Current event state\n */\nfunction processFieldInternal(\n field: string,\n value: string,\n currentEvent: EventState,\n) {\n switch (field) {\n case ServerSentEventField.EVENT:\n currentEvent.event = value;\n break;\n case ServerSentEventField.DATA:\n currentEvent.data.push(value);\n break;\n case ServerSentEventField.ID:\n currentEvent.id = value;\n break;\n case ServerSentEventField.RETRY: {\n const retryValue = parseInt(value, 10);\n if (!isNaN(retryValue)) {\n currentEvent.retry = retryValue;\n }\n break;\n }\n default:\n // Ignore unknown fields\n break;\n }\n}\n\ninterface EventState {\n event?: string;\n id?: string;\n retry?: number;\n data: string[];\n}\n\nconst DEFAULT_EVENT_TYPE = 'message';\n\n/**\n * Transformer responsible for converting a string stream into a ServerSentEvent object stream.\n *\n * Implements the Transformer interface for processing data transformation in TransformStream.\n */\nexport class ServerSentEventTransformer\n implements Transformer<string, ServerSentEvent>\n{\n // Initialize currentEvent with default values in a closure\n private currentEvent: EventState = {\n event: DEFAULT_EVENT_TYPE,\n id: undefined,\n retry: undefined,\n data: [],\n };\n\n /**\n * Transform input string chunk into ServerSentEvent object.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<ServerSentEvent>,\n ) {\n const currentEvent = this.currentEvent;\n try {\n // Skip empty lines (event separator)\n if (chunk.trim() === '') {\n // If there is accumulated event data, send event\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n\n // Reset current event (preserve id and retry for subsequent events)\n currentEvent.event = DEFAULT_EVENT_TYPE;\n // Preserve id and retry for subsequent events (no need to reassign to themselves)\n currentEvent.data = [];\n }\n return;\n }\n\n // Ignore comment lines (starting with colon)\n if (chunk.startsWith(':')) {\n return;\n }\n\n // Parse fields\n const colonIndex = chunk.indexOf(':');\n let field: string;\n let value: string;\n\n if (colonIndex === -1) {\n // No colon, entire line as field name, value is empty\n field = chunk.toLowerCase();\n value = '';\n } else {\n // Extract field name and value\n field = chunk.substring(0, colonIndex).toLowerCase();\n value = chunk.substring(colonIndex + 1);\n\n // If value starts with space, remove leading space\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n }\n\n // Remove trailing newlines from field and value\n field = field.trim();\n value = value.trim();\n\n processFieldInternal(field, value, currentEvent);\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n\n /**\n * Called when the stream ends, used to process remaining data.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<ServerSentEvent>) {\n const currentEvent = this.currentEvent;\n try {\n // Send the last event (if any)\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n }\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n } finally {\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n}\n\n/**\n * A TransformStream that converts a stream of strings into a stream of ServerSentEvent objects.\n */\nexport class ServerSentEventTransformStream extends TransformStream<\n string,\n ServerSentEvent\n> {\n constructor() {\n super(new ServerSentEventTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TextLineTransformStream } from './textLineTransformStream';\nimport {\n ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Converts a Response object to a ServerSentEventStream.\n *\n * Processes the response body through a series of transform streams:\n * 1. TextDecoderStream: Decode Uint8Array data to UTF-8 strings\n * 2. TextLineStream: Split text by lines\n * 3. ServerSentEventStream: Parse line data into server-sent events\n *\n * @param response - The Response object to convert\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws Error if the response body is null\n */\nexport function toServerSentEventStream(\n response: Response,\n): ServerSentEventStream {\n if (!response.body) {\n throw new Error('Response body is null');\n }\n\n return response.body\n .pipeThrough(new TextDecoderStream('utf-8'))\n .pipeThrough(new TextLineTransformStream())\n .pipeThrough(new ServerSentEventTransformStream());\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ServerSentEvent } from './serverSentEventTransformStream';\nimport { ServerSentEventStream } from './eventStreamConverter';\n\nexport interface JsonServerSentEvent<DATA>\n extends Omit<ServerSentEvent, 'data'> {\n data: DATA;\n}\n\nexport class JsonServerSentEventTransform<DATA>\n implements Transformer<ServerSentEvent, JsonServerSentEvent<DATA>> {\n transform(\n chunk: ServerSentEvent,\n controller: TransformStreamDefaultController<JsonServerSentEvent<DATA>>,\n ) {\n const json = JSON.parse(chunk.data) as DATA;\n controller.enqueue({\n data: json,\n event: chunk.event,\n id: chunk.id,\n retry: chunk.retry,\n });\n }\n}\n\nexport class JsonServerSentEventTransformStream<DATA> extends TransformStream<\n ServerSentEvent,\n JsonServerSentEvent<DATA>\n> {\n constructor() {\n super(new JsonServerSentEventTransform());\n }\n}\n\nexport type JsonServerSentEventStream<DATA> = ReadableStream<\n JsonServerSentEvent<DATA>\n>;\n\nexport function toJsonServerSentEventStream<DATA>(\n serverSentEventStream: ServerSentEventStream,\n): JsonServerSentEventStream<DATA> {\n return serverSentEventStream.pipeThrough(\n new JsonServerSentEventTransformStream<DATA>(),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { toServerSentEventStream } from './eventStreamConverter';\nimport {\n ContentTypeHeader,\n ContentTypeValues,\n FetchExchange,\n ResponseInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { toJsonServerSentEventStream } from './jsonServerSentEventTransformStream';\n\n/**\n * The name of the EventStreamInterceptor.\n */\nexport const EVENT_STREAM_INTERCEPTOR_NAME = 'EventStreamInterceptor';\n\n/**\n * The order of the EventStreamInterceptor.\n * Set to Number.MAX_SAFE_INTEGER - 1000 to ensure it runs latest among response interceptors.\n */\nexport const EVENT_STREAM_INTERCEPTOR_ORDER = Number.MAX_SAFE_INTEGER - 1000;\n\n/**\n * Interceptor that enhances Response objects with event stream capabilities.\n *\n * This interceptor detects responses with `text/event-stream` content type and adds\n * an `eventStream()` method to the Response object, which returns a readable stream\n * of Server-Sent Events that can be consumed using `for await` syntax.\n *\n * @remarks\n * This interceptor runs at the very end of the response interceptor chain to ensure\n * it runs after all standard response processing is complete, as it adds\n * specialized functionality to the response object. The order is set to\n * EVENT_STREAM_INTERCEPTOR_ORDER to ensure it executes latest among response interceptors,\n * allowing for other response interceptors to run before it if needed. This positioning\n * ensures that all response processing is completed before specialized event stream\n * functionality is added to the response object.\n *\n * @example\n * ```typescript\n * // Using the eventStream method\n * const response = await fetcher.get('/events');\n * if (response.headers.get('content-type')?.includes('text/event-stream')) {\n * const eventStream = response.eventStream();\n * for await (const event of eventStream) {\n * console.log('Received event:', event);\n * }\n * }\n * ```\n */\nexport class EventStreamInterceptor implements ResponseInterceptor {\n readonly name = EVENT_STREAM_INTERCEPTOR_NAME;\n readonly order = EVENT_STREAM_INTERCEPTOR_ORDER;\n\n /**\n * Intercepts responses to add event stream capabilities.\n *\n * This method runs at the very end of the response interceptor chain to ensure\n * it runs after all standard response processing is complete. It detects responses\n * with `text/event-stream` content type and adds an `eventStream()` method to\n * the Response object, which returns a readable stream of Server-Sent Events.\n *\n * @param exchange - The exchange containing the response to enhance\n *\n * @remarks\n * This method executes latest among response interceptors to ensure all response\n * processing is completed before specialized event stream functionality is added.\n * It only enhances responses with `text/event-stream` content type, leaving other\n * responses unchanged. The positioning at the end of the response chain ensures\n * that all response transformations and validations are completed before event\n * stream capabilities are added to the response object.\n */\n intercept(exchange: FetchExchange) {\n // Check if the response is an event stream\n const response = exchange.response;\n if (!response) {\n return;\n }\n const contentType = response.headers.get(ContentTypeHeader);\n if (contentType?.includes(ContentTypeValues.TEXT_EVENT_STREAM)) {\n response.eventStream = () => toServerSentEventStream(response);\n response.jsonEventStream = () =>\n toJsonServerSentEventStream(toServerSentEventStream(response));\n }\n }\n}\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","ServerSentEventField","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","toServerSentEventStream","response","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","EVENT_STREAM_INTERCEPTOR_NAME","EVENT_STREAM_INTERCEPTOR_ORDER","EventStreamInterceptor","exchange","ContentTypeHeader","ContentTypeValues"],"mappings":";AAoBO,MAAMA,EAA2D;AAAA,EAAjE,cAAA;AACL,SAAQ,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQjB,UACEC,GACAC,GACA;AACA,QAAI;AACF,WAAK,UAAUD;AACf,YAAME,IAAQ,KAAK,OAAO,MAAM;AAAA,CAAI;AACpC,WAAK,SAASA,EAAM,IAAA,KAAS;AAE7B,iBAAWC,KAAQD;AACjB,QAAAD,EAAW,QAAQE,CAAI;A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ADoBA,EAAS,QAAQ,IAAIU,CAAiB,GACzC,SAASC,EAAkB,iBAAiB,MAC3DX,EAAS,cAAc,MAAMD,EAAwBC,CAAQ,GAC7DA,EAAS,kBAAkB,MACzBI,EAA4BL,EAAwBC,CAAQ,CAAC;AAAA,EAEnE;AACF;"}
1
+ {"version":3,"file":"index.es.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/eventStreamInterceptor.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Transformer that splits text into lines.\n *\n * This transformer accumulates chunks of text and splits them by newline characters,\n * emitting each line as a separate chunk while preserving the remaining buffer\n * for the next chunk.\n */\nexport class TextLineTransformer implements Transformer<string, string> {\n private buffer = '';\n\n /**\n * Transform input string chunk by splitting it into lines.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<string>,\n ) {\n try {\n this.buffer += chunk;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() || '';\n\n for (const line of lines) {\n controller.enqueue(line);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n\n /**\n * Flush remaining buffer when the stream ends.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<string>) {\n try {\n // Only send when buffer is not empty, avoid sending meaningless empty lines\n if (this.buffer) {\n controller.enqueue(this.buffer);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n}\n\n/**\n * A TransformStream that splits text into lines.\n */\nexport class TextLineTransformStream extends TransformStream<string, string> {\n constructor() {\n super(new TextLineTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents a message sent in an event stream.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format}\n */\nexport interface ServerSentEvent {\n /** The event ID to set the EventSource object's last event ID value. */\n id?: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\nexport class ServerSentEventFields {\n static readonly ID = 'id';\n static readonly RETRY = 'retry';\n static readonly EVENT = 'event';\n static readonly DATA = 'data';\n}\n\n/**\n * Process field value\n * @param field Field name\n * @param value Field value\n * @param currentEvent Current event state\n */\nfunction processFieldInternal(\n field: string,\n value: string,\n currentEvent: EventState,\n) {\n switch (field) {\n case ServerSentEventFields.EVENT:\n currentEvent.event = value;\n break;\n case ServerSentEventFields.DATA:\n currentEvent.data.push(value);\n break;\n case ServerSentEventFields.ID:\n currentEvent.id = value;\n break;\n case ServerSentEventFields.RETRY: {\n const retryValue = parseInt(value, 10);\n if (!isNaN(retryValue)) {\n currentEvent.retry = retryValue;\n }\n break;\n }\n default:\n // Ignore unknown fields\n break;\n }\n}\n\ninterface EventState {\n event?: string;\n id?: string;\n retry?: number;\n data: string[];\n}\n\nconst DEFAULT_EVENT_TYPE = 'message';\n\n/**\n * Transformer responsible for converting a string stream into a ServerSentEvent object stream.\n *\n * Implements the Transformer interface for processing data transformation in TransformStream.\n */\nexport class ServerSentEventTransformer\n implements Transformer<string, ServerSentEvent> {\n // Initialize currentEvent with default values in a closure\n private currentEvent: EventState = {\n event: DEFAULT_EVENT_TYPE,\n id: undefined,\n retry: undefined,\n data: [],\n };\n\n /**\n * Transform input string chunk into ServerSentEvent object.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<ServerSentEvent>,\n ) {\n const currentEvent = this.currentEvent;\n try {\n // Skip empty lines (event separator)\n if (chunk.trim() === '') {\n // If there is accumulated event data, send event\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n\n // Reset current event (preserve id and retry for subsequent events)\n currentEvent.event = DEFAULT_EVENT_TYPE;\n // Preserve id and retry for subsequent events (no need to reassign to themselves)\n currentEvent.data = [];\n }\n return;\n }\n\n // Ignore comment lines (starting with colon)\n if (chunk.startsWith(':')) {\n return;\n }\n\n // Parse fields\n const colonIndex = chunk.indexOf(':');\n let field: string;\n let value: string;\n\n if (colonIndex === -1) {\n // No colon, entire line as field name, value is empty\n field = chunk.toLowerCase();\n value = '';\n } else {\n // Extract field name and value\n field = chunk.substring(0, colonIndex).toLowerCase();\n value = chunk.substring(colonIndex + 1);\n\n // If value starts with space, remove leading space\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n }\n\n // Remove trailing newlines from field and value\n field = field.trim();\n value = value.trim();\n\n processFieldInternal(field, value, currentEvent);\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n\n /**\n * Called when the stream ends, used to process remaining data.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<ServerSentEvent>) {\n const currentEvent = this.currentEvent;\n try {\n // Send the last event (if any)\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n }\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n } finally {\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n}\n\n/**\n * A TransformStream that converts a stream of strings into a stream of ServerSentEvent objects.\n */\nexport class ServerSentEventTransformStream extends TransformStream<\n string,\n ServerSentEvent\n> {\n constructor() {\n super(new ServerSentEventTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TextLineTransformStream } from './textLineTransformStream';\nimport {\n ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Converts a Response object to a ServerSentEventStream.\n *\n * Processes the response body through a series of transform streams:\n * 1. TextDecoderStream: Decode Uint8Array data to UTF-8 strings\n * 2. TextLineStream: Split text by lines\n * 3. ServerSentEventStream: Parse line data into server-sent events\n *\n * @param response - The Response object to convert\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws Error if the response body is null\n */\nexport function toServerSentEventStream(\n response: Response,\n): ServerSentEventStream {\n if (!response.body) {\n throw new Error('Response body is null');\n }\n\n return response.body\n .pipeThrough(new TextDecoderStream('utf-8'))\n .pipeThrough(new TextLineTransformStream())\n .pipeThrough(new ServerSentEventTransformStream());\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ServerSentEvent } from './serverSentEventTransformStream';\nimport { ServerSentEventStream } from './eventStreamConverter';\n\nexport interface JsonServerSentEvent<DATA>\n extends Omit<ServerSentEvent, 'data'> {\n data: DATA;\n}\n\nexport class JsonServerSentEventTransform<DATA>\n implements Transformer<ServerSentEvent, JsonServerSentEvent<DATA>> {\n transform(\n chunk: ServerSentEvent,\n controller: TransformStreamDefaultController<JsonServerSentEvent<DATA>>,\n ) {\n const json = JSON.parse(chunk.data) as DATA;\n controller.enqueue({\n data: json,\n event: chunk.event,\n id: chunk.id,\n retry: chunk.retry,\n });\n }\n}\n\nexport class JsonServerSentEventTransformStream<DATA> extends TransformStream<\n ServerSentEvent,\n JsonServerSentEvent<DATA>\n> {\n constructor() {\n super(new JsonServerSentEventTransform());\n }\n}\n\nexport type JsonServerSentEventStream<DATA> = ReadableStream<\n JsonServerSentEvent<DATA>\n>;\n\nexport function toJsonServerSentEventStream<DATA>(\n serverSentEventStream: ServerSentEventStream,\n): JsonServerSentEventStream<DATA> {\n return serverSentEventStream.pipeThrough(\n new JsonServerSentEventTransformStream<DATA>(),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { toServerSentEventStream } from './eventStreamConverter';\nimport {\n CONTENT_TYPE_HEADER,\n ContentTypeValues,\n FetchExchange,\n ResponseInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { toJsonServerSentEventStream } from './jsonServerSentEventTransformStream';\n\n/**\n * The name of the EventStreamInterceptor.\n */\nexport const EVENT_STREAM_INTERCEPTOR_NAME = 'EventStreamInterceptor';\n\n/**\n * The order of the EventStreamInterceptor.\n * Set to Number.MAX_SAFE_INTEGER - 1000 to ensure it runs latest among response interceptors.\n */\nexport const EVENT_STREAM_INTERCEPTOR_ORDER = Number.MAX_SAFE_INTEGER - 1000;\n\n/**\n * Interceptor that enhances Response objects with event stream capabilities.\n *\n * This interceptor detects responses with `text/event-stream` content type and adds\n * an `eventStream()` method to the Response object, which returns a readable stream\n * of Server-Sent Events that can be consumed using `for await` syntax.\n *\n * @remarks\n * This interceptor runs at the very end of the response interceptor chain to ensure\n * it runs after all standard response processing is complete, as it adds\n * specialized functionality to the response object. The order is set to\n * EVENT_STREAM_INTERCEPTOR_ORDER to ensure it executes latest among response interceptors,\n * allowing for other response interceptors to run before it if needed. This positioning\n * ensures that all response processing is completed before specialized event stream\n * functionality is added to the response object.\n *\n * @example\n * ```typescript\n * // Using the eventStream method\n * const response = await fetcher.get('/events');\n * if (response.headers.get('content-type')?.includes('text/event-stream')) {\n * const eventStream = response.eventStream();\n * for await (const event of eventStream) {\n * console.log('Received event:', event);\n * }\n * }\n * ```\n */\nexport class EventStreamInterceptor implements ResponseInterceptor {\n readonly name = EVENT_STREAM_INTERCEPTOR_NAME;\n readonly order = EVENT_STREAM_INTERCEPTOR_ORDER;\n\n /**\n * Intercepts responses to add event stream capabilities.\n *\n * This method runs at the very end of the response interceptor chain to ensure\n * it runs after all standard response processing is complete. It detects responses\n * with `text/event-stream` content type and adds an `eventStream()` method to\n * the Response object, which returns a readable stream of Server-Sent Events.\n *\n * @param exchange - The exchange containing the response to enhance\n *\n * @remarks\n * This method executes latest among response interceptors to ensure all response\n * processing is completed before specialized event stream functionality is added.\n * It only enhances responses with `text/event-stream` content type, leaving other\n * responses unchanged. The positioning at the end of the response chain ensures\n * that all response transformations and validations are completed before event\n * stream capabilities are added to the response object.\n */\n intercept(exchange: FetchExchange) {\n // Check if the response is an event stream\n const response = exchange.response;\n if (!response) {\n return;\n }\n const contentType = response.headers.get(CONTENT_TYPE_HEADER);\n if (contentType?.includes(ContentTypeValues.TEXT_EVENT_STREAM)) {\n response.eventStream = () => toServerSentEventStream(response);\n response.jsonEventStream = () =>\n toJsonServerSentEventStream(toServerSentEventStream(response));\n }\n }\n}\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","_ServerSentEventFields","ServerSentEventFields","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","toServerSentEventStream","response","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","EVENT_STREAM_INTERCEPTOR_NAME","EVENT_STREAM_INTERCEPTOR_ORDER","EventStreamInterceptor","exchange","CONTENT_TYPE_HEADER","ContentTypeValues"],"mappings":";AAoBO,MAAMA,EAA2D;AAAA,EAAjE,cAAA;AACL,SAAQ,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQjB,UACEC,GACAC,GACA;AACA,QAAI;AACF,WAAK,UAAUD;AACf,YAAME,IAAQ,KAAK,OAAO,MAAM;AAAA,CAAI;AACpC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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoBjB,UAAUE,GAAyB;AAEjC,UAAMT,IAAWS,EAAS;AAC1B,QAAI,CAACT;AACH;AAGF,IADoBA,EAAS,QAAQ,IAAIU,CAAmB,GAC3C,SAASC,EAAkB,iBAAiB,MAC3DX,EAAS,cAAc,MAAMD,EAAwBC,CAAQ,GAC7DA,EAAS,kBAAkB,MACzBI,EAA4BL,EAAwBC,CAAQ,CAAC;AAAA,EAEnE;AACF;"}
package/dist/index.umd.js CHANGED
@@ -1,5 +1,5 @@
1
- (function(s,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher"],i):(s=typeof globalThis<"u"?globalThis:s||self,i(s.FetcherEventStream={},s.Fetcher))})(this,(function(s,i){"use strict";class d{constructor(){this.buffer=""}transform(t,e){try{this.buffer+=t;const r=this.buffer.split(`
2
- `);this.buffer=r.pop()||"";for(const a of r)e.enqueue(a)}catch(r){e.error(r)}}flush(t){try{this.buffer&&t.enqueue(this.buffer)}catch(e){t.error(e)}}}class c extends TransformStream{constructor(){super(new d)}}var u=(n=>(n.ID="id",n.RETRY="retry",n.EVENT="event",n.DATA="data",n))(u||{});function b(n,t,e){switch(n){case"event":e.event=t;break;case"data":e.data.push(t);break;case"id":e.id=t;break;case"retry":{const r=parseInt(t,10);isNaN(r)||(e.retry=r);break}}}const f="message";class S{constructor(){this.currentEvent={event:f,id:void 0,retry:void 0,data:[]}}transform(t,e){const r=this.currentEvent;try{if(t.trim()===""){r.data.length>0&&(e.enqueue({event:r.event||f,data:r.data.join(`
3
- `),id:r.id||"",retry:r.retry}),r.event=f,r.data=[]);return}if(t.startsWith(":"))return;const a=t.indexOf(":");let E,o;a===-1?(E=t.toLowerCase(),o=""):(E=t.substring(0,a).toLowerCase(),o=t.substring(a+1),o.startsWith(" ")&&(o=o.substring(1))),E=E.trim(),o=o.trim(),b(E,o,r)}catch(a){e.error(a instanceof Error?a:new Error(String(a))),r.event=f,r.id=void 0,r.retry=void 0,r.data=[]}}flush(t){const e=this.currentEvent;try{e.data.length>0&&t.enqueue({event:e.event||f,data:e.data.join(`
4
- `),id:e.id||"",retry:e.retry})}catch(r){t.error(r instanceof Error?r:new Error(String(r)))}finally{e.event=f,e.id=void 0,e.retry=void 0,e.data=[]}}}class m extends TransformStream{constructor(){super(new S)}}function T(n){if(!n.body)throw new Error("Response body is null");return n.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new c).pipeThrough(new m)}class v{transform(t,e){const r=JSON.parse(t.data);e.enqueue({data:r,event:t.event,id:t.id,retry:t.retry})}}class h extends TransformStream{constructor(){super(new v)}}function y(n){return n.pipeThrough(new h)}const p="EventStreamInterceptor",R=Number.MAX_SAFE_INTEGER-1e3;class l{constructor(){this.name=p,this.order=R}intercept(t){const e=t.response;if(!e)return;e.headers.get(i.ContentTypeHeader)?.includes(i.ContentTypeValues.TEXT_EVENT_STREAM)&&(e.eventStream=()=>T(e),e.jsonEventStream=()=>y(T(e)))}}s.EVENT_STREAM_INTERCEPTOR_NAME=p,s.EVENT_STREAM_INTERCEPTOR_ORDER=R,s.EventStreamInterceptor=l,s.JsonServerSentEventTransform=v,s.JsonServerSentEventTransformStream=h,s.ServerSentEventField=u,s.ServerSentEventTransformStream=m,s.ServerSentEventTransformer=S,s.TextLineTransformStream=c,s.TextLineTransformer=d,s.toJsonServerSentEventStream=y,s.toServerSentEventStream=T,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(n,f){typeof exports=="object"&&typeof module<"u"?f(exports,require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher"],f):(n=typeof globalThis<"u"?globalThis:n||self,f(n.FetcherEventStream={},n.Fetcher))})(this,(function(n,f){"use strict";class u{constructor(){this.buffer=""}transform(r,e){try{this.buffer+=r;const t=this.buffer.split(`
2
+ `);this.buffer=t.pop()||"";for(const a of t)e.enqueue(a)}catch(t){e.error(t)}}flush(r){try{this.buffer&&r.enqueue(this.buffer)}catch(e){r.error(e)}}}class m extends TransformStream{constructor(){super(new u)}}const T=class T{};T.ID="id",T.RETRY="retry",T.EVENT="event",T.DATA="data";let i=T;function b(s,r,e){switch(s){case i.EVENT:e.event=r;break;case i.DATA:e.data.push(r);break;case i.ID:e.id=r;break;case i.RETRY:{const t=parseInt(r,10);isNaN(t)||(e.retry=t);break}}}const E="message";class S{constructor(){this.currentEvent={event:E,id:void 0,retry:void 0,data:[]}}transform(r,e){const t=this.currentEvent;try{if(r.trim()===""){t.data.length>0&&(e.enqueue({event:t.event||E,data:t.data.join(`
3
+ `),id:t.id||"",retry:t.retry}),t.event=E,t.data=[]);return}if(r.startsWith(":"))return;const a=r.indexOf(":");let c,o;a===-1?(c=r.toLowerCase(),o=""):(c=r.substring(0,a).toLowerCase(),o=r.substring(a+1),o.startsWith(" ")&&(o=o.substring(1))),c=c.trim(),o=o.trim(),b(c,o,t)}catch(a){e.error(a instanceof Error?a:new Error(String(a))),t.event=E,t.id=void 0,t.retry=void 0,t.data=[]}}flush(r){const e=this.currentEvent;try{e.data.length>0&&r.enqueue({event:e.event||E,data:e.data.join(`
4
+ `),id:e.id||"",retry:e.retry})}catch(t){r.error(t instanceof Error?t:new Error(String(t)))}finally{e.event=E,e.id=void 0,e.retry=void 0,e.data=[]}}}class v extends TransformStream{constructor(){super(new S)}}function d(s){if(!s.body)throw new Error("Response body is null");return s.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new m).pipeThrough(new v)}class h{transform(r,e){const t=JSON.parse(r.data);e.enqueue({data:t,event:r.event,id:r.id,retry:r.retry})}}class y extends TransformStream{constructor(){super(new h)}}function R(s){return s.pipeThrough(new y)}const p="EventStreamInterceptor",N=Number.MAX_SAFE_INTEGER-1e3;class l{constructor(){this.name=p,this.order=N}intercept(r){const e=r.response;if(!e)return;e.headers.get(f.CONTENT_TYPE_HEADER)?.includes(f.ContentTypeValues.TEXT_EVENT_STREAM)&&(e.eventStream=()=>d(e),e.jsonEventStream=()=>R(d(e)))}}n.EVENT_STREAM_INTERCEPTOR_NAME=p,n.EVENT_STREAM_INTERCEPTOR_ORDER=N,n.EventStreamInterceptor=l,n.JsonServerSentEventTransform=h,n.JsonServerSentEventTransformStream=y,n.ServerSentEventFields=i,n.ServerSentEventTransformStream=v,n.ServerSentEventTransformer=S,n.TextLineTransformStream=m,n.TextLineTransformer=u,n.toJsonServerSentEventStream=R,n.toServerSentEventStream=d,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})}));
5
5
  //# sourceMappingURL=index.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/eventStreamInterceptor.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Transformer that splits text into lines.\n *\n * This transformer accumulates chunks of text and splits them by newline characters,\n * emitting each line as a separate chunk while preserving the remaining buffer\n * for the next chunk.\n */\nexport class TextLineTransformer implements Transformer<string, string> {\n private buffer = '';\n\n /**\n * Transform input string chunk by splitting it into lines.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<string>,\n ) {\n try {\n this.buffer += chunk;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() || '';\n\n for (const line of lines) {\n controller.enqueue(line);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n\n /**\n * Flush remaining buffer when the stream ends.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<string>) {\n try {\n // Only send when buffer is not empty, avoid sending meaningless empty lines\n if (this.buffer) {\n controller.enqueue(this.buffer);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n}\n\n/**\n * A TransformStream that splits text into lines.\n */\nexport class TextLineTransformStream extends TransformStream<string, string> {\n constructor() {\n super(new TextLineTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents a message sent in an event stream.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format}\n */\nexport interface ServerSentEvent {\n /** The event ID to set the EventSource object's last event ID value. */\n id?: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\nexport enum ServerSentEventField {\n ID = 'id',\n RETRY = 'retry',\n EVENT = 'event',\n DATA = 'data',\n}\n\n/**\n * Process field value\n * @param field Field name\n * @param value Field value\n * @param currentEvent Current event state\n */\nfunction processFieldInternal(\n field: string,\n value: string,\n currentEvent: EventState,\n) {\n switch (field) {\n case ServerSentEventField.EVENT:\n currentEvent.event = value;\n break;\n case ServerSentEventField.DATA:\n currentEvent.data.push(value);\n break;\n case ServerSentEventField.ID:\n currentEvent.id = value;\n break;\n case ServerSentEventField.RETRY: {\n const retryValue = parseInt(value, 10);\n if (!isNaN(retryValue)) {\n currentEvent.retry = retryValue;\n }\n break;\n }\n default:\n // Ignore unknown fields\n break;\n }\n}\n\ninterface EventState {\n event?: string;\n id?: string;\n retry?: number;\n data: string[];\n}\n\nconst DEFAULT_EVENT_TYPE = 'message';\n\n/**\n * Transformer responsible for converting a string stream into a ServerSentEvent object stream.\n *\n * Implements the Transformer interface for processing data transformation in TransformStream.\n */\nexport class ServerSentEventTransformer\n implements Transformer<string, ServerSentEvent>\n{\n // Initialize currentEvent with default values in a closure\n private currentEvent: EventState = {\n event: DEFAULT_EVENT_TYPE,\n id: undefined,\n retry: undefined,\n data: [],\n };\n\n /**\n * Transform input string chunk into ServerSentEvent object.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<ServerSentEvent>,\n ) {\n const currentEvent = this.currentEvent;\n try {\n // Skip empty lines (event separator)\n if (chunk.trim() === '') {\n // If there is accumulated event data, send event\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n\n // Reset current event (preserve id and retry for subsequent events)\n currentEvent.event = DEFAULT_EVENT_TYPE;\n // Preserve id and retry for subsequent events (no need to reassign to themselves)\n currentEvent.data = [];\n }\n return;\n }\n\n // Ignore comment lines (starting with colon)\n if (chunk.startsWith(':')) {\n return;\n }\n\n // Parse fields\n const colonIndex = chunk.indexOf(':');\n let field: string;\n let value: string;\n\n if (colonIndex === -1) {\n // No colon, entire line as field name, value is empty\n field = chunk.toLowerCase();\n value = '';\n } else {\n // Extract field name and value\n field = chunk.substring(0, colonIndex).toLowerCase();\n value = chunk.substring(colonIndex + 1);\n\n // If value starts with space, remove leading space\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n }\n\n // Remove trailing newlines from field and value\n field = field.trim();\n value = value.trim();\n\n processFieldInternal(field, value, currentEvent);\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n\n /**\n * Called when the stream ends, used to process remaining data.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<ServerSentEvent>) {\n const currentEvent = this.currentEvent;\n try {\n // Send the last event (if any)\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n }\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n } finally {\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n}\n\n/**\n * A TransformStream that converts a stream of strings into a stream of ServerSentEvent objects.\n */\nexport class ServerSentEventTransformStream extends TransformStream<\n string,\n ServerSentEvent\n> {\n constructor() {\n super(new ServerSentEventTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TextLineTransformStream } from './textLineTransformStream';\nimport {\n ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Converts a Response object to a ServerSentEventStream.\n *\n * Processes the response body through a series of transform streams:\n * 1. TextDecoderStream: Decode Uint8Array data to UTF-8 strings\n * 2. TextLineStream: Split text by lines\n * 3. ServerSentEventStream: Parse line data into server-sent events\n *\n * @param response - The Response object to convert\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws Error if the response body is null\n */\nexport function toServerSentEventStream(\n response: Response,\n): ServerSentEventStream {\n if (!response.body) {\n throw new Error('Response body is null');\n }\n\n return response.body\n .pipeThrough(new TextDecoderStream('utf-8'))\n .pipeThrough(new TextLineTransformStream())\n .pipeThrough(new ServerSentEventTransformStream());\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ServerSentEvent } from './serverSentEventTransformStream';\nimport { ServerSentEventStream } from './eventStreamConverter';\n\nexport interface JsonServerSentEvent<DATA>\n extends Omit<ServerSentEvent, 'data'> {\n data: DATA;\n}\n\nexport class JsonServerSentEventTransform<DATA>\n implements Transformer<ServerSentEvent, JsonServerSentEvent<DATA>> {\n transform(\n chunk: ServerSentEvent,\n controller: TransformStreamDefaultController<JsonServerSentEvent<DATA>>,\n ) {\n const json = JSON.parse(chunk.data) as DATA;\n controller.enqueue({\n data: json,\n event: chunk.event,\n id: chunk.id,\n retry: chunk.retry,\n });\n }\n}\n\nexport class JsonServerSentEventTransformStream<DATA> extends TransformStream<\n ServerSentEvent,\n JsonServerSentEvent<DATA>\n> {\n constructor() {\n super(new JsonServerSentEventTransform());\n }\n}\n\nexport type JsonServerSentEventStream<DATA> = ReadableStream<\n JsonServerSentEvent<DATA>\n>;\n\nexport function toJsonServerSentEventStream<DATA>(\n serverSentEventStream: ServerSentEventStream,\n): JsonServerSentEventStream<DATA> {\n return serverSentEventStream.pipeThrough(\n new JsonServerSentEventTransformStream<DATA>(),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { toServerSentEventStream } from './eventStreamConverter';\nimport {\n ContentTypeHeader,\n ContentTypeValues,\n FetchExchange,\n ResponseInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { toJsonServerSentEventStream } from './jsonServerSentEventTransformStream';\n\n/**\n * The name of the EventStreamInterceptor.\n */\nexport const EVENT_STREAM_INTERCEPTOR_NAME = 'EventStreamInterceptor';\n\n/**\n * The order of the EventStreamInterceptor.\n * Set to Number.MAX_SAFE_INTEGER - 1000 to ensure it runs latest among response interceptors.\n */\nexport const EVENT_STREAM_INTERCEPTOR_ORDER = Number.MAX_SAFE_INTEGER - 1000;\n\n/**\n * Interceptor that enhances Response objects with event stream capabilities.\n *\n * This interceptor detects responses with `text/event-stream` content type and adds\n * an `eventStream()` method to the Response object, which returns a readable stream\n * of Server-Sent Events that can be consumed using `for await` syntax.\n *\n * @remarks\n * This interceptor runs at the very end of the response interceptor chain to ensure\n * it runs after all standard response processing is complete, as it adds\n * specialized functionality to the response object. The order is set to\n * EVENT_STREAM_INTERCEPTOR_ORDER to ensure it executes latest among response interceptors,\n * allowing for other response interceptors to run before it if needed. This positioning\n * ensures that all response processing is completed before specialized event stream\n * functionality is added to the response object.\n *\n * @example\n * ```typescript\n * // Using the eventStream method\n * const response = await fetcher.get('/events');\n * if (response.headers.get('content-type')?.includes('text/event-stream')) {\n * const eventStream = response.eventStream();\n * for await (const event of eventStream) {\n * console.log('Received event:', event);\n * }\n * }\n * ```\n */\nexport class EventStreamInterceptor implements ResponseInterceptor {\n readonly name = EVENT_STREAM_INTERCEPTOR_NAME;\n readonly order = EVENT_STREAM_INTERCEPTOR_ORDER;\n\n /**\n * Intercepts responses to add event stream capabilities.\n *\n * This method runs at the very end of the response interceptor chain to ensure\n * it runs after all standard response processing is complete. It detects responses\n * with `text/event-stream` content type and adds an `eventStream()` method to\n * the Response object, which returns a readable stream of Server-Sent Events.\n *\n * @param exchange - The exchange containing the response to enhance\n *\n * @remarks\n * This method executes latest among response interceptors to ensure all response\n * processing is completed before specialized event stream functionality is added.\n * It only enhances responses with `text/event-stream` content type, leaving other\n * responses unchanged. The positioning at the end of the response chain ensures\n * that all response transformations and validations are completed before event\n * stream capabilities are added to the response object.\n */\n intercept(exchange: FetchExchange) {\n // Check if the response is an event stream\n const response = exchange.response;\n if (!response) {\n return;\n }\n const contentType = response.headers.get(ContentTypeHeader);\n if (contentType?.includes(ContentTypeValues.TEXT_EVENT_STREAM)) {\n response.eventStream = () => toServerSentEventStream(response);\n response.jsonEventStream = () =>\n toJsonServerSentEventStream(toServerSentEventStream(response));\n }\n }\n}\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","ServerSentEventField","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","toServerSentEventStream","response","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","EVENT_STREAM_INTERCEPTOR_NAME","EVENT_STREAM_INTERCEPTOR_ORDER","EventStreamInterceptor","exchange","ContentTypeHeader","ContentTypeValues"],"mappings":"0SAoBO,MAAMA,CAA2D,CAAjE,aAAA,CACL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C7KO,SAASG,EACdC,EACuB,CACvB,GAAI,CAACA,EAAS,KACZ,MAAM,IAAI,MAAM,uBAAuB,EAGzC,OAAOA,EAAS,KACb,YAAY,IAAI,kBAAkB,OAAO,CAAC,EAC1C,YAAY,IAAIZ,CAAyB,EACzC,YAAY,IAAIU,CAAgC,CACrD,CC1BO,MAAMG,CACwD,CACnE,UACElB,EACAC,EACA,CACA,MAAMkB,EAAO,KAAK,MAAMnB,EAAM,IAAI,EAClCC,EAAW,QAAQ,CACjB,KAAMkB,EACN,MAAOnB,EAAM,MACb,GAAIA,EAAM,GACV,MAAOA,EAAM,KAAA,CACd,CACH,CACF,CAEO,MAAMoB,UAAiD,eAG5D,CACA,aAAc,CACZ,MAAM,IAAIF,CAA8B,CAC1C,CACF,CAMO,SAASG,EACdC,EACiC,CACjC,OAAOA,EAAsB,YAC3B,IAAIF,CAAyC,CAEjD,CC/BO,MAAMG,EAAgC,yBAMhCC,EAAiC,OAAO,iBAAmB,IA8BjE,MAAMC,CAAsD,CAA5D,aAAA,CACL,KAAS,KAAOF,EAChB,KAAS,MAAQC,CAAA,CAoBjB,UAAUE,EAAyB,CAEjC,MAAMT,EAAWS,EAAS,SAC1B,GAAI,CAACT,EACH,OAEkBA,EAAS,QAAQ,IAAIU,EAAAA,iBAAiB,GACzC,SAASC,EAAAA,kBAAkB,iBAAiB,IAC3DX,EAAS,YAAc,IAAMD,EAAwBC,CAAQ,EAC7DA,EAAS,gBAAkB,IACzBI,EAA4BL,EAAwBC,CAAQ,CAAC,EAEnE,CACF"}
1
+ {"version":3,"file":"index.umd.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/eventStreamInterceptor.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Transformer that splits text into lines.\n *\n * This transformer accumulates chunks of text and splits them by newline characters,\n * emitting each line as a separate chunk while preserving the remaining buffer\n * for the next chunk.\n */\nexport class TextLineTransformer implements Transformer<string, string> {\n private buffer = '';\n\n /**\n * Transform input string chunk by splitting it into lines.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<string>,\n ) {\n try {\n this.buffer += chunk;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() || '';\n\n for (const line of lines) {\n controller.enqueue(line);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n\n /**\n * Flush remaining buffer when the stream ends.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<string>) {\n try {\n // Only send when buffer is not empty, avoid sending meaningless empty lines\n if (this.buffer) {\n controller.enqueue(this.buffer);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n}\n\n/**\n * A TransformStream that splits text into lines.\n */\nexport class TextLineTransformStream extends TransformStream<string, string> {\n constructor() {\n super(new TextLineTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents a message sent in an event stream.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format}\n */\nexport interface ServerSentEvent {\n /** The event ID to set the EventSource object's last event ID value. */\n id?: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\nexport class ServerSentEventFields {\n static readonly ID = 'id';\n static readonly RETRY = 'retry';\n static readonly EVENT = 'event';\n static readonly DATA = 'data';\n}\n\n/**\n * Process field value\n * @param field Field name\n * @param value Field value\n * @param currentEvent Current event state\n */\nfunction processFieldInternal(\n field: string,\n value: string,\n currentEvent: EventState,\n) {\n switch (field) {\n case ServerSentEventFields.EVENT:\n currentEvent.event = value;\n break;\n case ServerSentEventFields.DATA:\n currentEvent.data.push(value);\n break;\n case ServerSentEventFields.ID:\n currentEvent.id = value;\n break;\n case ServerSentEventFields.RETRY: {\n const retryValue = parseInt(value, 10);\n if (!isNaN(retryValue)) {\n currentEvent.retry = retryValue;\n }\n break;\n }\n default:\n // Ignore unknown fields\n break;\n }\n}\n\ninterface EventState {\n event?: string;\n id?: string;\n retry?: number;\n data: string[];\n}\n\nconst DEFAULT_EVENT_TYPE = 'message';\n\n/**\n * Transformer responsible for converting a string stream into a ServerSentEvent object stream.\n *\n * Implements the Transformer interface for processing data transformation in TransformStream.\n */\nexport class ServerSentEventTransformer\n implements Transformer<string, ServerSentEvent> {\n // Initialize currentEvent with default values in a closure\n private currentEvent: EventState = {\n event: DEFAULT_EVENT_TYPE,\n id: undefined,\n retry: undefined,\n data: [],\n };\n\n /**\n * Transform input string chunk into ServerSentEvent object.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<ServerSentEvent>,\n ) {\n const currentEvent = this.currentEvent;\n try {\n // Skip empty lines (event separator)\n if (chunk.trim() === '') {\n // If there is accumulated event data, send event\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n\n // Reset current event (preserve id and retry for subsequent events)\n currentEvent.event = DEFAULT_EVENT_TYPE;\n // Preserve id and retry for subsequent events (no need to reassign to themselves)\n currentEvent.data = [];\n }\n return;\n }\n\n // Ignore comment lines (starting with colon)\n if (chunk.startsWith(':')) {\n return;\n }\n\n // Parse fields\n const colonIndex = chunk.indexOf(':');\n let field: string;\n let value: string;\n\n if (colonIndex === -1) {\n // No colon, entire line as field name, value is empty\n field = chunk.toLowerCase();\n value = '';\n } else {\n // Extract field name and value\n field = chunk.substring(0, colonIndex).toLowerCase();\n value = chunk.substring(colonIndex + 1);\n\n // If value starts with space, remove leading space\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n }\n\n // Remove trailing newlines from field and value\n field = field.trim();\n value = value.trim();\n\n processFieldInternal(field, value, currentEvent);\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n\n /**\n * Called when the stream ends, used to process remaining data.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<ServerSentEvent>) {\n const currentEvent = this.currentEvent;\n try {\n // Send the last event (if any)\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n }\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n } finally {\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n}\n\n/**\n * A TransformStream that converts a stream of strings into a stream of ServerSentEvent objects.\n */\nexport class ServerSentEventTransformStream extends TransformStream<\n string,\n ServerSentEvent\n> {\n constructor() {\n super(new ServerSentEventTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TextLineTransformStream } from './textLineTransformStream';\nimport {\n ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Converts a Response object to a ServerSentEventStream.\n *\n * Processes the response body through a series of transform streams:\n * 1. TextDecoderStream: Decode Uint8Array data to UTF-8 strings\n * 2. TextLineStream: Split text by lines\n * 3. ServerSentEventStream: Parse line data into server-sent events\n *\n * @param response - The Response object to convert\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws Error if the response body is null\n */\nexport function toServerSentEventStream(\n response: Response,\n): ServerSentEventStream {\n if (!response.body) {\n throw new Error('Response body is null');\n }\n\n return response.body\n .pipeThrough(new TextDecoderStream('utf-8'))\n .pipeThrough(new TextLineTransformStream())\n .pipeThrough(new ServerSentEventTransformStream());\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ServerSentEvent } from './serverSentEventTransformStream';\nimport { ServerSentEventStream } from './eventStreamConverter';\n\nexport interface JsonServerSentEvent<DATA>\n extends Omit<ServerSentEvent, 'data'> {\n data: DATA;\n}\n\nexport class JsonServerSentEventTransform<DATA>\n implements Transformer<ServerSentEvent, JsonServerSentEvent<DATA>> {\n transform(\n chunk: ServerSentEvent,\n controller: TransformStreamDefaultController<JsonServerSentEvent<DATA>>,\n ) {\n const json = JSON.parse(chunk.data) as DATA;\n controller.enqueue({\n data: json,\n event: chunk.event,\n id: chunk.id,\n retry: chunk.retry,\n });\n }\n}\n\nexport class JsonServerSentEventTransformStream<DATA> extends TransformStream<\n ServerSentEvent,\n JsonServerSentEvent<DATA>\n> {\n constructor() {\n super(new JsonServerSentEventTransform());\n }\n}\n\nexport type JsonServerSentEventStream<DATA> = ReadableStream<\n JsonServerSentEvent<DATA>\n>;\n\nexport function toJsonServerSentEventStream<DATA>(\n serverSentEventStream: ServerSentEventStream,\n): JsonServerSentEventStream<DATA> {\n return serverSentEventStream.pipeThrough(\n new JsonServerSentEventTransformStream<DATA>(),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { toServerSentEventStream } from './eventStreamConverter';\nimport {\n CONTENT_TYPE_HEADER,\n ContentTypeValues,\n FetchExchange,\n ResponseInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { toJsonServerSentEventStream } from './jsonServerSentEventTransformStream';\n\n/**\n * The name of the EventStreamInterceptor.\n */\nexport const EVENT_STREAM_INTERCEPTOR_NAME = 'EventStreamInterceptor';\n\n/**\n * The order of the EventStreamInterceptor.\n * Set to Number.MAX_SAFE_INTEGER - 1000 to ensure it runs latest among response interceptors.\n */\nexport const EVENT_STREAM_INTERCEPTOR_ORDER = Number.MAX_SAFE_INTEGER - 1000;\n\n/**\n * Interceptor that enhances Response objects with event stream capabilities.\n *\n * This interceptor detects responses with `text/event-stream` content type and adds\n * an `eventStream()` method to the Response object, which returns a readable stream\n * of Server-Sent Events that can be consumed using `for await` syntax.\n *\n * @remarks\n * This interceptor runs at the very end of the response interceptor chain to ensure\n * it runs after all standard response processing is complete, as it adds\n * specialized functionality to the response object. The order is set to\n * EVENT_STREAM_INTERCEPTOR_ORDER to ensure it executes latest among response interceptors,\n * allowing for other response interceptors to run before it if needed. This positioning\n * ensures that all response processing is completed before specialized event stream\n * functionality is added to the response object.\n *\n * @example\n * ```typescript\n * // Using the eventStream method\n * const response = await fetcher.get('/events');\n * if (response.headers.get('content-type')?.includes('text/event-stream')) {\n * const eventStream = response.eventStream();\n * for await (const event of eventStream) {\n * console.log('Received event:', event);\n * }\n * }\n * ```\n */\nexport class EventStreamInterceptor implements ResponseInterceptor {\n readonly name = EVENT_STREAM_INTERCEPTOR_NAME;\n readonly order = EVENT_STREAM_INTERCEPTOR_ORDER;\n\n /**\n * Intercepts responses to add event stream capabilities.\n *\n * This method runs at the very end of the response interceptor chain to ensure\n * it runs after all standard response processing is complete. It detects responses\n * with `text/event-stream` content type and adds an `eventStream()` method to\n * the Response object, which returns a readable stream of Server-Sent Events.\n *\n * @param exchange - The exchange containing the response to enhance\n *\n * @remarks\n * This method executes latest among response interceptors to ensure all response\n * processing is completed before specialized event stream functionality is added.\n * It only enhances responses with `text/event-stream` content type, leaving other\n * responses unchanged. The positioning at the end of the response chain ensures\n * that all response transformations and validations are completed before event\n * stream capabilities are added to the response object.\n */\n intercept(exchange: FetchExchange) {\n // Check if the response is an event stream\n const response = exchange.response;\n if (!response) {\n return;\n }\n const contentType = response.headers.get(CONTENT_TYPE_HEADER);\n if (contentType?.includes(ContentTypeValues.TEXT_EVENT_STREAM)) {\n response.eventStream = () => toServerSentEventStream(response);\n response.jsonEventStream = () =>\n toJsonServerSentEventStream(toServerSentEventStream(response));\n }\n }\n}\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","_ServerSentEventFields","ServerSentEventFields","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","toServerSentEventStream","response","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","EVENT_STREAM_INTERCEPTOR_NAME","EVENT_STREAM_INTERCEPTOR_ORDER","EventStreamInterceptor","exchange","CONTENT_TYPE_HEADER","ContentTypeValues"],"mappings":"0SAoBO,MAAMA,CAA2D,CAAjE,aAAA,CACL,KAAQ,OAAS,EAAA,CAQjB,UACEC,EACAC,EACA,CACA,GAAI,CACF,KAAK,QAAUD,EACf,MAAME,EAAQ,KAAK,OAAO,MAAM;AAAA,CAAI,EACpC,KAAK,OAASA,EAAM,IAAA,GAAS,GAE7B,UAAWC,KAAQD,EACjBD,EAAW,QAAQE,CAAI,CAE3B,OAASC,EAAO,CACdH,EAAW,MAAMG,CAAK,CACxB,CACF,CAOA,MAAMH,EAAsD,CAC1D,GAAI,CAEE,KAAK,QACPA,EAAW,QAAQ,KAAK,MAAM,CAElC,OAASG,EAAO,CACdH,EAAW,MAAMG,CAAK,CACxB,CACF,CACF,CAKO,MAAMC,UAAgC,eAAgC,CAC3E,aAAc,CACZ,MAAM,IAAIN,CAAqB,CACjC,CACF,CCzCO,MAAMO,EAAN,MAAMA,CAAsB,CAKnC,EAJEA,EAAgB,GAAK,KACrBA,EAAgB,MAAQ,QACxBA,EAAgB,MAAQ,QACxBA,EAAgB,KAAO,OAJlB,IAAMC,EAAND,EAaP,SAASE,EACPC,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C,OAAO,iBAAmB,IA8BjE,MAAMC,CAAsD,CAA5D,aAAA,CACL,KAAS,KAAOF,EAChB,KAAS,MAAQC,CAAA,CAoBjB,UAAUE,EAAyB,CAEjC,MAAMT,EAAWS,EAAS,SAC1B,GAAI,CAACT,EACH,OAEkBA,EAAS,QAAQ,IAAIU,EAAAA,mBAAmB,GAC3C,SAASC,EAAAA,kBAAkB,iBAAiB,IAC3DX,EAAS,YAAc,IAAMD,EAAwBC,CAAQ,EAC7DA,EAAS,gBAAkB,IACzBI,EAA4BL,EAAwBC,CAAQ,CAAC,EAEnE,CACF"}
@@ -13,11 +13,11 @@ export interface ServerSentEvent {
13
13
  /** The reconnection interval (in milliseconds) to wait before retrying the connection */
14
14
  retry?: number;
15
15
  }
16
- export declare enum ServerSentEventField {
17
- ID = "id",
18
- RETRY = "retry",
19
- EVENT = "event",
20
- DATA = "data"
16
+ export declare class ServerSentEventFields {
17
+ static readonly ID = "id";
18
+ static readonly RETRY = "retry";
19
+ static readonly EVENT = "event";
20
+ static readonly DATA = "data";
21
21
  }
22
22
  /**
23
23
  * Transformer responsible for converting a string stream into a ServerSentEvent object stream.
@@ -1 +1 @@
1
- {"version":3,"file":"serverSentEventTransformStream.d.ts","sourceRoot":"","sources":["../src/serverSentEventTransformStream.ts"],"names":[],"mappings":"AAaA;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,wEAAwE;IACxE,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,wDAAwD;IACxD,KAAK,EAAE,MAAM,CAAC;IACd,qBAAqB;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,yFAAyF;IACzF,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,oBAAY,oBAAoB;IAC9B,EAAE,OAAO;IACT,KAAK,UAAU;IACf,KAAK,UAAU;IACf,IAAI,SAAS;CACd;AA6CD;;;;GAIG;AACH,qBAAa,0BACX,YAAW,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC;IAG/C,OAAO,CAAC,YAAY,CAKlB;IAEF;;;;;OAKG;IACH,SAAS,CACP,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,gCAAgC,CAAC,eAAe,CAAC;IAiE/D;;;;OAIG;IACH,KAAK,CAAC,UAAU,EAAE,gCAAgC,CAAC,eAAe,CAAC;CAwBpE;AAED;;GAEG;AACH,qBAAa,8BAA+B,SAAQ,eAAe,CACjE,MAAM,EACN,eAAe,CAChB;;CAIA"}
1
+ {"version":3,"file":"serverSentEventTransformStream.d.ts","sourceRoot":"","sources":["../src/serverSentEventTransformStream.ts"],"names":[],"mappings":"AAaA;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,wEAAwE;IACxE,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,wDAAwD;IACxD,KAAK,EAAE,MAAM,CAAC;IACd,qBAAqB;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,yFAAyF;IACzF,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,qBAAa,qBAAqB;IAChC,MAAM,CAAC,QAAQ,CAAC,EAAE,QAAQ;IAC1B,MAAM,CAAC,QAAQ,CAAC,KAAK,WAAW;IAChC,MAAM,CAAC,QAAQ,CAAC,KAAK,WAAW;IAChC,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU;CAC/B;AA6CD;;;;GAIG;AACH,qBAAa,0BACX,YAAW,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC;IAE/C,OAAO,CAAC,YAAY,CAKlB;IAEF;;;;;OAKG;IACH,SAAS,CACP,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,gCAAgC,CAAC,eAAe,CAAC;IAiE/D;;;;OAIG;IACH,KAAK,CAAC,UAAU,EAAE,gCAAgC,CAAC,eAAe,CAAC;CAwBpE;AAED;;GAEG;AACH,qBAAa,8BAA+B,SAAQ,eAAe,CACjE,MAAM,EACN,eAAe,CAChB;;CAIA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ahoo-wang/fetcher-eventstream",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "description": "Server-Sent Events (SSE) support for Fetcher HTTP client with native LLM streaming API support. Enables real-time data streaming and token-by-token LLM response handling.",
5
5
  "keywords": [
6
6
  "fetch",
@@ -39,7 +39,7 @@
39
39
  "dist"
40
40
  ],
41
41
  "dependencies": {
42
- "@ahoo-wang/fetcher": "1.0.6"
42
+ "@ahoo-wang/fetcher": "1.0.8"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@vitest/coverage-v8": "^3.2.4",