1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// protocol https://creator.poe.com/docs/poe-protocol-specification
async function getResponse(req: any, send: (event: string, data?: any) => void) {
send("meta", { content_type: "text/markdown" });
send("text", { text: "```\n" + JSON.stringify(req, null, 3) + "\n```" });
send("done");
}
function encodeEvent(event: string, data?: any = {}) {
return new TextEncoder().encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
}
export default async function(req: Request): Promise<Response> {
let timerId: number | undefined;
const body = new ReadableStream({
start(controller) {
req.json().catch((e) => {
console.error("No json body");
return null;
}).then((reqBody) => {
const send = (event, data) => {
controller.enqueue(encodeEvent(event, data));
};
return getResponse(reqBody, send);
}).finally(() => {
controller.close();
});
},
});
return new Response(body, {
status: 200,
headers: {
"Content-Type": "text/event-stream",
},
});
}