SPB Git

Repository Public

NotesAPI.swift 24.5 KB 435 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/NotesAPI.swift3// Description: The typed endpoints of the backend, one method per route of the contract: change feed, pages,4//              versions, tags, attachments, authentication, AI streams, search, tasks, inbox, capture, health.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// Typed access to every route the native apps use. A value type around the shared `HTTPClient`: cheap to copy,11/// safe to use from any task.12public struct NotesAPI: Sendable {13    public let client: HTTPClient1415    public init(client: HTTPClient) {16        self.client = client17    }1819    /// A new lower-case UUID for a page or an attachment created on the device.20    public static func newID() -> String { UUID().uuidString.lowercased() }2122    /// A new idempotency key (`[A-Za-z0-9_-]{8,100}`). Keep it with the pending operation and send it again on a retry.23    public static func newIdempotencyKey() -> String { "spn-" + UUID().uuidString.lowercased() }2425    private static func seg(_ id: String) -> String { HTTPRequest.segment(id) }2627    // MARK: - Change feed2829    /// `GET /api/sync` — changes after `since` (0 = full copy). Call again with `cursor` while `more`; start again30    /// from 0 when `reset`.31    /// - Parameter limit: 1…500 (server default 200).32    public func sync(since: Int64, limit: Int? = nil) async throws -> SyncPage {33        var query = [URLQueryItem(name: "since", value: String(since))]34        if let limit { query.append(URLQueryItem(name: "limit", value: String(limit))) }35        return try await client.decode(SyncPage.self, .get("/api/sync", query: query))36    }3738    // MARK: - Pages3940    /// `POST /api/pages` — creates a page. With a `draft.id` that already exists (even in the trash) the stored page41    /// is returned untouched and `existing` is `true`.42    ///43    /// Note: when the answer is an idempotent replay (same `idempotencyKey`), the server does not repeat the44    /// `x-existing` header; `existing` is then `false` although nothing new was created.45    public func createPage(_ draft: PageDraft = PageDraft(), idempotencyKey: String? = nil) async throws -> Created<Page> {46        let response = try await client.send(.json(.post, "/api/pages", body: draft, idempotencyKey: idempotencyKey))47        return Created(value: try response.decode(Page.self), existing: response.isExisting)48    }4950    /// `GET /api/pages/<id>` — the row with its breadcrumb and backlinks (trashed pages included).51    /// - Parameter open: `true` records the visit (`lastOpenedAt`; not a change in the feed).52    public func page(id: String, open: Bool = false) async throws -> PageDetail {53        try await client.decode(PageDetail.self, .get("/api/pages/\(Self.seg(id))", query: open ? [URLQueryItem(name: "open", value: "1")] : []))54    }5556    /// `GET /api/pages/<id>?head=1` — version and dates only.57    public func pageHead(id: String) async throws -> PageHead {58        try await client.decode(PageHead.self, .get("/api/pages/\(Self.seg(id))", query: [URLQueryItem(name: "head", value: "1")]))59    }6061    /// `PATCH /api/pages/<id>`. Throws `APIError.conflict(server:message:)` when `patch.baseVersion` is no longer the62    /// version of the page (nothing is written).63    public func patchPage(id: String, _ patch: PagePatch, idempotencyKey: String? = nil) async throws -> PagePatchResult {64        try await client.decode(PagePatchResult.self, .json(.patch, "/api/pages/\(Self.seg(id))", body: patch, idempotencyKey: idempotencyKey))65    }6667    private struct ResolveBody: Encodable {68        var choice: ConflictChoice69        var serverVersion: Int70        var mine: ConflictMine71    }7273    /// `POST /api/pages/<id>/resolve` — settles a conflict; both copies survive in the server history. Throws74    /// `APIError.conflict` again if the page moved since `serverVersion`.75    public func resolveConflict(pageID: String, choice: ConflictChoice, serverVersion: Int, mine: ConflictMine, idempotencyKey: String? = nil) async throws -> ResolvedPage {76        let body = ResolveBody(choice: choice, serverVersion: serverVersion, mine: mine)77        return try await client.decode(ResolvedPage.self, .json(.post, "/api/pages/\(Self.seg(pageID))/resolve", body: body, idempotencyKey: idempotencyKey))78    }7980    /// `DELETE /api/pages/<id>` — moves the page and its descendants to the trash.81    @discardableResult82    public func trashPage(id: String, idempotencyKey: String? = nil) async throws -> TrashResult {83        try await client.decode(TrashResult.self, HTTPRequest(method: .delete, path: "/api/pages/\(Self.seg(id))", idempotencyKey: idempotencyKey))84    }8586    /// `DELETE /api/pages/<id>?purge=1` — permanent. Needs a fresh passkey verification: `APIError.needsReauth`.87    @discardableResult88    public func purgePage(id: String) async throws -> OKResult {89        try await client.decode(OKResult.self, HTTPRequest(method: .delete, path: "/api/pages/\(Self.seg(id))", query: [URLQueryItem(name: "purge", value: "1")]))90    }9192    /// `DELETE /api/trash[?olderThanDays=N]` — permanently deletes the trashed pages (all of them when `olderThanDays`93    /// is `nil`). Needs a fresh passkey verification.94    @discardableResult95    public func emptyTrash(olderThanDays: Int? = nil) async throws -> PurgeResult {96        let query = olderThanDays.map { [URLQueryItem(name: "olderThanDays", value: String($0))] } ?? []97        return try await client.decode(PurgeResult.self, HTTPRequest(method: .delete, path: "/api/trash", query: query))98    }99100    /// `POST /api/pages/<id>?action=restore` — takes the page out of the trash.101    @discardableResult102    public func restorePage(id: String, idempotencyKey: String? = nil) async throws -> OKResult {103        try await client.decode(OKResult.self, HTTPRequest(method: .post, path: "/api/pages/\(Self.seg(id))", query: [URLQueryItem(name: "action", value: "restore")], idempotencyKey: idempotencyKey))104    }105106    /// `POST /api/pages/<id>?action=duplicate` — returns the new page ("… (copy)").107    public func duplicatePage(id: String, idempotencyKey: String? = nil) async throws -> Page {108        try await client.decode(Page.self, HTTPRequest(method: .post, path: "/api/pages/\(Self.seg(id))", query: [URLQueryItem(name: "action", value: "duplicate")], idempotencyKey: idempotencyKey))109    }110111    // MARK: - Versions112113    /// `GET /api/pages/<id>/versions` — the history, newest first (≤ 200).114    public func pageVersions(pageID: String) async throws -> [PageVersionSummary] {115        try await client.decode([PageVersionSummary].self, .get("/api/pages/\(Self.seg(pageID))/versions"))116    }117118    /// `GET /api/pages/<id>/versions?v=<n>` — one full snapshot.119    public func pageVersion(pageID: String, version: Int) async throws -> PageVersionSnapshot {120        try await client.decode(PageVersionSnapshot.self, .get("/api/pages/\(Self.seg(pageID))/versions", query: [URLQueryItem(name: "v", value: String(version))]))121    }122123    private struct VersionBody: Encodable { var version: Int }124125    /// `POST /api/pages/<id>/versions` — restores a snapshot (the current state is kept in the history).126    public func restorePageVersion(pageID: String, version: Int, idempotencyKey: String? = nil) async throws -> VersionRestoreResult {127        try await client.decode(VersionRestoreResult.self, .json(.post, "/api/pages/\(Self.seg(pageID))/versions", body: VersionBody(version: version), idempotencyKey: idempotencyKey))128    }129130    // MARK: - Tags131132    /// `GET /api/pages/<id>/tags`.133    public func pageTags(pageID: String) async throws -> [String] {134        try await client.decode([String].self, .get("/api/pages/\(Self.seg(pageID))/tags"))135    }136137    private struct TagsBody: Encodable { var tags: [String] }138139    /// `PUT /api/pages/<id>/tags` — replaces the tags; returns them normalised (trimmed, no `#`, lower-case, ≤ 40140    /// characters, ≤ 20 tags).141    public func setPageTags(pageID: String, tags: [String], idempotencyKey: String? = nil) async throws -> [String] {142        try await client.decode([String].self, .json(.put, "/api/pages/\(Self.seg(pageID))/tags", body: TagsBody(tags: tags), idempotencyKey: idempotencyKey))143    }144145    /// `GET /api/tags` — the tags of the workspace.146    public func tags() async throws -> [TagSummary] {147        try await client.decode([TagSummary].self, .get("/api/tags"))148    }149150    // MARK: - Attachments151152    /// `POST /api/attachments` — uploads a file from disk (≤ 200 MB). The multipart body is assembled in a temporary153    /// file and streamed: nothing is loaded in memory. Cancelling the calling task cancels the upload.154    /// - Parameters:155    ///   - id: UUID chosen by the client; if it already exists the stored attachment is returned (`existing`).156    ///   - filename: defaults to the last path component of `fileURL`.157    ///   - mimeType: defaults to a type derived from the file extension.158    ///   - progress: called on a background queue.159    public func uploadAttachment(fileURL: URL, id: String? = nil, pageID: String? = nil, filename: String? = nil, mimeType: String? = nil, progress: TransferProgressHandler? = nil) async throws -> Created<UploadedAttachment> {160        let name = filename ?? fileURL.lastPathComponent161        let form = MultipartForm()162        var fields: [MultipartForm.Field] = []163        if let id { fields.append(.init("id", id)) }164        if let pageID { fields.append(.init("pageId", pageID)) }165        let body = FileManager.default.temporaryDirectory.appendingPathComponent("spnotes-upload-\(UUID().uuidString).multipart")166        defer { try? FileManager.default.removeItem(at: body) }167        try form.write(fields: fields, fileField: "file", filename: name, mimeType: mimeType ?? MultipartForm.mimeType(forFilename: name), source: fileURL, to: body)168        let request = HTTPRequest(method: .post, path: "/api/attachments", contentType: form.contentType)169        let response = try await client.upload(request, fromFile: body, progress: progress)170        return Created(value: try response.decode(UploadedAttachment.self), existing: response.isExisting)171    }172173    /// `GET /api/attachments[?pageId=]`.174    public func attachments(pageID: String? = nil) async throws -> [AttachmentInfo] {175        let query = pageID.map { [URLQueryItem(name: "pageId", value: $0)] } ?? []176        return try await client.decode([AttachmentInfo].self, .get("/api/attachments", query: query))177    }178179    /// `DELETE /api/attachments?id=<id>` — soft delete (the feed then reports the attachment with `deletedAt`).180    @discardableResult181    public func deleteAttachment(id: String, idempotencyKey: String? = nil) async throws -> OKResult {182        try await client.decode(OKResult.self, HTTPRequest(method: .delete, path: "/api/attachments", query: [URLQueryItem(name: "id", value: id)], idempotencyKey: idempotencyKey))183    }184185    /// `GET /api/files/<id>` — downloads the bytes to `destination` (replaced if it exists), streamed to disk.186    /// Cancelling the calling task cancels the download.187    public func downloadFile(id: String, to destination: URL, progress: TransferProgressHandler? = nil) async throws -> DownloadedFile {188        let response = try await client.download(.get(Self.filePath(id: id)), to: destination, progress: progress)189        return DownloadedFile(190            fileURL: destination,191            contentType: response.contentType,192            expectedSize: response.header("content-length").flatMap(Int64.init),193            suggestedFilename: response.header("content-disposition").flatMap(Self.filename(fromContentDisposition:))194        )195    }196197    /// `/api/files/<id>` — the `src` of image and file nodes.198    public static func filePath(id: String) -> String { "/api/files/\(seg(id))" }199200    /// The attachment id of a `src` such as `/api/files/<id>` (also accepts an absolute URL).201    public static func fileID(fromSource source: String) -> String? {202        guard let range = source.range(of: "/api/files/") else { return nil }203        let tail = source[range.upperBound...]204        let id = tail.prefix { $0 != "/" && $0 != "?" && $0 != "#" }205        return id.isEmpty ? nil : String(id)206    }207208    static func filename(fromContentDisposition header: String) -> String? {209        for part in header.components(separatedBy: ";").map({ $0.trimmingCharacters(in: .whitespaces) }) {210            if part.lowercased().hasPrefix("filename*=") {211                let value = part.dropFirst("filename*=".count)212                if let quote = value.range(of: "''") { return String(value[quote.upperBound...]).removingPercentEncoding }213            }214        }215        for part in header.components(separatedBy: ";").map({ $0.trimmingCharacters(in: .whitespaces) }) {216            if part.lowercased().hasPrefix("filename=") {217                return part.dropFirst("filename=".count).trimmingCharacters(in: CharacterSet(charactersIn: "\""))218            }219        }220        return nil221    }222223    // MARK: - Authentication224225    private func requestOptions(_ path: String, _ kind: PasskeyCeremony.Kind) async throws -> PasskeyRequestOptions {226        let response = try await client.send(HTTPRequest(method: .post, path: path, ceremony: .begin(kind.rawValue)))227        do { return try PasskeyCeremony.decodeRequestOptions(response.data) } catch { throw APIError.decoding(String(describing: error)) }228    }229230    private func verifyAssertion<T: Decodable & Sendable>(_ path: String, _ kind: PasskeyCeremony.Kind, _ credential: PasskeyAssertionCredential) async throws -> T {231        let body: Data232        do { body = try PasskeyCeremony.assertionVerifyBody(credential) } catch { throw APIError.decoding("request body: \(error)") }233        return try await client.decode(T.self, HTTPRequest(method: .post, path: path, body: body, contentType: "application/json", ceremony: .complete(kind.rawValue)))234    }235236    /// `POST /api/auth/login/options` (public) — starts a sign-in. `409 not_enrolled` when the account has no passkey.237    public func loginOptions() async throws -> PasskeyRequestOptions {238        try await requestOptions("/api/auth/login/options", .login)239    }240241    /// `POST /api/auth/login/verify` (public) — on success the transport stores the session token of the answer.242    public func loginVerify(_ credential: PasskeyAssertionCredential) async throws -> LoginResult {243        try await verifyAssertion("/api/auth/login/verify", .login, credential)244    }245246    /// `POST /api/auth/reauth/options` — starts a step-up.247    public func reauthOptions() async throws -> PasskeyRequestOptions {248        try await requestOptions("/api/auth/reauth/options", .reauth)249    }250251    /// `POST /api/auth/reauth/verify` — the session becomes "fresh" and its token is rotated (stored by the transport).252    public func reauthVerify(_ credential: PasskeyAssertionCredential) async throws -> ReauthResult {253        try await verifyAssertion("/api/auth/reauth/verify", .reauth, credential)254    }255256    /// `GET /api/auth/state`.257    public func authState() async throws -> AuthState {258        try await client.decode(AuthState.self, .get("/api/auth/state"))259    }260261    /// `POST /api/auth/logout` — revokes the session on the server (always 200). The transport forgets the token when262    /// the server clears the cookie; `AuthService.signOut()` also clears it locally whatever happens.263    @discardableResult264    public func logout() async throws -> OKResult {265        try await client.decode(OKResult.self, HTTPRequest(method: .post, path: "/api/auth/logout"))266    }267268    /// `GET /api/auth/sessions`.269    public func sessions() async throws -> [SessionInfo] {270        try await client.decode([SessionInfo].self, .get("/api/auth/sessions"))271    }272273    /// `DELETE /api/auth/sessions/<id>` — revokes one session (the server asks for a fresh passkey verification:274    /// `APIError.needsReauth`).275    @discardableResult276    public func revokeSession(id: String) async throws -> OKResult {277        try await client.decode(OKResult.self, HTTPRequest(method: .delete, path: "/api/auth/sessions/\(Self.seg(id))"))278    }279280    private struct RevokeAllBody: Encodable { var includeCurrent: Bool }281282    /// `DELETE /api/auth/sessions` — revokes every session (needs a fresh passkey verification).283    /// - Parameter includeCurrent: also ends this session (the transport then emits the signed-out event).284    @discardableResult285    public func revokeAllSessions(includeCurrent: Bool = false) async throws -> RevokeSessionsResult {286        try await client.decode(RevokeSessionsResult.self, .json(.delete, "/api/auth/sessions", body: RevokeAllBody(includeCurrent: includeCurrent)))287    }288289    /// `GET /api/auth/passkeys`.290    public func passkeys() async throws -> [PasskeyInfo] {291        try await client.decode([PasskeyInfo].self, .get("/api/auth/passkeys"))292    }293294    /// `POST /api/auth/passkeys/options` — starts the creation of an additional passkey (fresh verification needed).295    public func passkeyRegistrationOptions() async throws -> PasskeyCreationOptions {296        let response = try await client.send(HTTPRequest(method: .post, path: "/api/auth/passkeys/options", ceremony: .begin(PasskeyCeremony.Kind.register.rawValue)))297        do { return try PasskeyCeremony.decodeCreationOptions(response.data) } catch { throw APIError.decoding(String(describing: error)) }298    }299300    /// `POST /api/auth/passkeys/verify` — stores the new passkey (fresh verification needed).301    public func passkeyRegistrationVerify(_ credential: PasskeyRegistrationCredential, label: String? = nil) async throws -> PasskeyAdded {302        let body: Data303        do { body = try PasskeyCeremony.registrationVerifyBody(credential, label: label) } catch { throw APIError.decoding("request body: \(error)") }304        return try await client.decode(PasskeyAdded.self, HTTPRequest(method: .post, path: "/api/auth/passkeys/verify", body: body, contentType: "application/json", ceremony: .complete(PasskeyCeremony.Kind.register.rawValue)))305    }306307    private struct LabelBody: Encodable { var label: String }308309    /// `PATCH /api/auth/passkeys/<id>` — renames a passkey.310    public func renamePasskey(id: String, label: String) async throws {311        _ = try await client.send(.json(.patch, "/api/auth/passkeys/\(Self.seg(id))", body: LabelBody(label: label)))312    }313314    /// `DELETE /api/auth/passkeys/<id>` — `409 last_passkey` for the only passkey of the account.315    public func deletePasskey(id: String) async throws {316        _ = try await client.send(HTTPRequest(method: .delete, path: "/api/auth/passkeys/\(Self.seg(id))"))317    }318319    // MARK: - AI320321    /// `POST /api/ai/action` — an inline action on a selection, streamed.322    ///323    /// Errors raised before the stream starts are thrown by this call: `APIError.confirmExpensive(plan:message:)`324    /// (send again with `confirmExpensive: true`), `503 not_configured | no_model`, `400`. Once the stream runs,325    /// provider failures arrive as `.error` events. The stream ends after `data: [DONE]`. Cancelling the task that326    /// iterates the stream (or dropping the stream) closes the connection; the server stops the generation.327    public func aiAction(_ request: AIActionRequest) async throws -> AsyncThrowingStream<AIEvent, Error> {328        try await eventStream(.json(.post, "/api/ai/action", body: request))329    }330331    /// `POST /api/ai/chat` — a chat turn, streamed (`meta`, `text`, `done`, `error`, `needs_confirmation`).332    /// Same error and cancellation rules as `aiAction`.333    public func aiChat(_ request: AIChatRequest) async throws -> AsyncThrowingStream<AIEvent, Error> {334        try await eventStream(.json(.post, "/api/ai/chat", body: request))335    }336337    private func eventStream(_ request: HTTPRequest) async throws -> AsyncThrowingStream<AIEvent, Error> {338        let (_, bytes) = try await client.openStream(request)339        return Self.events(from: bytes)340    }341342    /// Turns the bytes of a `text/event-stream` answer into AI events (ends at `[DONE]` or when the server closes).343    static func events<Bytes: AsyncSequence & Sendable>(from bytes: Bytes) -> AsyncThrowingStream<AIEvent, Error> where Bytes.Element == UInt8 {344        AsyncThrowingStream(bufferingPolicy: .unbounded) { continuation in345            let reader = Task {346                var parser = SSEParser()347                do {348                    for try await byte in bytes {349                        guard let event = parser.feed(byte: byte) else { continue }350                        if event.isDone { continuation.finish(); return }351                        if let ai = AIEvent(json: Data(event.data.utf8)) { continuation.yield(ai) }352                    }353                    if let event = parser.finish(), !event.isDone, let ai = AIEvent(json: Data(event.data.utf8)) { continuation.yield(ai) }354                    continuation.finish()355                } catch {356                    continuation.finish(throwing: APIError.fromTransport(error))357                }358            }359            continuation.onTermination = { _ in reader.cancel() }360        }361    }362363    // MARK: - Search364365    /// `GET /api/search` — server-side search (the optional online complement of the local index).366    public func search(_ query: SearchQuery) async throws -> [SearchHit] {367        var items = [URLQueryItem(name: "q", value: query.text), URLQueryItem(name: "mode", value: query.mode.rawValue)]368        if let limit = query.limit { items.append(URLQueryItem(name: "limit", value: String(limit))) }369        if let semantic = query.semantic { items.append(URLQueryItem(name: "semantic", value: semantic ? "1" : "0")) }370        if let section = query.section { items.append(URLQueryItem(name: "section", value: section.rawValue)) }371        if let since = query.since { items.append(URLQueryItem(name: "since", value: since)) }372        if let until = query.until { items.append(URLQueryItem(name: "until", value: until)) }373        if query.includeArchived { items.append(URLQueryItem(name: "archived", value: "1")) }374        if let kinds = query.kinds, !kinds.isEmpty { items.append(URLQueryItem(name: "kinds", value: kinds.joined(separator: ","))) }375        if query.group { items.append(URLQueryItem(name: "group", value: "1")) }376        return try await client.decode([SearchHit].self, .get("/api/search", query: items))377    }378379    // MARK: - Tasks380381    /// `GET /api/tasks[?done=1]` — open tasks, plus the done ones when `includeDone`.382    public func tasks(includeDone: Bool = false) async throws -> [TaskItem] {383        try await client.decode([TaskItem].self, .get("/api/tasks", query: includeDone ? [URLQueryItem(name: "done", value: "1")] : []))384    }385386    /// `POST /api/tasks`.387    public func createTask(_ draft: TaskDraft, idempotencyKey: String? = nil) async throws -> TaskItem {388        try await client.decode(TaskItem.self, .json(.post, "/api/tasks", body: draft, idempotencyKey: idempotencyKey))389    }390391    /// `PATCH /api/tasks`.392    public func updateTask(_ patch: TaskPatch, idempotencyKey: String? = nil) async throws -> TaskItem {393        try await client.decode(TaskItem.self, .json(.patch, "/api/tasks", body: patch, idempotencyKey: idempotencyKey))394    }395396    /// `DELETE /api/tasks?id=`.397    @discardableResult398    public func deleteTask(id: String, idempotencyKey: String? = nil) async throws -> OKResult {399        try await client.decode(OKResult.self, HTTPRequest(method: .delete, path: "/api/tasks", query: [URLQueryItem(name: "id", value: id)], idempotencyKey: idempotencyKey))400    }401402    // MARK: - Inbox and capture403404    /// `GET /api/inbox` — the captures waiting for triage.405    public func inbox() async throws -> [InboxItem] {406        try await client.decode([InboxItem].self, .get("/api/inbox"))407    }408409    /// `POST /api/inbox/<id>` — triages one capture.410    public func triageInboxItem(id: String, _ action: InboxAction, idempotencyKey: String? = nil) async throws -> TriageResult {411        try await client.decode(TriageResult.self, .json(.post, "/api/inbox/\(Self.seg(id))", body: action, idempotencyKey: idempotencyKey))412    }413414    private struct UndoBody: Encodable { var actionId: String }415416    /// `POST /api/inbox/undo` — reverses a triage.417    @discardableResult418    public func undoInboxAction(actionID: String) async throws -> UndoResult {419        try await client.decode(UndoResult.self, .json(.post, "/api/inbox/undo", body: UndoBody(actionId: actionID)))420    }421422    /// `POST /api/capture` — one new page in the inbox. Always give an idempotency key when the capture may be423    /// replayed from an offline queue.424    public func capture(_ request: CaptureRequest, idempotencyKey: String? = nil) async throws -> CaptureResult {425        try await client.decode(CaptureResult.self, .json(.post, "/api/capture", body: request, idempotencyKey: idempotencyKey))426    }427428    // MARK: - Health429430    /// `GET /api/health` (public).431    public func health() async throws -> Health {432        try await client.decode(Health.self, .get("/api/health"))433    }434}435
Files main
Menu

Theme