// // MicropubCategories.swift // Museion // // #207: the blog's own categories — the list the publish sheet // offers as suggestions for the piece's `category:` line. One // query, no writes: naming a category Micro.blog doesn't know // CREATES it when the post is sent (the create/update carry the // list — Micropub.swift and the codec in PostFrontmatter.swift), // so there is no separate create call here. // // Wire facts (microblog.dev/api/posting, book.micro.blog/micropub): // `GET /micropub?q=category` answers the blog's categories as a // root `categories` string array; some answers carry the richer // `microblog-categories` objects (`name` + `url`) instead. A 2xx // with neither is a blog without categories — no suggestions is // not an error, and neither is any failure: the sheet stays silent // (a typed new name still creates the category at the send, and a // rejected token surfaces on the send itself). // import Foundation nonisolated extension Micropub { /// `GET ?q=category` — the config query's shape. static func makeCategoryListRequest(token: String) -> URLRequest { queryRequest("category", token: token) } /// The blog's categories for the sheet's suggestions — trimmed, /// empties dropped; `[]` on any failure or non-2xx (there is no /// error to surface — see the header). static func blogCategories(token: String, transport: Transport = urlSessionTransport) async -> [String] { guard let (data, response) = try? await transport(makeCategoryListRequest(token: token)), (200 ..< 300).contains(response.statusCode) else { return [] } return categoryNames(in: data) } /// The root `categories` strings, else the `microblog-categories` /// objects' `name` fields. private static func categoryNames(in data: Data) -> [String] { let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] let names = (root["categories"] as? [String]) ?? (root["microblog-categories"] as? [[String: Any]])?.compactMap { $0["name"] as? String } ?? [] return names.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty } } }