import Foundation /// A write that must be retried as itself: the same key, body and revision /// until its result is known (equipo-v1.md, "Retry writes"). Keep it until /// the call returns a result or a definite error; resend it after `.offline`. public struct PendingWrite: Sendable, Equatable, Codable { public let key: String public let body: Data public let ifMatch: Int64? public init(body: Data, ifMatch: Int64? = nil, key: String = UUID().uuidString.lowercased()) { self.key = key; self.body = body; self.ifMatch = ifMatch } public static func json(_ value: T, ifMatch: Int64? = nil) throws -> PendingWrite { PendingWrite(body: try EquipoJSON.encoder.encode(value), ifMatch: ifMatch) } } /// The person API, for one instance and one device credential. public struct EquipoClient: Sendable { public let transport: EquipoTransport public let token: String? public init(transport: EquipoTransport, token: String?) { self.transport = transport; self.token = token } public var origin: URL { transport.origin } // MARK: Reads (the conversation engine, as a device bearer reads it) public func me() async throws -> Me { try await get("/me") } public func snapshot() async throws -> Snapshot { try await get("/snapshot") } public func olderMessages(before: String, limit: Int = 50) async throws -> MessagePage { try await get("/messages", [URLQueryItem(name: "before", value: before), URLQueryItem(name: "limit", value: String(min(max(limit, 1), 200)))]) } public func tasks() async throws -> ThinList { try await get("/tasks") } public func needsYou() async throws -> ThinList { try await get("/needs-you") } public func task(_ id: String) async throws -> ThinTask { try await get("/tasks/\(escape(id))") } public func projects() async throws -> ProjectList { try await get("/projects") } public func devices() async throws -> Page { try await get("/auth/devices") } /// The conversation's events after `cursor`, as Server-Sent Event lines. public func events(after cursor: Int64) async throws -> AsyncThrowingStream { try await transport.lines(APIRequest("GET", "/events", query: [URLQueryItem(name: "after", value: String(cursor))], bearer: token)) } // MARK: Writes. Each takes a PendingWrite so a retry is the same request. /// A message; the engine takes its key in the body as well as the header. public static func message(_ text: String, projectID: String? = nil, attachments: [String] = []) throws -> PendingWrite { let key = UUID().uuidString.lowercased() var body: [String: AnyEncodable] = ["text": .init(text), "idempotency_key": .init(key)] guard attachments.count <= AttachmentLimits.maxCount, Set(attachments).count == attachments.count else { throw EquipoAPIError.status(422) } if let projectID { body["project_id"] = .init(projectID) } if !attachments.isEmpty { body["attachments"] = .init(attachments) } return PendingWrite(body: try EquipoJSON.encoder.encode(body), key: key) } public func send(_ write: PendingWrite) async throws -> Sent { try await post("/messages", write) } public func postThread(task taskID: String, _ write: PendingWrite) async throws -> ThreadEntry { try await post("/tasks/\(escape(taskID))/thread", write) } /// An answer to a card, bound to the card revision the person saw. public static func answer(_ choice: String, note: String? = nil, rememberName: String? = nil, to card: ThinCard) throws -> PendingWrite { var body: [String: AnyEncodable] = ["choice": .init(choice), "revision": .init(card.revision)] if let note, !note.isEmpty { body["note"] = .init(note) } if let rememberName { body["remember_name"] = .init(rememberName) } return PendingWrite(body: try EquipoJSON.encoder.encode(body), ifMatch: card.revision) } public func answer(card id: String, _ write: PendingWrite) async throws -> Answered { guard write.ifMatch != nil else { throw EquipoAPIError.status(428) } return try await post("/cards/\(escape(id))/answer", write) } /// Stops the coordinator's turn; only that turn. /// POST /tasks/{id}/run-now: Run now on the held step at its revision. public func runNow(task id: String, step: String, revision: Int64, offer: String) async throws -> RunNowAccepted { try await post("/tasks/\(escape(id))/run-now", try .json(RunNowInput(step: step, stepRevision: revision, offer: offer))) } /// PUT /time-zone: this device's IANA zone. public func setTimeZone(_ zone: String) async throws -> TimeZoneValue { try await send(APIRequest("PUT", "/time-zone", body: try EquipoJSON.encoder.encode(TimeZoneValue(timeZone: zone)), bearer: token)) } public func cancelTurn(_ id: String) async throws { let _: EmptyResponse = try await post("/turns/\(escape(id))/cancel", PendingWrite(body: Data("{}".utf8))) } public func revokeDevice(_ id: String, _ write: PendingWrite) async throws -> Ack { try await send(APIRequest("DELETE", "/auth/devices/\(escape(id))", body: write.body, bearer: token, idempotencyKey: write.key, ifMatch: write.ifMatch)) } public static func empty(ifMatch: Int64? = nil) -> PendingWrite { PendingWrite(body: Data("{}".utf8), ifMatch: ifMatch) } // MARK: Pairing. No bearer: the device has none yet. public func beginDevice(_ write: PendingWrite) async throws -> DeviceChallenge { try await send(APIRequest("POST", "/auth/devices", body: write.body, idempotencyKey: write.key)) } public func exchangeDevice(_ write: PendingWrite) async throws -> DeviceCredential { try await send(APIRequest("POST", "/auth/devices/exchange", body: write.body, idempotencyKey: write.key)) } // MARK: Plumbing func escape(_ id: String) -> String { id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/"))) ?? id } func get(_ path: String, _ query: [URLQueryItem] = []) async throws -> T { try await send(APIRequest("GET", path, query: query, bearer: token)) } func post(_ path: String, _ write: PendingWrite) async throws -> T { try await send(APIRequest("POST", path, body: write.body, bearer: token, idempotencyKey: write.key, ifMatch: write.ifMatch)) } func send(_ request: APIRequest) async throws -> T { if T.self == EmptyResponse.self { let response = try await transport.send(request) guard (200..<300).contains(response.status) else { throw Self.error(response) } return EmptyResponse() as! T } let response = try await transport.send(request) guard (200..<300).contains(response.status) else { throw Self.error(response) } do { return try EquipoJSON.decoder.decode(T.self, from: response.data) } catch { throw EquipoAPIError.undecodable } } static func error(_ response: APIResponse) -> EquipoAPIError { if let conflict = try? EquipoJSON.decoder.decode(CardConflict.self, from: response.data) { return .card(status: response.status, code: conflict.code, card: conflict.card) } if let body = try? EquipoJSON.decoder.decode(APIErrorBody.self, from: response.data) { return .server(status: response.status, body: body) } return .status(response.status) } } public struct EmptyResponse: Decodable, Sendable { public init() {} } /// Lets one JSON body mix strings and numbers. public struct AnyEncodable: Encodable, Sendable { private let encodeValue: @Sendable (Encoder) throws -> Void public init(_ value: T) { encodeValue = { try value.encode(to: $0) } } public func encode(to encoder: Encoder) throws { try encodeValue(encoder) } }