| 1 | import Foundation |
| 2 | |
| 3 | /// One Server-Sent Event, as the HTML standard assembles it from lines. |
| 4 | public struct SSEEvent: Sendable, Equatable { |
| 5 | /// The event's own `id:`, if it had one. (A glance has none: Base sends |
| 6 | /// it live only, so the cursor stays where the last event put it.) |
| 7 | public var id: String? |
| 8 | /// `event:`, or "message". |
| 9 | public var type: String |
| 10 | /// Every `data:` line, joined with newlines. |
| 11 | public var data: String |
| 12 | /// `retry:`, in milliseconds. |
| 13 | public var retry: Int? |
| 14 | } |
| 15 | |
| 16 | /// Assembles lines into events (the HTML standard's "interpret an event |
| 17 | /// stream"): a blank line dispatches; `:` starts a comment (Base's pings); |
| 18 | /// `data` lines join with "\n"; `id`, `event` and `retry` as the standard |
| 19 | /// says. An event with no data is dropped, but its `retry` is kept for the |
| 20 | /// next. Lines come framed by the kit's NativeStreamLines (CR, LF, CRLF). |
| 21 | public struct SSEParser: Sendable { |
| 22 | private var id: String? |
| 23 | private var type = "" |
| 24 | private var data: [String] = [] |
| 25 | private var retry: Int? |
| 26 | private var sawData = false |
| 27 | |
| 28 | public init() {} |
| 29 | |
| 30 | public mutating func feed(_ line: String) -> SSEEvent? { |
| 31 | if line.isEmpty { return dispatch() } |
| 32 | if line.hasPrefix(":") { return nil } |
| 33 | let name: Substring, value: Substring |
| 34 | if let colon = line.firstIndex(of: ":") { |
| 35 | name = line[..<colon] |
| 36 | var rest = line[line.index(after: colon)...] |
| 37 | if rest.first == " " { rest = rest.dropFirst() } |
| 38 | value = rest |
| 39 | } else { |
| 40 | name = line[...]; value = "" |
| 41 | } |
| 42 | switch name { |
| 43 | case "event": type = String(value) |
| 44 | case "data": data.append(String(value)); sawData = true |
| 45 | case "id": if !value.contains("\0") { id = String(value) } |
| 46 | case "retry": if !value.isEmpty, value.allSatisfy(\.isASCII), value.allSatisfy(\.isNumber) { retry = Int(value) } |
| 47 | default: break |
| 48 | } |
| 49 | return nil |
| 50 | } |
| 51 | |
| 52 | private mutating func dispatch() -> SSEEvent? { |
| 53 | defer { id = nil; type = ""; data = []; sawData = false } |
| 54 | guard sawData else { return nil } |
| 55 | let event = SSEEvent(id: id, type: type.isEmpty ? "message" : type, data: data.joined(separator: "\n"), retry: retry) |
| 56 | retry = nil |
| 57 | return event |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | /// A few of the reply's words, streamed: `offset` counts the UTF-8 bytes |
| 62 | /// before them. |
| 63 | public struct AskDelta: Decodable, Sendable, Equatable { |
| 64 | public var turnID: String |
| 65 | public var offset: Int64 |
| 66 | public var text: String |
| 67 | public init(turnID: String, offset: Int64, text: String) { self.turnID = turnID; self.offset = offset; self.text = text } |
| 68 | enum CodingKeys: String, CodingKey { case turnID = "turn_id", offset, text } |
| 69 | public init(from decoder: Decoder) throws { |
| 70 | let c = try decoder.container(keyedBy: CodingKeys.self) |
| 71 | turnID = c.value(.turnID, ""); offset = c.value(.offset, -1); text = c.value(.text, "") |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | /// A line about a turn in flight: Equipo's glance (said once, before the |
| 76 | /// first words) or an activity label. |
| 77 | public struct AskLine: Decodable, Sendable, Equatable { |
| 78 | public var turnID: String |
| 79 | public var text: String |
| 80 | public init(turnID: String, text: String) { self.turnID = turnID; self.text = text } |
| 81 | enum CodingKeys: String, CodingKey { case turnID = "turn_id", text, label } |
| 82 | public init(from decoder: Decoder) throws { |
| 83 | let c = try decoder.container(keyedBy: CodingKeys.self) |
| 84 | turnID = c.value(.turnID, ""); text = c.optional(.text) ?? c.value(.label, "") |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /// What Base's stream says (ask_relay.go `frame`, ask.js `listen`). Each |
| 89 | /// conversation event's data is `{"type": …, "data": …}`, the data in |
| 90 | /// `/ask/state`'s shapes; a stream that can't start says why in one |
| 91 | /// `state` event whose data is `{"state": …}`. |
| 92 | public enum AskEvent: Sendable, Equatable { |
| 93 | case message(AskMessage) |
| 94 | case turn(AskTurn) |
| 95 | case card(AskCard) |
| 96 | case delta(AskDelta) |
| 97 | case glance(AskLine) |
| 98 | case activity(AskLine) |
| 99 | case state(AskPhase) |
| 100 | |
| 101 | /// The event, or nil for one this app doesn't know or can't read. |
| 102 | public static func decode(_ event: SSEEvent) -> AskEvent? { |
| 103 | let raw = Data(event.data.utf8) |
| 104 | let decoder = JSONDecoder() |
| 105 | if event.type == "state" { |
| 106 | struct State: Decodable { var state: String? } |
| 107 | guard let s = try? decoder.decode(State.self, from: raw) else { return nil } |
| 108 | return .state(AskPhase(server: s.state)) |
| 109 | } |
| 110 | struct Envelope<T: Decodable>: Decodable { var data: T } |
| 111 | func data<T: Decodable>(_: T.Type) -> T? { (try? decoder.decode(Envelope<T>.self, from: raw))?.data } |
| 112 | switch event.type { |
| 113 | case "message": return data(AskMessage.self).flatMap { $0.id.isEmpty ? nil : .message($0) } |
| 114 | case "turn": return data(AskTurn.self).flatMap { $0.id.isEmpty ? nil : .turn($0) } |
| 115 | case "card": return data(AskCard.self).flatMap { $0.id.isEmpty ? nil : .card($0) } |
| 116 | case "delta": return data(AskDelta.self).flatMap { $0.turnID.isEmpty ? nil : .delta($0) } |
| 117 | case "glance": return data(AskLine.self).flatMap { $0.turnID.isEmpty ? nil : .glance($0) } |
| 118 | case "activity": return data(AskLine.self).flatMap { $0.turnID.isEmpty ? nil : .activity($0) } |
| 119 | default: return nil |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |