aiwrapper
Version:
A Universal AI Wrapper for JavaScript & TypeScript
53 lines (52 loc) • 1.39 kB
JavaScript
const processLinesFromStream = (rawData, onData) => {
if (rawData.startsWith("{")) {
processDataAsJson(rawData, onData);
return;
}
processDataAsStr(rawData, onData);
};
const processDataAsStr = (rawData, onData) => {
const lines = rawData.split("\n");
let currentEvent = null;
for (const line of lines) {
if (line.startsWith("event: ")) {
currentEvent = line.substring(7).trim();
continue;
}
if (line.startsWith("data: ")) {
const dataStr = line.substring(6);
if (dataStr === "[DONE]") {
onData({ finished: true });
currentEvent = null;
continue;
}
try {
const data = JSON.parse(dataStr);
if (currentEvent && typeof data === "object" && data !== null && !("type" in data)) {
data.type = currentEvent;
}
onData(data);
} catch (err) {
throw new Error(err);
} finally {
currentEvent = null;
}
}
}
};
const processDataAsJson = (rawData, onData) => {
const lines = rawData.split("\n");
for (const line of lines) {
try {
const data = JSON.parse(line);
onData(data);
} catch (err) {
throw new Error(err);
}
}
};
var process_lines_from_stream_default = processLinesFromStream;
export {
process_lines_from_stream_default as default
};
//# sourceMappingURL=process-lines-from-stream.js.map