Spaces:
Running

File size: 2,108 Bytes
03608f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Server-sent events over fetch (EventSource cannot send an Authorization header).

export interface SseEvent {
  event: string;
  data: string;
  id?: string;
}

/** Parse complete events out of a text buffer; returns the unparsed remainder. */
export function parseSse(buffer: string): { events: SseEvent[]; rest: string } {
  const normalized = buffer.replace(/\r\n?/g, "\n");
  const blocks = normalized.split("\n\n");
  const rest = blocks.pop() ?? "";
  const events: SseEvent[] = [];
  for (const block of blocks) {
    let event = "message";
    let id: string | undefined;
    const data: string[] = [];
    for (const line of block.split("\n")) {
      if (!line || line.startsWith(":")) continue;
      const i = line.indexOf(":");
      const field = i === -1 ? line : line.slice(0, i);
      const value = i === -1 ? "" : line.slice(i + 1).replace(/^ /, "");
      if (field === "event") event = value;
      else if (field === "data") data.push(value);
      else if (field === "id") id = value;
    }
    if (data.length) events.push({ event, data: data.join("\n"), id });
  }
  return { events, rest };
}

export interface StreamOptions {
  headers?: Record<string, string>;
  signal?: AbortSignal;
  onEvent: (e: SseEvent) => void;
}

/** Read one SSE response to the end. Resolves when the server closes the stream. */
export async function streamSse(url: string, opts: StreamOptions): Promise<number> {
  const res = await fetch(url, {
    headers: { Accept: "text/event-stream", ...opts.headers },
    signal: opts.signal,
    cache: "no-store",
  });
  if (!res.ok || !res.body) return res.status;
  const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
  let buffer = "";
  for (;;) {
    const { value, done } = await reader.read();
    if (done) break;
    buffer += value;
    const { events, rest } = parseSse(buffer);
    buffer = rest;
    for (const e of events) opts.onEvent(e);
  }
  const { events } = parseSse(buffer + "\n\n");
  for (const e of events) opts.onEvent(e);
  return res.status;
}