Create fetchsse.js
Browse files- fetchsse.js +64 -0
fetchsse.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
async function* streamAsyncIterable(stream) {
|
| 2 |
+
const reader = stream.getReader();
|
| 3 |
+
try {
|
| 4 |
+
while (true) {
|
| 5 |
+
const { done, value } = await reader.read();
|
| 6 |
+
if (done) {
|
| 7 |
+
return;
|
| 8 |
+
}
|
| 9 |
+
yield value;
|
| 10 |
+
}
|
| 11 |
+
} finally {
|
| 12 |
+
reader.releaseLock();
|
| 13 |
+
}
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
// add timeout to fetchSSE
|
| 17 |
+
async function fetchSSE(url, options, fetch2 = fetch) {
|
| 18 |
+
const { createParser } = await import("eventsource-parser");
|
| 19 |
+
const { onMessage, timeout , ...fetchOptions } = options;
|
| 20 |
+
const controller = new AbortController();
|
| 21 |
+
const timeoutId = setTimeout(() => controller.abort(), timeout||30000)
|
| 22 |
+
|
| 23 |
+
const res = await fetch2(url, {...fetchOptions,signal:controller.signal});
|
| 24 |
+
clearTimeout(timeoutId);
|
| 25 |
+
|
| 26 |
+
if (!res.ok) {
|
| 27 |
+
let reason;
|
| 28 |
+
try {
|
| 29 |
+
reason = await res.text();
|
| 30 |
+
} catch (err) {
|
| 31 |
+
reason = res.statusText;
|
| 32 |
+
}
|
| 33 |
+
const msg = `ChatGPT error ${res.status}: ${reason}`;
|
| 34 |
+
const error = new ChatGPTError(msg, { cause: res });
|
| 35 |
+
error.statusCode = res.status;
|
| 36 |
+
error.statusText = res.statusText;
|
| 37 |
+
error.context = { url, options };
|
| 38 |
+
throw error;
|
| 39 |
+
}
|
| 40 |
+
const parser = createParser((event) => {
|
| 41 |
+
if (event.type === "event") {
|
| 42 |
+
onMessage(event.data);
|
| 43 |
+
}
|
| 44 |
+
});
|
| 45 |
+
if (!res.body.getReader) {
|
| 46 |
+
const body = res.body;
|
| 47 |
+
if (!body.on || !body.read) {
|
| 48 |
+
throw new ChatGPTError('unsupported "fetch" implementation');
|
| 49 |
+
}
|
| 50 |
+
body.on("readable", () => {
|
| 51 |
+
let chunk;
|
| 52 |
+
while (null !== (chunk = body.read())) {
|
| 53 |
+
parser.feed(chunk.toString());
|
| 54 |
+
}
|
| 55 |
+
});
|
| 56 |
+
} else {
|
| 57 |
+
for await (const chunk of streamAsyncIterable(res.body)) {
|
| 58 |
+
const str = new TextDecoder().decode(chunk);
|
| 59 |
+
parser.feed(str);
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
module.exports = fetchSSE;
|