SPB Git

Repository Public

NextCoreModels.swift 10.9 KB 258 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/NextCoreModels.swift3// Description: Models of the 3.0 foundation the sync engine relies on (API-NEXT §1, §3, §4.2, §4.8): server meta and4//              feature flags, entity rows of the change feed, tasks with client ids, canvases with their 409 copy.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910// MARK: - Meta1112/// The feature flags of `GET /api/meta`. Gate UI and engine behaviour on these, never on the version string.13public enum ServerFeature {14    public static let entities = "entities"15    public static let tasksV2 = "tasks-v2"16    public static let events = "events"17    public static let timeMachine = "timemachine"18    public static let graphV2 = "graph-v2"19    public static let insights = "insights"20    public static let canvas = "canvas"21    public static let health = "health"22    public static let brief = "brief"23    public static let query = "query"24    public static let zoom = "zoom"25    public static let nodesV3 = "nodes-v3"26    public static let filesRange = "files-range"27    /// The Thought Constellation projection (`GET /api/graph/constellation`); not on every 3.0 server.28    public static let constellation = "constellation"29}3031/// `GET /api/meta`. A 2.x server has no such route: `NotesAPI.meta()` then returns `.legacy`.32public struct ServerMeta: Codable, Sendable, Equatable {33    /// API level: 3 for the Next Generation backend, 2 for anything older.34    public var api: Int35    public var version: String36    public var features: [String]37    public var serverTime: Date?3839    public init(api: Int, version: String, features: [String], serverTime: Date? = nil) {40        self.api = api41        self.version = version42        self.features = features43        self.serverTime = serverTime44    }4546    public init(from decoder: Decoder) throws {47        let c = try decoder.container(keyedBy: CodingKeys.self)48        api = try c.decodeIfPresent(Int.self, forKey: .api) ?? 249        version = try c.decodeIfPresent(String.self, forKey: .version) ?? ""50        features = try c.decodeIfPresent([String].self, forKey: .features) ?? []51        serverTime = try c.decodeIfPresent(Date.self, forKey: .serverTime)52    }5354    /// What a 2.x server is taken for (`404` on `/api/meta`).55    public static let legacy = ServerMeta(api: 2, version: "2.x", features: [])5657    public func has(_ feature: String) -> Bool { features.contains(feature) }58}5960// MARK: - Entity feed6162/// One row of `entities.<kind>` in `GET /api/sync?kinds=…`: the whole row is kept as raw JSON (unknown keys63/// included); `id`, `rev` and `deletedAt` are lifted for the engine.64public struct SyncEntityRow: Codable, Sendable, Equatable, Identifiable {65    public var id: String66    public var rev: Int6467    /// Soft-deleted rows (tasks, databases, database rows, references) stay in the feed with a date here.68    public var deletedAt: Date?69    public var updatedAt: Date?70    /// The complete row as the server sent it (canonical key order).71    public var json: RawJSON7273    public init(id: String, rev: Int64, deletedAt: Date? = nil, updatedAt: Date? = nil, json: RawJSON) {74        self.id = id75        self.rev = rev76        self.deletedAt = deletedAt77        self.updatedAt = updatedAt78        self.json = json79    }8081    public init(from decoder: Decoder) throws {82        let value = try JSONValue(from: decoder)83        guard let id = value["id"]?.stringValue else {84            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "entity row without id"))85        }86        self.id = id87        switch value["rev"] {88        case .int(let n)?: rev = n89        case .double(let d)?: rev = Int64(d)90        default: rev = 091        }92        deletedAt = value["deletedAt"]?.stringValue.flatMap(APIDate.parse)93        updatedAt = value["updatedAt"]?.stringValue.flatMap(APIDate.parse)94        json = value.raw()95    }9697    public func encode(to encoder: Encoder) throws { try json.encode(to: encoder) }9899    /// Decodes the row into a typed model (`TaskItem`, …).100    public func decode<T: Decodable>(_ type: T.Type = T.self) throws -> T { try json.decode(T.self) }101}102103/// The kinds accepted by `GET /api/sync?kinds=` (API-NEXT §3), in the server's order.104public enum SyncKind {105    public static let task = "task"106    public static let database = "database"107    public static let databaseProperty = "database_property"108    public static let databaseView = "database_view"109    public static let databaseRow = "database_row"110    public static let edge = "edge"111    public static let reference = "reference"112    public static let canvas = "canvas"113    public static let concept = "concept"114    public static let all = [task, database, databaseProperty, databaseView, databaseRow, edge, reference, canvas, concept]115}116117// MARK: - Tasks (3.0)118119/// Answer of `DELETE /api/tasks/<id>`: idempotent, `deleted` is false when the task was already deleted.120public struct TaskDeleteResult: Codable, Sendable, Equatable {121    public var ok: Bool122    public var deleted: Bool?123}124125/// Body of `PATCH /api/tasks/<id>`. Only what is set is sent; nullable fields are cleared with `.null`.126public struct TaskChanges: Encodable, Sendable, Equatable {127    public var title: String?128    public var status: TaskStatus?129    public var priority: TaskPriority?130    public var dueAt: PatchValue<Date>?131    /// A bare calendar day `YYYY-MM-DD` (stored at 12:00 UTC by the server). Sent as `due`; `dueAt` wins when both are set.132    public var dueDay: PatchValue<String>?133    public var project: PatchValue<String>?134    public var pageId: PatchValue<String>?135    public var blockId: PatchValue<String>?136137    public init(title: String? = nil, status: TaskStatus? = nil, priority: TaskPriority? = nil, dueAt: PatchValue<Date>? = nil,138                dueDay: PatchValue<String>? = nil, project: PatchValue<String>? = nil, pageId: PatchValue<String>? = nil,139                blockId: PatchValue<String>? = nil) {140        self.title = title141        self.status = status142        self.priority = priority143        self.dueAt = dueAt144        self.dueDay = dueDay145        self.project = project146        self.pageId = pageId147        self.blockId = blockId148    }149150    public var isEmpty: Bool {151        title == nil && status == nil && priority == nil && dueAt == nil && dueDay == nil && project == nil && pageId == nil && blockId == nil152    }153154    enum CodingKeys: String, CodingKey { case title, status, priority, dueAt, due, project, pageId, blockId }155156    public func encode(to encoder: Encoder) throws {157        var c = encoder.container(keyedBy: CodingKeys.self)158        try c.encodeIfPresent(title, forKey: .title)159        try c.encodeIfPresent(status, forKey: .status)160        try c.encodeIfPresent(priority, forKey: .priority)161        try c.encodePatch(dueAt, forKey: .dueAt)162        try c.encodePatch(dueDay, forKey: .due)163        try c.encodePatch(project, forKey: .project)164        try c.encodePatch(pageId, forKey: .pageId)165        try c.encodePatch(blockId, forKey: .blockId)166    }167}168169// MARK: - Canvas170171/// `GET /api/canvases/<pageId>`.172public struct CanvasEnvelope: Codable, Sendable, Equatable {173    public var pageId: String174    public var title: String?175    /// The `spn-canvas-1` document (parse with `SPNotesDocument.CanvasDocument`).176    public var data: RawJSON177    public var version: Int178    public var rev: Int64?179    public var updatedAt: Date?180}181182/// `PUT /api/canvases/<pageId>` → 200.183public struct CanvasSaveResult: Codable, Sendable, Equatable {184    public var version: Int185    public var rev: Int64?186    public var updatedAt: Date?187    /// True when the stored canvas already was exactly what was sent (same `version`).188    public var unchanged: Bool?189}190191/// The server copy carried by `409 conflict` on a canvas save: nothing was written.192public struct CanvasServerCopy: Codable, Sendable, Equatable {193    public var version: Int194    public var data: RawJSON195    public var rev: Int64?196    public var updatedAt: Date?197}198199private struct CanvasConflictBody: Decodable { var server: CanvasServerCopy }200201extension APIError {202    /// The server copy of a refused canvas save (`409 conflict` of `PUT /api/canvases/<pageId>`).203    public var canvasConflict: CanvasServerCopy? {204        guard case .http(409, Code.conflict?, _, let body) = self else { return nil }205        return (try? APIJSON.decoder().decode(CanvasConflictBody.self, from: body))?.server206    }207208    /// The value of an extra field of the error body (`field` of `bad_node`, `id` of `relation_exists`, `kinds` of `bad_kinds`…).209    public func detail(_ key: String) -> RawJSON? {210        guard case .http(_, _, _, let body) = self, let json = try? JSONValue(parsing: body), let value = json[key] else { return nil }211        return value.raw()212    }213214    /// A string extra field of the error body.215    public func detailString(_ key: String) -> String? {216        guard case .http(_, _, _, let body) = self, let json = try? JSONValue(parsing: body) else { return nil }217        return json[key]?.stringValue218    }219220    /// The feature is not provided by this server (`501 not_implemented`, or a 2.x server answering 404 on a 3.0 route).221    public var isNotImplemented: Bool { status == 501 }222223    /// `400` family: the request itself is wrong (validation, malformed id); sending it again unchanged cannot work.224    public var isBadRequest: Bool { status == 400 || status == 413 || status == 415 || status == 422 }225226    /// The stable codes of API-NEXT §5 (3.0).227    public enum NextCode {228        public static let badRequest = "bad_request"229        /// Defaults by status since the integration hardening pass (every error body has a code).230        public static let invalidState = "invalid_state"231        public static let tooLarge = "too_large"232        public static let upstreamError = "upstream_error"233        public static let internalError = "internal"234        public static let badFilter = "bad_filter"235        public static let lastView = "last_view"236        /// `POST /api/research/references` with the id of a deleted reference (409, body `{id, deletedAt}`).237        public static let referenceDeleted = "reference_deleted"238        public static let badCursor = "bad_cursor"239        public static let badKinds = "bad_kinds"240        public static let badView = "bad_view"241        public static let badPage = "bad_page"242        public static let badParent = "bad_parent"243        public static let badNode = "bad_node"244        public static let badCanvas = "bad_canvas"245        public static let notFound = "not_found"246        public static let notCanvas = "not_canvas"247        public static let cycle = "cycle"248        public static let idTaken = "id_taken"249        public static let relationExists = "relation_exists"250        public static let conceptExists = "concept_exists"251        public static let derivedEdge = "derived_edge"252        public static let rowDeleted = "row_deleted"253        public static let gone = "gone"254        public static let notImplemented = "not_implemented"255        public static let aiEmpty = "ai_empty"256    }257}258
Files main
Menu

Theme