import Foundation // What Base's server answers the apps, decoded tolerantly: a field a newer // Base adds is ignored, and one an older Base leaves out takes its default, // so neither ends a session or empties a screen. The shapes are the plan's // Task 5 (`/api/v1/me`, `/api/v1/home`) and Ask's existing JSON // (internal/web/ask.go askStateJSON, ask_relay.go, internal/equipo/chat.go), // the same contract ask.js reads (docs/api/base-native-v1.md, Task 6). extension KeyedDecodingContainer { /// The value at `key`, or `fallback` when it is missing, null or of /// another type. func value(_ key: Key, _ fallback: T) -> T { ((try? decodeIfPresent(T.self, forKey: key)) ?? nil) ?? fallback } func optional(_ key: Key) -> T? { (try? decodeIfPresent(T.self, forKey: key)) ?? nil } /// An RFC 3339 time (Go's, with or without fractional seconds); nil when /// missing, empty or unreadable. func date(_ key: Key) -> Date? { BaseJSON.date(optional(key)) } /// An http(s) URL; nil when missing, empty or anything else. func webURL(_ key: Key) -> URL? { BaseJSON.webURL(optional(key)) } } public enum BaseJSON { public static func date(_ text: String?) -> Date? { guard let text, !text.isEmpty else { return nil } if let d = try? Date(text, strategy: .iso8601.year().month().day().time(includingFractionalSeconds: true).timeZone(separator: .omitted)) { return d } if let d = try? Date(text, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) { return d } return try? Date(text, strategy: .iso8601) } /// `equipo.WebURL`: an absolute http or https URL with a host and no /// user info, else nil. Links the server passes are already clean; this /// holds the apps to the same rule. public static func webURL(_ text: String?) -> URL? { guard let text, let c = URLComponents(string: text), let scheme = c.scheme?.lowercased(), scheme == "http" || scheme == "https", let host = c.host, !host.isEmpty, c.user == nil, c.password == nil, let url = c.url else { return nil } return url } } // MARK: /api/v1/me /// `GET /api/v1/me`: who is signed in, to which Base, and their Appearance. public struct Me: Decodable, Sendable, Equatable { public struct Member: Decodable, Sendable, Equatable { public var id = "", name = "", email = "", initials = "" public var owner = false public init(id: String = "", name: String = "", email: String = "", initials: String = "", owner: Bool = false) { self.id = id; self.name = name; self.email = email; self.initials = initials; self.owner = owner } enum CodingKeys: String, CodingKey { case id, name, email, initials, owner } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = c.value(.id, ""); name = c.value(.name, ""); email = c.value(.email, "") initials = c.value(.initials, ""); owner = c.value(.owner, false) } } public struct Base: Decodable, Sendable, Equatable { public var name = "", slug = "", timezone = "" public var origin: URL? public init(name: String = "", slug: String = "", origin: URL? = nil, timezone: String = "") { self.name = name; self.slug = slug; self.origin = origin; self.timezone = timezone } enum CodingKeys: String, CodingKey { case name, slug, origin, timezone } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) name = c.value(.name, ""); slug = c.value(.slug, ""); origin = c.webURL(.origin); timezone = c.value(.timezone, "") } /// Base's time zone, for when a job started; nil if unknown. public var timeZone: TimeZone? { TimeZone(identifier: timezone) } } public var member: Member public var base: Base public var appearance: BaseAppearance public var equipoOrigin: URL? public init(member: Member, base: Base, appearance: BaseAppearance = .system, equipoOrigin: URL? = nil) { self.member = member; self.base = base; self.appearance = appearance; self.equipoOrigin = equipoOrigin } enum CodingKeys: String, CodingKey { case member, base, appearance, equipoOrigin = "equipo_origin" } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) member = c.value(.member, Member()); base = c.value(.base, Base()) appearance = BaseAppearance(server: c.optional(.appearance)); equipoOrigin = c.webURL(.equipoOrigin) } } // MARK: /api/v1/home /// `GET /api/v1/home`: Home's greeting, its first steps and the apps, in /// Home's order (P6). public struct HomeData: Decodable, Sendable, Equatable { public struct Step: Decodable, Sendable, Equatable, Hashable { public var label: String public var done: Bool public init(label: String, done: Bool) { self.label = label; self.done = done } enum CodingKeys: String, CodingKey { case label, done } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) label = c.value(.label, ""); done = c.value(.done, false) } } public struct App: Decodable, Sendable, Equatable, Identifiable { public enum Kind: String, Sendable, Equatable { case oficina, installed, own, other } public var id: String public var kind: Kind public var name: String public var url: URL? public var iconURL: String? public var tint: String? public var iconSVG: String? public var bundleID: String? public var scheme: String? public init(id: String, kind: Kind, name: String, url: URL?, iconURL: String? = nil, tint: String? = nil, iconSVG: String? = nil, bundleID: String? = nil, scheme: String? = nil) { self.id = id; self.kind = kind; self.name = name; self.url = url; self.iconURL = iconURL self.tint = tint; self.iconSVG = iconSVG; self.bundleID = bundleID; self.scheme = scheme } enum CodingKeys: String, CodingKey { case id, kind, name, url, tint, scheme case iconURL = "icon_url", iconSVG = "icon_svg", bundleID = "bundle_id" } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = c.value(.id, ""); kind = Kind(rawValue: c.value(.kind, "")) ?? .other; name = c.value(.name, "") url = c.webURL(.url); iconURL = c.optional(.iconURL); tint = c.optional(.tint); iconSVG = c.optional(.iconSVG) bundleID = c.optional(.bundleID); scheme = c.optional(.scheme) } } public var greeting: String public var lede: String public var steps: [Step] public var apps: [App] enum CodingKeys: String, CodingKey { case greeting, lede, steps, apps } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) greeting = c.value(.greeting, ""); lede = c.value(.lede, "") steps = c.value(.steps, []); apps = c.value(.apps, []).filter { !$0.id.isEmpty } } } // MARK: Ask /// Ask's states (ask.go): `ready` shows the conversation; `norunner` and /// `oldrunner` show it with a note; the rest stand in its place. /// `not_linked` is the app's own (Task 7: Equipo doesn't know this person); /// anything a newer Base says that this app doesn't know is `unavailable`. public enum AskPhase: String, Sendable, Equatable, CaseIterable { case loading, connect, pending, reconnect, unavailable, ready, norunner, oldrunner case notLinked = "not_linked" public init(server value: String?) { self = value.flatMap(AskPhase.init(rawValue:)).flatMap { $0 == .loading ? nil : $0 } ?? .unavailable } /// The states that show the conversation (ask.js `chatting`). public var chatting: Bool { self == .ready || self == .norunner || self == .oldrunner } } /// One line of the conversation (equipo.Message). Role is `person` or the /// Assistant's. public struct AskMessage: Decodable, Sendable, Equatable, Identifiable { public var id: String public var role: String public var text: String public var turnID: String public var createdAt: Date? /// The files the person sent with it, in order (none for most). public var attachments: [AskAttachment] /// What the Assistant looked up on the web for its reply, in the order /// it did, drawn under its words (none on a person's message). public var lookups: [AskLookup] public var isPerson: Bool { role == "person" } public init(id: String, role: String, text: String, turnID: String = "", createdAt: Date? = nil, attachments: [AskAttachment] = [], lookups: [AskLookup] = []) { self.id = id; self.role = role; self.text = text; self.turnID = turnID; self.createdAt = createdAt; self.attachments = attachments self.lookups = lookups } enum CodingKeys: String, CodingKey { case id, role, text, turnID = "turn_id", createdAt = "created_at", attachments, lookups } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = c.value(.id, ""); role = c.value(.role, ""); text = c.value(.text, "") turnID = c.value(.turnID, ""); createdAt = c.date(.createdAt) attachments = c.value(.attachments, [AskAttachment]()).filter { !$0.id.isEmpty } lookups = role == "person" ? [] : c.value(.lookups, [AskLookup]()).filter { !$0.answer.isEmpty && !$0.sources.isEmpty } } } /// One thing the Assistant looked up for a reply (docs/api/base-native-v1.md, /// Lookup): a short answer, drawn with LookupMarkdown (never a link), and /// the pages it came from, each drawn as its title (a link) and its host. public struct AskLookup: Decodable, Sendable, Equatable { public var answer: String public var sources: [AskSource] public init(answer: String, sources: [AskSource]) { self.answer = answer; self.sources = sources } enum CodingKeys: String, CodingKey { case answer, sources } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) answer = c.value(.answer, "") sources = c.value(.sources, [AskSource]()).filter { $0.url != nil } } } /// A page a lookup's answer came from: https only (anything else has no /// url, and is dropped). public struct AskSource: Decodable, Sendable, Equatable { public var url: URL? public var title: String public init(url: URL?, title: String) { self.url = url; self.title = title } enum CodingKeys: String, CodingKey { case url, title } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) let u = c.webURL(.url) url = u?.scheme == "https" ? u : nil title = c.value(.title, "") } /// The host as the Sources line shows it, without "www." (sourceHost /// in ask_cards.go). public var host: String { let h = (url?.host ?? "").lowercased() return h.hasPrefix("www.") ? String(h.dropFirst(4)) : h } /// What the link says: the title, or the host without one. public var label: String { title.isEmpty ? host : title } } /// One of a message's files (docs/api/base-native-v1.md, Attachment). /// Until the app draws files (slice 2), only its name shows. A kind the /// app doesn't know is a file. public struct AskAttachment: Decodable, Sendable, Equatable { public var id: String public var kind: String public var name: String public var mediaType: String public var size: Int64 public var width: Int public var height: Int public var isImage: Bool { kind == "image" } public init(id: String, kind: String = "file", name: String, mediaType: String = "", size: Int64 = 0, width: Int = 0, height: Int = 0) { self.id = id; self.kind = kind; self.name = name; self.mediaType = mediaType; self.size = size; self.width = width; self.height = height } enum CodingKeys: String, CodingKey { case id, kind, name, mediaType = "media_type", size, width, height } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = c.value(.id, ""); name = c.value(.name, ""); mediaType = c.value(.mediaType, "") let k: String = c.value(.kind, "file") kind = k == "image" ? "image" : "file" size = c.value(.size, Int64(0)); width = c.value(.width, 0); height = c.value(.height, 0) } } /// The Assistant's answer to the person's messages (equipo.Turn). public struct AskTurn: Decodable, Sendable, Equatable { public var id: String public var kind: String public var state: String public var reason: String /// The reply's message id, when the server says it (ask.js reads it). public var replyID: String public init(id: String, kind: String = "", state: String, reason: String = "", replyID: String = "") { self.id = id; self.kind = kind; self.state = state; self.reason = reason; self.replyID = replyID } enum CodingKeys: String, CodingKey { case id, kind, state, reason, replyID = "reply_id" } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = c.value(.id, ""); kind = c.value(.kind, ""); state = c.value(.state, "") reason = c.value(.reason, ""); replyID = c.value(.replyID, "") } /// replied, failed and cancelled end a turn. public var ended: Bool { state == "replied" || state == "failed" || state == "cancelled" } /// A team_update turn is the Assistant taking a job's news by itself: /// quiet, with no status, activity or Stop. public var quiet: Bool { kind == "team_update" } } /// Something in the conversation to act on (equipo.Card): a question, /// confirm, outcome or connect card, or a job (`kind` "job"). public struct AskCard: Decodable, Sendable, Equatable, Identifiable { public struct Option: Decodable, Sendable, Equatable, Hashable { public var value: String public var label: String public init(value: String, label: String) { self.value = value; self.label = label } enum CodingKeys: String, CodingKey { case value, label } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) value = c.value(.value, ""); label = c.value(.label, "") } } public struct Link: Decodable, Sendable, Equatable, Hashable { public var label: String public var url: URL? public var rel: String public init(label: String, url: URL?, rel: String = "") { self.label = label; self.url = url; self.rel = rel } enum CodingKeys: String, CodingKey { case label, url, rel } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) label = c.value(.label, ""); url = c.webURL(.url); rel = c.value(.rel, "") } } public var id: String public var revision: Int64 public var kind: String public var state: String public var question: String public var options: [Option] public var links: [Link] public var result: String public var job: String public var detail: String public var startedAt: Date? public var turnID: String /// A paused job offers "Carry on now" (`carry_on`; Base sends it on a /// paused or stopped job card only). public var carryOn: Bool public init(id: String, revision: Int64 = 1, kind: String, state: String, question: String = "", options: [Option] = [], links: [Link] = [], result: String = "", job: String = "", detail: String = "", startedAt: Date? = nil, turnID: String = "", carryOn: Bool = false) { self.id = id; self.revision = revision; self.kind = kind; self.state = state; self.question = question self.options = options; self.links = links; self.result = result; self.job = job; self.detail = detail self.startedAt = startedAt; self.turnID = turnID; self.carryOn = carryOn } enum CodingKeys: String, CodingKey { case id, revision, kind, state, question, options, links, result, job, detail case startedAt = "started_at", turnID = "turn_id", carryOn = "carry_on" } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = c.value(.id, ""); revision = c.value(.revision, 0); kind = c.value(.kind, ""); state = c.value(.state, "") question = c.value(.question, ""); options = c.value(.options, []).filter { !$0.value.isEmpty } links = c.value(.links, []).filter { $0.url != nil }; result = c.value(.result, "") job = c.value(.job, ""); detail = c.value(.detail, ""); startedAt = c.date(.startedAt); turnID = c.value(.turnID, "") carryOn = c.value(.carryOn, false) } public var isOpen: Bool { state == "open" } public var isJob: Bool { kind == "job" } public var jobState: JobState? { isJob ? JobState(rawValue: state) : nil } /// A paused job that offers "Carry on now", or a stopped one held /// while building was off, once it is on again. public var offersCarryOn: Bool { (jobState == .paused || jobState == .stopped) && carryOn } /// The kinds drawn as cards (ask.js `kinds`). public static let drawnKinds: Set = ["question", "confirm", "outcome", "connect"] /// Where to see a job's work once there is something to see (ready, /// done): its first link with no rel. public var go: Link? { guard isJob, state == "ready" || state == "done" else { return nil } return links.first { $0.rel.isEmpty } } /// The job's own page in Equipo (rel "equipo"): the job view's title. public var equipoLink: Link? { isJob ? links.first { $0.rel == "equipo" } : nil } /// An open connect card's link to Base's own connect page. public var connectLink: Link? { kind == "connect" ? links.first { $0.rel == "oficina_connect" } : nil } } /// A job as `/ask/state` lists it: its card, with the cards that belong /// to it (jobView in ask.go). public struct AskJob: Decodable, Sendable, Equatable { public var card: AskCard public var cards: [AskCard] public init(card: AskCard, cards: [AskCard] = []) { self.card = card; self.cards = cards } enum CodingKeys: String, CodingKey { case cards } public init(from decoder: Decoder) throws { card = try AskCard(from: decoder) cards = try decoder.container(keyedBy: CodingKeys.self).value(.cards, []) } } /// `GET /ask/state`: what the conversation draws, and the cursor its event /// stream starts after. `renew_after` and `equipo_origin` are Task 7's. public struct AskSnapshot: Decodable, Sendable, Equatable { public var state: AskPhase public var messages: [AskMessage] public var jobs: [AskJob] public var cards: [AskCard] public var turn: AskTurn? public var status: String public var cursor: Int64 public var renewAfter: Date? public var equipoOrigin: URL? /// The member disconnected Ask (on any client) and hasn't set it up /// again: no set-up by itself. Nil from a Base that doesn't say. public var disconnected: Bool? enum CodingKeys: String, CodingKey { case state, messages, jobs, cards, turn, status, cursor, disconnected case renewAfter = "renew_after", equipoOrigin = "equipo_origin" } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) state = AskPhase(server: c.optional(.state)); messages = c.value(.messages, []).filter { !$0.id.isEmpty } jobs = c.value(.jobs, []); cards = c.value(.cards, []).filter { !$0.id.isEmpty } turn = c.optional(.turn).flatMap { (t: AskTurn) in t.id.isEmpty ? nil : t } status = c.value(.status, ""); cursor = c.value(.cursor, 0) renewAfter = c.date(.renewAfter); equipoOrigin = c.webURL(.equipoOrigin) disconnected = c.optional(.disconnected) } } /// `POST /ask/messages`'s answer: the person's message and the turn it /// started (equipo.Sent). public struct AskSent: Decodable, Sendable, Equatable { public var message: AskMessage? public var turn: AskTurn? enum CodingKeys: String, CodingKey { case message, turn } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) message = c.optional(.message).flatMap { (m: AskMessage) in m.id.isEmpty ? nil : m } turn = c.optional(.turn).flatMap { (t: AskTurn) in t.id.isEmpty ? nil : t } } } /// `POST /ask/cards/{id}/answer`'s answer: the card as it is now, and the /// message and turn the answer started (both null for an outcome card). public struct AskAnswered: Decodable, Sendable, Equatable { public var card: AskCard? public var message: AskMessage? public var turn: AskTurn? enum CodingKeys: String, CodingKey { case card, message, turn } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) card = c.optional(.card).flatMap { (k: AskCard) in k.id.isEmpty ? nil : k } message = c.optional(.message).flatMap { (m: AskMessage) in m.id.isEmpty ? nil : m } turn = c.optional(.turn).flatMap { (t: AskTurn) in t.id.isEmpty ? nil : t } } } /// `POST /ask/cards/{id}/carry_on`'s answer: the job card as it is now. public struct AskCarriedOn: Decodable, Sendable, Equatable { public var card: AskCard? enum CodingKeys: String, CodingKey { case card } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) card = c.optional(.card).flatMap { (k: AskCard) in k.id.isEmpty ? nil : k } } } /// `POST /api/v1/ask/oficina`'s answer (Task 7): `ready` with when to renew, /// or `not_linked`. public struct AskSetupAnswer: Decodable, Sendable, Equatable { public var state: AskPhase public var renewAfter: Date? enum CodingKeys: String, CodingKey { case state, renewAfter = "renew_after" } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) state = AskPhase(server: c.optional(.state)); renewAfter = c.date(.renewAfter) } }