@ahoo-wang/fetcher-eventstream 1.3.3 → 1.5.0
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/eventStreamResultExtractor.d.ts +20 -0
- package/dist/eventStreamResultExtractor.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.es.js +87 -84
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +4 -4
- package/dist/index.umd.js.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ResultExtractor } from '@ahoo-wang/fetcher';
|
|
2
|
+
import { ServerSentEventStream } from './eventStreamConverter';
|
|
3
|
+
import { JsonServerSentEventStream } from './jsonServerSentEventTransformStream';
|
|
4
|
+
/**
|
|
5
|
+
* ServerSentEventStream result extractor, used to extract server-sent event stream from FetchExchange
|
|
6
|
+
*
|
|
7
|
+
* @param exchange - FetchExchange object containing request and response information
|
|
8
|
+
* @returns Readable stream object of server-sent event stream
|
|
9
|
+
* @throws ExchangeError exception when server does not support ServerSentEventStream
|
|
10
|
+
*/
|
|
11
|
+
export declare const EventStreamResultExtractor: ResultExtractor<ServerSentEventStream>;
|
|
12
|
+
/**
|
|
13
|
+
* JsonServerSentEventStream result extractor, used to extract JSON server-sent event stream from FetchExchange
|
|
14
|
+
*
|
|
15
|
+
* @param exchange - FetchExchange object containing request and response information
|
|
16
|
+
* @returns Readable stream object of JSON server-sent event stream
|
|
17
|
+
* @throws ExchangeError exception when server does not support JsonServerSentEventStream
|
|
18
|
+
*/
|
|
19
|
+
export declare const JsonEventStreamResultExtractor: ResultExtractor<JsonServerSentEventStream<any>>;
|
|
20
|
+
//# sourceMappingURL=eventStreamResultExtractor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"eventStreamResultExtractor.d.ts","sourceRoot":"","sources":["../src/eventStreamResultExtractor.ts"],"names":[],"mappings":"AAcA,OAAO,EAAiB,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AAEjF;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,EAAE,eAAe,CAAC,qBAAqB,CAI7E,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,8BAA8B,EAAE,eAAe,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAI1F,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export * from './eventStreamConverter';
|
|
2
2
|
export * from './jsonServerSentEventTransformStream';
|
|
3
|
+
export * from './eventStreamResultExtractor';
|
|
3
4
|
export * from './responses';
|
|
4
5
|
export * from './serverSentEventTransformStream';
|
|
5
6
|
export * from './textLineTransformStream';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,wBAAwB,CAAC;AACvC,cAAc,sCAAsC,CAAC;AACrD,cAAc,aAAa,CAAC;AAC5B,cAAc,kCAAkC,CAAC;AACjD,cAAc,2BAA2B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,wBAAwB,CAAC;AACvC,cAAc,sCAAsC,CAAC;AACrD,cAAc,8BAA8B,CAAC;AAC7C,cAAc,aAAa,CAAC;AAC5B,cAAc,kCAAkC,CAAC;AACjD,cAAc,2BAA2B,CAAC"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { FetcherError as p, CONTENT_TYPE_HEADER as d, ContentTypeValues as
|
|
2
|
-
class
|
|
1
|
+
import { FetcherError as p, CONTENT_TYPE_HEADER as d, ContentTypeValues as m } from "@ahoo-wang/fetcher";
|
|
2
|
+
class h {
|
|
3
3
|
constructor() {
|
|
4
4
|
this.buffer = "";
|
|
5
5
|
}
|
|
@@ -9,16 +9,16 @@ class m {
|
|
|
9
9
|
* @param chunk Input string chunk
|
|
10
10
|
* @param controller Controller for controlling the transform stream
|
|
11
11
|
*/
|
|
12
|
-
transform(
|
|
12
|
+
transform(r, n) {
|
|
13
13
|
try {
|
|
14
|
-
this.buffer +=
|
|
15
|
-
const
|
|
14
|
+
this.buffer += r;
|
|
15
|
+
const t = this.buffer.split(`
|
|
16
16
|
`);
|
|
17
|
-
this.buffer =
|
|
18
|
-
for (const s of
|
|
19
|
-
|
|
20
|
-
} catch (
|
|
21
|
-
|
|
17
|
+
this.buffer = t.pop() || "";
|
|
18
|
+
for (const s of t)
|
|
19
|
+
n.enqueue(s);
|
|
20
|
+
} catch (t) {
|
|
21
|
+
n.error(t);
|
|
22
22
|
}
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
@@ -26,43 +26,43 @@ class m {
|
|
|
26
26
|
*
|
|
27
27
|
* @param controller Controller for controlling the transform stream
|
|
28
28
|
*/
|
|
29
|
-
flush(
|
|
29
|
+
flush(r) {
|
|
30
30
|
try {
|
|
31
|
-
this.buffer &&
|
|
32
|
-
} catch (
|
|
33
|
-
|
|
31
|
+
this.buffer && r.enqueue(this.buffer);
|
|
32
|
+
} catch (n) {
|
|
33
|
+
r.error(n);
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
class v extends TransformStream {
|
|
38
38
|
constructor() {
|
|
39
|
-
super(new
|
|
39
|
+
super(new h());
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
42
|
const c = class c {
|
|
43
43
|
};
|
|
44
44
|
c.ID = "id", c.RETRY = "retry", c.EVENT = "event", c.DATA = "data";
|
|
45
45
|
let i = c;
|
|
46
|
-
function
|
|
47
|
-
switch (
|
|
46
|
+
function E(e, r, n) {
|
|
47
|
+
switch (e) {
|
|
48
48
|
case i.EVENT:
|
|
49
|
-
|
|
49
|
+
n.event = r;
|
|
50
50
|
break;
|
|
51
51
|
case i.DATA:
|
|
52
|
-
|
|
52
|
+
n.data.push(r);
|
|
53
53
|
break;
|
|
54
54
|
case i.ID:
|
|
55
|
-
|
|
55
|
+
n.id = r;
|
|
56
56
|
break;
|
|
57
57
|
case i.RETRY: {
|
|
58
|
-
const
|
|
59
|
-
isNaN(
|
|
58
|
+
const t = parseInt(r, 10);
|
|
59
|
+
isNaN(t) || (n.retry = t);
|
|
60
60
|
break;
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
const a = "message";
|
|
65
|
-
class
|
|
65
|
+
class y {
|
|
66
66
|
constructor() {
|
|
67
67
|
this.currentEvent = {
|
|
68
68
|
event: a,
|
|
@@ -77,28 +77,28 @@ class T {
|
|
|
77
77
|
* @param chunk Input string chunk
|
|
78
78
|
* @param controller Controller for controlling the transform stream
|
|
79
79
|
*/
|
|
80
|
-
transform(
|
|
81
|
-
const
|
|
80
|
+
transform(r, n) {
|
|
81
|
+
const t = this.currentEvent;
|
|
82
82
|
try {
|
|
83
|
-
if (
|
|
84
|
-
|
|
85
|
-
event:
|
|
86
|
-
data:
|
|
83
|
+
if (r.trim() === "") {
|
|
84
|
+
t.data.length > 0 && (n.enqueue({
|
|
85
|
+
event: t.event || a,
|
|
86
|
+
data: t.data.join(`
|
|
87
87
|
`),
|
|
88
|
-
id:
|
|
89
|
-
retry:
|
|
90
|
-
}),
|
|
88
|
+
id: t.id || "",
|
|
89
|
+
retry: t.retry
|
|
90
|
+
}), t.event = a, t.data = []);
|
|
91
91
|
return;
|
|
92
92
|
}
|
|
93
|
-
if (
|
|
93
|
+
if (r.startsWith(":"))
|
|
94
94
|
return;
|
|
95
|
-
const s =
|
|
96
|
-
let
|
|
97
|
-
s === -1 ? (
|
|
95
|
+
const s = r.indexOf(":");
|
|
96
|
+
let u, o;
|
|
97
|
+
s === -1 ? (u = r.toLowerCase(), o = "") : (u = r.substring(0, s).toLowerCase(), o = r.substring(s + 1), o.startsWith(" ") && (o = o.substring(1))), u = u.trim(), o = o.trim(), E(u, o, t);
|
|
98
98
|
} catch (s) {
|
|
99
|
-
|
|
99
|
+
n.error(
|
|
100
100
|
s instanceof Error ? s : new Error(String(s))
|
|
101
|
-
),
|
|
101
|
+
), t.event = a, t.id = void 0, t.retry = void 0, t.data = [];
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
104
|
/**
|
|
@@ -106,54 +106,54 @@ class T {
|
|
|
106
106
|
*
|
|
107
107
|
* @param controller Controller for controlling the transform stream
|
|
108
108
|
*/
|
|
109
|
-
flush(
|
|
110
|
-
const
|
|
109
|
+
flush(r) {
|
|
110
|
+
const n = this.currentEvent;
|
|
111
111
|
try {
|
|
112
|
-
|
|
113
|
-
event:
|
|
114
|
-
data:
|
|
112
|
+
n.data.length > 0 && r.enqueue({
|
|
113
|
+
event: n.event || a,
|
|
114
|
+
data: n.data.join(`
|
|
115
115
|
`),
|
|
116
|
-
id:
|
|
117
|
-
retry:
|
|
116
|
+
id: n.id || "",
|
|
117
|
+
retry: n.retry
|
|
118
118
|
});
|
|
119
|
-
} catch (
|
|
120
|
-
|
|
121
|
-
|
|
119
|
+
} catch (t) {
|
|
120
|
+
r.error(
|
|
121
|
+
t instanceof Error ? t : new Error(String(t))
|
|
122
122
|
);
|
|
123
123
|
} finally {
|
|
124
|
-
|
|
124
|
+
n.event = a, n.id = void 0, n.retry = void 0, n.data = [];
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
127
|
}
|
|
128
|
-
class
|
|
128
|
+
class T extends TransformStream {
|
|
129
129
|
constructor() {
|
|
130
|
-
super(new
|
|
130
|
+
super(new y());
|
|
131
131
|
}
|
|
132
132
|
}
|
|
133
|
-
class
|
|
133
|
+
class f extends p {
|
|
134
134
|
/**
|
|
135
135
|
* Creates a new EventStreamConvertError instance.
|
|
136
136
|
* @param response - The Response object associated with the error
|
|
137
137
|
* @param errorMsg - Optional error message describing what went wrong during conversion
|
|
138
138
|
* @param cause - Optional underlying error that caused this error
|
|
139
139
|
*/
|
|
140
|
-
constructor(
|
|
141
|
-
super(
|
|
140
|
+
constructor(r, n, t) {
|
|
141
|
+
super(n, t), this.response = r, this.name = "EventStreamConvertError", Object.setPrototypeOf(this, f.prototype);
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
|
-
function S(
|
|
145
|
-
if (!
|
|
146
|
-
throw new
|
|
147
|
-
return
|
|
144
|
+
function S(e) {
|
|
145
|
+
if (!e.body)
|
|
146
|
+
throw new f(e, "Response body is null");
|
|
147
|
+
return e.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new v()).pipeThrough(new T());
|
|
148
148
|
}
|
|
149
149
|
class l {
|
|
150
|
-
transform(
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
data:
|
|
154
|
-
event:
|
|
155
|
-
id:
|
|
156
|
-
retry:
|
|
150
|
+
transform(r, n) {
|
|
151
|
+
const t = JSON.parse(r.data);
|
|
152
|
+
n.enqueue({
|
|
153
|
+
data: t,
|
|
154
|
+
event: r.event,
|
|
155
|
+
id: r.id,
|
|
156
|
+
retry: r.retry
|
|
157
157
|
});
|
|
158
158
|
}
|
|
159
159
|
}
|
|
@@ -162,11 +162,12 @@ class b extends TransformStream {
|
|
|
162
162
|
super(new l());
|
|
163
163
|
}
|
|
164
164
|
}
|
|
165
|
-
function
|
|
166
|
-
return
|
|
165
|
+
function R(e) {
|
|
166
|
+
return e.pipeThrough(
|
|
167
167
|
new b()
|
|
168
168
|
);
|
|
169
169
|
}
|
|
170
|
+
const g = (e) => e.requiredResponse.requiredEventStream(), x = (e) => e.requiredResponse.requiredJsonEventStream();
|
|
170
171
|
Object.defineProperty(Response.prototype, "contentType", {
|
|
171
172
|
get() {
|
|
172
173
|
return this.headers.get(d);
|
|
@@ -174,45 +175,47 @@ Object.defineProperty(Response.prototype, "contentType", {
|
|
|
174
175
|
});
|
|
175
176
|
Object.defineProperty(Response.prototype, "isEventStream", {
|
|
176
177
|
get() {
|
|
177
|
-
const
|
|
178
|
-
return
|
|
178
|
+
const e = this.contentType;
|
|
179
|
+
return e ? e.includes(m.TEXT_EVENT_STREAM) : !1;
|
|
179
180
|
}
|
|
180
181
|
});
|
|
181
182
|
Response.prototype.eventStream = function() {
|
|
182
183
|
return this.isEventStream ? S(this) : null;
|
|
183
184
|
};
|
|
184
185
|
Response.prototype.requiredEventStream = function() {
|
|
185
|
-
const
|
|
186
|
-
if (!
|
|
187
|
-
throw new
|
|
186
|
+
const e = this.eventStream();
|
|
187
|
+
if (!e)
|
|
188
|
+
throw new f(
|
|
188
189
|
this,
|
|
189
190
|
`Event stream is not available. Response content-type: [${this.contentType}]`
|
|
190
191
|
);
|
|
191
|
-
return
|
|
192
|
+
return e;
|
|
192
193
|
};
|
|
193
194
|
Response.prototype.jsonEventStream = function() {
|
|
194
|
-
const
|
|
195
|
-
return
|
|
195
|
+
const e = this.eventStream();
|
|
196
|
+
return e ? R(e) : null;
|
|
196
197
|
};
|
|
197
198
|
Response.prototype.requiredJsonEventStream = function() {
|
|
198
|
-
const
|
|
199
|
-
if (!
|
|
200
|
-
throw new
|
|
199
|
+
const e = this.jsonEventStream();
|
|
200
|
+
if (!e)
|
|
201
|
+
throw new f(
|
|
201
202
|
this,
|
|
202
203
|
`Event stream is not available. Response content-type: [${this.contentType}]`
|
|
203
204
|
);
|
|
204
|
-
return
|
|
205
|
+
return e;
|
|
205
206
|
};
|
|
206
207
|
export {
|
|
207
|
-
|
|
208
|
+
f as EventStreamConvertError,
|
|
209
|
+
g as EventStreamResultExtractor,
|
|
210
|
+
x as JsonEventStreamResultExtractor,
|
|
208
211
|
l as JsonServerSentEventTransform,
|
|
209
212
|
b as JsonServerSentEventTransformStream,
|
|
210
213
|
i as ServerSentEventFields,
|
|
211
|
-
|
|
212
|
-
|
|
214
|
+
T as ServerSentEventTransformStream,
|
|
215
|
+
y as ServerSentEventTransformer,
|
|
213
216
|
v as TextLineTransformStream,
|
|
214
|
-
|
|
215
|
-
|
|
217
|
+
h as TextLineTransformer,
|
|
218
|
+
R as toJsonServerSentEventStream,
|
|
216
219
|
S as toServerSentEventStream
|
|
217
220
|
};
|
|
218
221
|
//# sourceMappingURL=index.es.js.map
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/responses.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 type ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Custom error class for event stream conversion errors.\n * Thrown when there are issues converting a Response to a ServerSentEventStream.\n */\nexport class EventStreamConvertError extends FetcherError {\n /**\n * Creates a new EventStreamConvertError instance.\n * @param response - The Response object associated with the error\n * @param errorMsg - Optional error message describing what went wrong during conversion\n * @param cause - Optional underlying error that caused this error\n */\n constructor(\n public readonly response: Response,\n errorMsg?: string,\n cause?: Error | any,\n ) {\n super(errorMsg, cause);\n this.name = 'EventStreamConvertError';\n // Restore prototype chain for proper inheritance\n Object.setPrototypeOf(this, EventStreamConvertError.prototype);\n }\n}\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 EventStreamConvertError(response, '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 { type 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 {\n EventStreamConvertError,\n type ServerSentEventStream,\n toServerSentEventStream,\n} from './eventStreamConverter';\nimport {\n type JsonServerSentEventStream,\n toJsonServerSentEventStream,\n} from './jsonServerSentEventTransformStream';\nimport { CONTENT_TYPE_HEADER, ContentTypeValues } from '@ahoo-wang/fetcher';\n\ndeclare global {\n interface Response {\n /**\n * Gets the content type of the response.\n *\n * This property provides access to the Content-Type header of the response,\n * which indicates the media type of the resource transmitted in the response.\n *\n * @returns The content type header value as a string, or null if the header is not set\n */\n get contentType(): string | null;\n\n /**\n * Checks if the response is an event stream.\n *\n * This property examines the Content-Type header to determine if the response\n * contains server-sent events data (text/event-stream).\n *\n * @returns true if the response is an event stream, false otherwise\n */\n get isEventStream(): boolean;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects, or null if not an event stream\n */\n eventStream(): ServerSentEventStream | null;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is similar to eventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws {Error} if the event stream is not available\n */\n requiredEventStream(): ServerSentEventStream;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data, or null if not an event stream\n */\n jsonEventStream<DATA>(): JsonServerSentEventStream<DATA> | null;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is similar to jsonEventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream with JSON data.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data\n * @throws {Error} if the event stream is not available\n */\n requiredJsonEventStream<DATA>(): JsonServerSentEventStream<DATA>;\n }\n\n interface ReadableStream<R = any> {\n /**\n * Makes ReadableStream async iterable for use with for-await loops.\n *\n * This allows the stream to be consumed using `for await (const chunk of stream)` syntax.\n *\n * @returns An async iterator for the stream\n */\n [Symbol.asyncIterator](): AsyncIterator<R>;\n }\n}\n\n/**\n * Defines the contentType property on Response prototype.\n * This property provides a convenient way to access the Content-Type header value.\n */\nObject.defineProperty(Response.prototype, 'contentType', {\n get() {\n return this.headers.get(CONTENT_TYPE_HEADER);\n },\n});\n\n/**\n * Defines the isEventStream property on Response prototype.\n * This property checks if the response has a Content-Type header indicating it's an event stream.\n */\nObject.defineProperty(Response.prototype, 'isEventStream', {\n get() {\n const contentType = this.contentType;\n if (!contentType) {\n return false;\n }\n return contentType.includes(ContentTypeValues.TEXT_EVENT_STREAM);\n },\n});\n\n/**\n * Implementation of the eventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream.\n *\n * @returns A ServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.eventStream = function() {\n if (!this.isEventStream) {\n return null;\n }\n return toServerSentEventStream(this);\n};\n\n/**\n * Implementation of the requiredEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @returns A ServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredEventStream = function() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n\n/**\n * Implementation of the jsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.jsonEventStream = function <DATA>() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n return null;\n }\n return toJsonServerSentEventStream<DATA>(eventStream);\n};\n\n/**\n * Implementation of the requiredJsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredJsonEventStream = function <DATA>() {\n const eventStream = this.jsonEventStream<DATA>();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","_ServerSentEventFields","ServerSentEventFields","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","EventStreamConvertError","FetcherError","response","errorMsg","cause","toServerSentEventStream","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","CONTENT_TYPE_HEADER","contentType","ContentTypeValues","eventStream"],"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;AAAA,IAE3B,SAASC,GAAO;AACd,MAAAH,EAAW,MAAMG,CAAK;AAAA,IACxB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAMH,GAAsD;AAC1D,QAAI;AAEF,MAAI,KAAK,UACPA,EAAW,QAAQ,KAAK,MAAM;AAAA,IAElC,SAASG,GAAO;AACd,MAAAH,EAAW,MAAMG,CAAK;AAAA,IACxB;AAAA,EACF;AACF;AAKO,MAAMC,UAAgC,gBAAgC;AAAA,EAC3E,cAAc;AACZ,UAAM,IAAIN,GAAqB;AAAA,EACjC;AACF;ACzCO,MAAMO,IAAN,MAAMA,EAAsB;AAKnC;AAJEA,EAAgB,KAAK,MACrBA,EAAgB,QAAQ,SACxBA,EAAgB,QAAQ,SACxBA,EAAgB,OAAO;AAJlB,IAAMC,IAAND;AAaP,SAASE,EACPC,GACAC,GACAC,GACA;AACA,UAAQF,GAAA;AAAA,IACN,KAAKF,EAAsB;AACzB,MAAAI,EAAa,QAAQD;AACrB;AAAA,IACF,KAAKH,EAAsB;AACzB,MAAAI,EAAa,KAAK,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,UAAM,IAAId;AAAA,MACR;AAAA,MACA,0DAA0D,KAAK,WAAW;AAAA,IAAA;AAG9E,SAAOc;AACT;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/eventStreamResultExtractor.ts","../src/responses.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 type ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Custom error class for event stream conversion errors.\n * Thrown when there are issues converting a Response to a ServerSentEventStream.\n */\nexport class EventStreamConvertError extends FetcherError {\n /**\n * Creates a new EventStreamConvertError instance.\n * @param response - The Response object associated with the error\n * @param errorMsg - Optional error message describing what went wrong during conversion\n * @param cause - Optional underlying error that caused this error\n */\n constructor(\n public readonly response: Response,\n errorMsg?: string,\n cause?: Error | any,\n ) {\n super(errorMsg, cause);\n this.name = 'EventStreamConvertError';\n // Restore prototype chain for proper inheritance\n Object.setPrototypeOf(this, EventStreamConvertError.prototype);\n }\n}\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 EventStreamConvertError(response, '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 { type 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\n\nimport { FetchExchange, ResultExtractor } from '@ahoo-wang/fetcher';\nimport { ServerSentEventStream } from './eventStreamConverter';\nimport { JsonServerSentEventStream } from './jsonServerSentEventTransformStream';\n\n/**\n * ServerSentEventStream result extractor, used to extract server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of server-sent event stream\n * @throws ExchangeError exception when server does not support ServerSentEventStream\n */\nexport const EventStreamResultExtractor: ResultExtractor<ServerSentEventStream> = (\n exchange: FetchExchange,\n) => {\n return exchange.requiredResponse.requiredEventStream();\n};\n\n/**\n * JsonServerSentEventStream result extractor, used to extract JSON server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of JSON server-sent event stream\n * @throws ExchangeError exception when server does not support JsonServerSentEventStream\n */\nexport const JsonEventStreamResultExtractor: ResultExtractor<JsonServerSentEventStream<any>> = (\n exchange: FetchExchange,\n) => {\n return exchange.requiredResponse.requiredJsonEventStream();\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 {\n EventStreamConvertError,\n type ServerSentEventStream,\n toServerSentEventStream,\n} from './eventStreamConverter';\nimport {\n type JsonServerSentEventStream,\n toJsonServerSentEventStream,\n} from './jsonServerSentEventTransformStream';\nimport { CONTENT_TYPE_HEADER, ContentTypeValues } from '@ahoo-wang/fetcher';\n\ndeclare global {\n interface Response {\n /**\n * Gets the content type of the response.\n *\n * This property provides access to the Content-Type header of the response,\n * which indicates the media type of the resource transmitted in the response.\n *\n * @returns The content type header value as a string, or null if the header is not set\n */\n get contentType(): string | null;\n\n /**\n * Checks if the response is an event stream.\n *\n * This property examines the Content-Type header to determine if the response\n * contains server-sent events data (text/event-stream).\n *\n * @returns true if the response is an event stream, false otherwise\n */\n get isEventStream(): boolean;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects, or null if not an event stream\n */\n eventStream(): ServerSentEventStream | null;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is similar to eventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws {Error} if the event stream is not available\n */\n requiredEventStream(): ServerSentEventStream;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data, or null if not an event stream\n */\n jsonEventStream<DATA>(): JsonServerSentEventStream<DATA> | null;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is similar to jsonEventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream with JSON data.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data\n * @throws {Error} if the event stream is not available\n */\n requiredJsonEventStream<DATA>(): JsonServerSentEventStream<DATA>;\n }\n\n interface ReadableStream<R = any> {\n /**\n * Makes ReadableStream async iterable for use with for-await loops.\n *\n * This allows the stream to be consumed using `for await (const chunk of stream)` syntax.\n *\n * @returns An async iterator for the stream\n */\n [Symbol.asyncIterator](): AsyncIterator<R>;\n }\n}\n\n/**\n * Defines the contentType property on Response prototype.\n * This property provides a convenient way to access the Content-Type header value.\n */\nObject.defineProperty(Response.prototype, 'contentType', {\n get() {\n return this.headers.get(CONTENT_TYPE_HEADER);\n },\n});\n\n/**\n * Defines the isEventStream property on Response prototype.\n * This property checks if the response has a Content-Type header indicating it's an event stream.\n */\nObject.defineProperty(Response.prototype, 'isEventStream', {\n get() {\n const contentType = this.contentType;\n if (!contentType) {\n return false;\n }\n return contentType.includes(ContentTypeValues.TEXT_EVENT_STREAM);\n },\n});\n\n/**\n * Implementation of the eventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream.\n *\n * @returns A ServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.eventStream = function() {\n if (!this.isEventStream) {\n return null;\n }\n return toServerSentEventStream(this);\n};\n\n/**\n * Implementation of the requiredEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @returns A ServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredEventStream = function() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n\n/**\n * Implementation of the jsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.jsonEventStream = function <DATA>() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n return null;\n }\n return toJsonServerSentEventStream<DATA>(eventStream);\n};\n\n/**\n * Implementation of the requiredJsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredJsonEventStream = function <DATA>() {\n const eventStream = this.jsonEventStream<DATA>();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","_ServerSentEventFields","ServerSentEventFields","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","EventStreamConvertError","FetcherError","response","errorMsg","cause","toServerSentEventStream","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","EventStreamResultExtractor","exchange","JsonEventStreamResultExtractor","CONTENT_TYPE_HEADER","contentType","ContentTypeValues","eventStream"],"mappings":";AAoBO,MAAMA,EAA2D;AAAA,EAAjE,cAAA;AACL,SAAQ,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQjB,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UAAM,IAAIF,GAA8B;AAAA,EAC1C;AACF;AAMO,SAASG,EACdC,GACiC;AACjC,SAAOA,EAAsB;AAAA,IAC3B,IAAIF,EAAA;AAAA,EAAyC;AAEjD;AC/BO,MAAMG,IAAqE,CAChFC,MAEOA,EAAS,iBAAiB,oBAAA,GAUtBC,IAAkF,CAC7FD,MAEOA,EAAS,iBAAiB,wBAAA;ACoEnC,OAAO,eAAe,SAAS,WAAW,eAAe;AAAA,EACvD,MAAM;AACJ,WAAO,KAAK,QAAQ,IAAIE,CAAmB;AAAA,EAC7C;AACF,CAAC;AAMD,OAAO,eAAe,SAAS,WAAW,iBAAiB;AAAA,EACzD,MAAM;AACJ,UAAMC,IAAc,KAAK;AACzB,WAAKA,IAGEA,EAAY,SAASC,EAAkB,iBAAiB,IAFtD;AAAA,EAGX;AACF,CAAC;AAQD,SAAS,UAAU,cAAc,WAAW;AAC1C,SAAK,KAAK,gBAGHX,EAAwB,IAAI,IAF1B;AAGX;AAUA,SAAS,UAAU,sBAAsB,WAAW;AAClD,QAAMY,IAAc,KAAK,YAAA;AACzB,MAAI,CAACA;AACH,UAAM,IAAIjB;AAAA,MACR;AAAA,MACA,0DAA0D,KAAK,WAAW;AAAA,IAAA;AAG9E,SAAOiB;AACT;AASA,SAAS,UAAU,kBAAkB,WAAkB;AACrD,QAAMA,IAAc,KAAK,YAAA;AACzB,SAAKA,IAGER,EAAkCQ,CAAW,IAF3C;AAGX;AAWA,SAAS,UAAU,0BAA0B,WAAkB;AAC7D,QAAMA,IAAc,KAAK,gBAAA;AACzB,MAAI,CAACA;AACH,UAAM,IAAIjB;AAAA,MACR;AAAA,MACA,0DAA0D,KAAK,WAAW;AAAA,IAAA;AAG9E,SAAOiB;AACT;"}
|
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
|
|
2
|
-
`);this.buffer=
|
|
3
|
-
`),id:
|
|
4
|
-
`),id:
|
|
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(r,n){try{this.buffer+=r;const t=this.buffer.split(`
|
|
2
|
+
`);this.buffer=t.pop()||"";for(const o of t)n.enqueue(o)}catch(t){n.error(t)}}flush(r){try{this.buffer&&r.enqueue(this.buffer)}catch(n){r.error(n)}}}class S extends TransformStream{constructor(){super(new d)}}const m=class m{};m.ID="id",m.RETRY="retry",m.EVENT="event",m.DATA="data";let f=m;function b(e,r,n){switch(e){case f.EVENT:n.event=r;break;case f.DATA:n.data.push(r);break;case f.ID:n.id=r;break;case f.RETRY:{const t=parseInt(r,10);isNaN(t)||(n.retry=t);break}}}const u="message";class E{constructor(){this.currentEvent={event:u,id:void 0,retry:void 0,data:[]}}transform(r,n){const t=this.currentEvent;try{if(r.trim()===""){t.data.length>0&&(n.enqueue({event:t.event||u,data:t.data.join(`
|
|
3
|
+
`),id:t.id||"",retry:t.retry}),t.event=u,t.data=[]);return}if(r.startsWith(":"))return;const o=r.indexOf(":");let v,a;o===-1?(v=r.toLowerCase(),a=""):(v=r.substring(0,o).toLowerCase(),a=r.substring(o+1),a.startsWith(" ")&&(a=a.substring(1))),v=v.trim(),a=a.trim(),b(v,a,t)}catch(o){n.error(o instanceof Error?o:new Error(String(o))),t.event=u,t.id=void 0,t.retry=void 0,t.data=[]}}flush(r){const n=this.currentEvent;try{n.data.length>0&&r.enqueue({event:n.event||u,data:n.data.join(`
|
|
4
|
+
`),id:n.id||"",retry:n.retry})}catch(t){r.error(t instanceof Error?t:new Error(String(t)))}finally{n.event=u,n.id=void 0,n.retry=void 0,n.data=[]}}}class h extends TransformStream{constructor(){super(new E)}}class c extends i.FetcherError{constructor(r,n,t){super(n,t),this.response=r,this.name="EventStreamConvertError",Object.setPrototypeOf(this,c.prototype)}}function p(e){if(!e.body)throw new c(e,"Response body is null");return e.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new S).pipeThrough(new h)}class T{transform(r,n){const t=JSON.parse(r.data);n.enqueue({data:t,event:r.event,id:r.id,retry:r.retry})}}class y extends TransformStream{constructor(){super(new T)}}function l(e){return e.pipeThrough(new y)}const R=e=>e.requiredResponse.requiredEventStream(),w=e=>e.requiredResponse.requiredJsonEventStream();Object.defineProperty(Response.prototype,"contentType",{get(){return this.headers.get(i.CONTENT_TYPE_HEADER)}}),Object.defineProperty(Response.prototype,"isEventStream",{get(){const e=this.contentType;return e?e.includes(i.ContentTypeValues.TEXT_EVENT_STREAM):!1}}),Response.prototype.eventStream=function(){return this.isEventStream?p(this):null},Response.prototype.requiredEventStream=function(){const e=this.eventStream();if(!e)throw new c(this,`Event stream is not available. Response content-type: [${this.contentType}]`);return e},Response.prototype.jsonEventStream=function(){const e=this.eventStream();return e?l(e):null},Response.prototype.requiredJsonEventStream=function(){const e=this.jsonEventStream();if(!e)throw new c(this,`Event stream is not available. Response content-type: [${this.contentType}]`);return e},s.EventStreamConvertError=c,s.EventStreamResultExtractor=R,s.JsonEventStreamResultExtractor=w,s.JsonServerSentEventTransform=T,s.JsonServerSentEventTransformStream=y,s.ServerSentEventFields=f,s.ServerSentEventTransformStream=h,s.ServerSentEventTransformer=E,s.TextLineTransformStream=S,s.TextLineTransformer=d,s.toJsonServerSentEventStream=l,s.toServerSentEventStream=p,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
|
|
5
5
|
//# sourceMappingURL=index.umd.js.map
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/responses.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 type ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Custom error class for event stream conversion errors.\n * Thrown when there are issues converting a Response to a ServerSentEventStream.\n */\nexport class EventStreamConvertError extends FetcherError {\n /**\n * Creates a new EventStreamConvertError instance.\n * @param response - The Response object associated with the error\n * @param errorMsg - Optional error message describing what went wrong during conversion\n * @param cause - Optional underlying error that caused this error\n */\n constructor(\n public readonly response: Response,\n errorMsg?: string,\n cause?: Error | any,\n ) {\n super(errorMsg, cause);\n this.name = 'EventStreamConvertError';\n // Restore prototype chain for proper inheritance\n Object.setPrototypeOf(this, EventStreamConvertError.prototype);\n }\n}\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 EventStreamConvertError(response, '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 { type 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 {\n EventStreamConvertError,\n type ServerSentEventStream,\n toServerSentEventStream,\n} from './eventStreamConverter';\nimport {\n type JsonServerSentEventStream,\n toJsonServerSentEventStream,\n} from './jsonServerSentEventTransformStream';\nimport { CONTENT_TYPE_HEADER, ContentTypeValues } from '@ahoo-wang/fetcher';\n\ndeclare global {\n interface Response {\n /**\n * Gets the content type of the response.\n *\n * This property provides access to the Content-Type header of the response,\n * which indicates the media type of the resource transmitted in the response.\n *\n * @returns The content type header value as a string, or null if the header is not set\n */\n get contentType(): string | null;\n\n /**\n * Checks if the response is an event stream.\n *\n * This property examines the Content-Type header to determine if the response\n * contains server-sent events data (text/event-stream).\n *\n * @returns true if the response is an event stream, false otherwise\n */\n get isEventStream(): boolean;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects, or null if not an event stream\n */\n eventStream(): ServerSentEventStream | null;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is similar to eventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws {Error} if the event stream is not available\n */\n requiredEventStream(): ServerSentEventStream;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data, or null if not an event stream\n */\n jsonEventStream<DATA>(): JsonServerSentEventStream<DATA> | null;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is similar to jsonEventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream with JSON data.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data\n * @throws {Error} if the event stream is not available\n */\n requiredJsonEventStream<DATA>(): JsonServerSentEventStream<DATA>;\n }\n\n interface ReadableStream<R = any> {\n /**\n * Makes ReadableStream async iterable for use with for-await loops.\n *\n * This allows the stream to be consumed using `for await (const chunk of stream)` syntax.\n *\n * @returns An async iterator for the stream\n */\n [Symbol.asyncIterator](): AsyncIterator<R>;\n }\n}\n\n/**\n * Defines the contentType property on Response prototype.\n * This property provides a convenient way to access the Content-Type header value.\n */\nObject.defineProperty(Response.prototype, 'contentType', {\n get() {\n return this.headers.get(CONTENT_TYPE_HEADER);\n },\n});\n\n/**\n * Defines the isEventStream property on Response prototype.\n * This property checks if the response has a Content-Type header indicating it's an event stream.\n */\nObject.defineProperty(Response.prototype, 'isEventStream', {\n get() {\n const contentType = this.contentType;\n if (!contentType) {\n return false;\n }\n return contentType.includes(ContentTypeValues.TEXT_EVENT_STREAM);\n },\n});\n\n/**\n * Implementation of the eventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream.\n *\n * @returns A ServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.eventStream = function() {\n if (!this.isEventStream) {\n return null;\n }\n return toServerSentEventStream(this);\n};\n\n/**\n * Implementation of the requiredEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @returns A ServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredEventStream = function() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n\n/**\n * Implementation of the jsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.jsonEventStream = function <DATA>() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n return null;\n }\n return toJsonServerSentEventStream<DATA>(eventStream);\n};\n\n/**\n * Implementation of the requiredJsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredJsonEventStream = function <DATA>() {\n const eventStream = this.jsonEventStream<DATA>();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","_ServerSentEventFields","ServerSentEventFields","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","EventStreamConvertError","FetcherError","response","errorMsg","cause","toServerSentEventStream","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","CONTENT_TYPE_HEADER","contentType","ContentTypeValues","eventStream"],"mapp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EAAc,KAAK,YAAA,EACzB,GAAI,CAACA,EACH,MAAM,IAAId,EACR,KACA,0DAA0D,KAAK,WAAW,GAAA,EAG9E,OAAOc,CACT,EASA,SAAS,UAAU,gBAAkB,UAAkB,CACrD,MAAMA,EAAc,KAAK,YAAA,EACzB,OAAKA,EAGEL,EAAkCK,CAAW,EAF3C,IAGX,EAWA,SAAS,UAAU,wBAA0B,UAAkB,CAC7D,MAAMA,EAAc,KAAK,gBAAA,EACzB,GAAI,CAACA,EACH,MAAM,IAAId,EACR,KACA,0DAA0D,KAAK,WAAW,GAAA,EAG9E,OAAOc,CACT"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/eventStreamResultExtractor.ts","../src/responses.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 type ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Custom error class for event stream conversion errors.\n * Thrown when there are issues converting a Response to a ServerSentEventStream.\n */\nexport class EventStreamConvertError extends FetcherError {\n /**\n * Creates a new EventStreamConvertError instance.\n * @param response - The Response object associated with the error\n * @param errorMsg - Optional error message describing what went wrong during conversion\n * @param cause - Optional underlying error that caused this error\n */\n constructor(\n public readonly response: Response,\n errorMsg?: string,\n cause?: Error | any,\n ) {\n super(errorMsg, cause);\n this.name = 'EventStreamConvertError';\n // Restore prototype chain for proper inheritance\n Object.setPrototypeOf(this, EventStreamConvertError.prototype);\n }\n}\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 EventStreamConvertError(response, '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 { type 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\n\nimport { FetchExchange, ResultExtractor } from '@ahoo-wang/fetcher';\nimport { ServerSentEventStream } from './eventStreamConverter';\nimport { JsonServerSentEventStream } from './jsonServerSentEventTransformStream';\n\n/**\n * ServerSentEventStream result extractor, used to extract server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of server-sent event stream\n * @throws ExchangeError exception when server does not support ServerSentEventStream\n */\nexport const EventStreamResultExtractor: ResultExtractor<ServerSentEventStream> = (\n exchange: FetchExchange,\n) => {\n return exchange.requiredResponse.requiredEventStream();\n};\n\n/**\n * JsonServerSentEventStream result extractor, used to extract JSON server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of JSON server-sent event stream\n * @throws ExchangeError exception when server does not support JsonServerSentEventStream\n */\nexport const JsonEventStreamResultExtractor: ResultExtractor<JsonServerSentEventStream<any>> = (\n exchange: FetchExchange,\n) => {\n return exchange.requiredResponse.requiredJsonEventStream();\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 {\n EventStreamConvertError,\n type ServerSentEventStream,\n toServerSentEventStream,\n} from './eventStreamConverter';\nimport {\n type JsonServerSentEventStream,\n toJsonServerSentEventStream,\n} from './jsonServerSentEventTransformStream';\nimport { CONTENT_TYPE_HEADER, ContentTypeValues } from '@ahoo-wang/fetcher';\n\ndeclare global {\n interface Response {\n /**\n * Gets the content type of the response.\n *\n * This property provides access to the Content-Type header of the response,\n * which indicates the media type of the resource transmitted in the response.\n *\n * @returns The content type header value as a string, or null if the header is not set\n */\n get contentType(): string | null;\n\n /**\n * Checks if the response is an event stream.\n *\n * This property examines the Content-Type header to determine if the response\n * contains server-sent events data (text/event-stream).\n *\n * @returns true if the response is an event stream, false otherwise\n */\n get isEventStream(): boolean;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects, or null if not an event stream\n */\n eventStream(): ServerSentEventStream | null;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is similar to eventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws {Error} if the event stream is not available\n */\n requiredEventStream(): ServerSentEventStream;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data, or null if not an event stream\n */\n jsonEventStream<DATA>(): JsonServerSentEventStream<DATA> | null;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is similar to jsonEventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream with JSON data.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data\n * @throws {Error} if the event stream is not available\n */\n requiredJsonEventStream<DATA>(): JsonServerSentEventStream<DATA>;\n }\n\n interface ReadableStream<R = any> {\n /**\n * Makes ReadableStream async iterable for use with for-await loops.\n *\n * This allows the stream to be consumed using `for await (const chunk of stream)` syntax.\n *\n * @returns An async iterator for the stream\n */\n [Symbol.asyncIterator](): AsyncIterator<R>;\n }\n}\n\n/**\n * Defines the contentType property on Response prototype.\n * This property provides a convenient way to access the Content-Type header value.\n */\nObject.defineProperty(Response.prototype, 'contentType', {\n get() {\n return this.headers.get(CONTENT_TYPE_HEADER);\n },\n});\n\n/**\n * Defines the isEventStream property on Response prototype.\n * This property checks if the response has a Content-Type header indicating it's an event stream.\n */\nObject.defineProperty(Response.prototype, 'isEventStream', {\n get() {\n const contentType = this.contentType;\n if (!contentType) {\n return false;\n }\n return contentType.includes(ContentTypeValues.TEXT_EVENT_STREAM);\n },\n});\n\n/**\n * Implementation of the eventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream.\n *\n * @returns A ServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.eventStream = function() {\n if (!this.isEventStream) {\n return null;\n }\n return toServerSentEventStream(this);\n};\n\n/**\n * Implementation of the requiredEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @returns A ServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredEventStream = function() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n\n/**\n * Implementation of the jsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.jsonEventStream = function <DATA>() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n return null;\n }\n return toJsonServerSentEventStream<DATA>(eventStream);\n};\n\n/**\n * Implementation of the requiredJsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredJsonEventStream = function <DATA>() {\n const eventStream = this.jsonEventStream<DATA>();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","_ServerSentEventFields","ServerSentEventFields","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","EventStreamConvertError","FetcherError","response","errorMsg","cause","toServerSentEventStream","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","EventStreamResultExtractor","exchange","JsonEventStreamResultExtractor","CONTENT_TYPE_HEADER","contentType","ContentTypeValues","eventStream"],"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,EACAC,EACAC,EACA,CACA,OAAQF,EAAA,CACN,KAAKF,EAAsB,MACzBI,EAAa,MAAQD,EACrB,MACF,KAAKH,EAAsB,KACzBI,EAAa,KAAK,KAAKD,CAAK,EAC5B,MACF,KAAKH,EAAsB,GACzBI,EAAa,GAAKD,EAClB,MACF,KAAKH,EAAsB,MAAO,CAChC,MAAMK,EAAa,SAASF,EAAO,EAAE,EAChC,MAAME,CAAU,IACnBD,EAAa,MAAQC,GAEvB,KACF,CAGE,CAEN,CASA,MAAMC,EAAqB,UAOpB,MAAMC,CACqC,CAD3C,aAAA,CAGL,KAAQ,aAA2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UAAW,gBAAiB,CACzD,KAAM,CACJ,MAAMC,EAAc,KAAK,YACzB,OAAKA,EAGEA,EAAY,SAASC,EAAAA,kBAAkB,iBAAiB,EAFtD,EAGX,CACF,CAAC,EAQD,SAAS,UAAU,YAAc,UAAW,CAC1C,OAAK,KAAK,cAGHX,EAAwB,IAAI,EAF1B,IAGX,EAUA,SAAS,UAAU,oBAAsB,UAAW,CAClD,MAAMY,EAAc,KAAK,YAAA,EACzB,GAAI,CAACA,EACH,MAAM,IAAIjB,EACR,KACA,0DAA0D,KAAK,WAAW,GAAA,EAG9E,OAAOiB,CACT,EASA,SAAS,UAAU,gBAAkB,UAAkB,CACrD,MAAMA,EAAc,KAAK,YAAA,EACzB,OAAKA,EAGER,EAAkCQ,CAAW,EAF3C,IAGX,EAWA,SAAS,UAAU,wBAA0B,UAAkB,CAC7D,MAAMA,EAAc,KAAK,gBAAA,EACzB,GAAI,CAACA,EACH,MAAM,IAAIjB,EACR,KACA,0DAA0D,KAAK,WAAW,GAAA,EAG9E,OAAOiB,CACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ahoo-wang/fetcher-eventstream",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
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.
|
|
42
|
+
"@ahoo-wang/fetcher": "1.5.0"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"@vitest/coverage-v8": "^3.2.4",
|