26 lines
1.1 KiB
TypeScript
26 lines
1.1 KiB
TypeScript
// 运行:node sse-demo.ts —— 验证解析器能处理被切开的分块、多行 data、心跳注释
|
|
import { createSSEParser, parseFinal, type SSEEvent } from "./sse.ts";
|
|
|
|
const events: SSEEvent[] = [];
|
|
const feed = createSSEParser((e) => events.push(e));
|
|
|
|
const stream = [
|
|
": ping\n\n",
|
|
"id: 1\nevent: progress\ndata: {\"step\":\"检索资料\"}\n\n",
|
|
"id: 2\nevent: token\ndata: 签收 7 天内",
|
|
"可以无理由退货\n\nid: 3\nevent: tok",
|
|
"en\ndata: 。\n\n",
|
|
"id: 4\nevent: final\ndata: {\"answer\":\"签收 7 天内可以无理由退货。\",\n",
|
|
"data: \"citations\":[{\"id\":1,\"title\":\"退货政策\"}]}\n\n",
|
|
];
|
|
for (const chunk of stream) feed(chunk);
|
|
|
|
console.log(events.map((e) => `${e.id}:${e.event}`).join(" "));
|
|
const text = events.filter((e) => e.event === "token").map((e) => e.data).join("");
|
|
const last = events.at(-1);
|
|
const final = last ? parseFinal(last.data) : null;
|
|
console.log("拼接文本:", text, "引用:", final?.citations);
|
|
if (text !== "签收 7 天内可以无理由退货。" || events.length !== 4 || final?.citations[0]?.title !== "退货政策") {
|
|
throw new Error("断言失败");
|
|
}
|