SPB Git

Repository Public License

Patch.swift 10.5 KB 195 lines swift

1import Foundation2import PrismCore34/// A deterministic edit to a blueprint (ADR 0002). The agent, Design mode and Evolve all speak this.5public enum BlueprintPatch: Sendable, Hashable {6    case addObject(PrismObject, parent: String?, index: Int?)7    /// Removes the object and its whole subtree, and detaches it from its parent.8    case removeObject(id: String)9    case setProp(id: String, key: String, value: JSONValue)10    case removeProp(id: String, key: String)11    /// Any object field except `id` (by JSON name), e.g. `name`, `events`, `dataRef`, `permissions`.12    case setField(id: String, field: String, value: JSONValue)13    case setEvent(id: String, event: String, actions: [JSONValue])14    case moveChild(id: String, toParent: String, index: Int?)15    /// A blueprint-level field: `name`, `summary`, `entrypoint`, `permissions`, `theme`, `state`.16    case setBlueprintField(field: String, value: JSONValue)1718    public var json: JSONValue {19        switch self {20        case .addObject(let o, let parent, let index):21            var d: [String: JSONValue] = ["op": "addObject", "object": o.json]22            if let parent { d["parent"] = .string(parent) }23            if let index { d["index"] = .int(index) }24            return .object(d)25        case .removeObject(let id): return ["op": "removeObject", "id": .string(id)]26        case .setProp(let id, let key, let value): return ["op": "setProp", "id": .string(id), "key": .string(key), "value": value]27        case .removeProp(let id, let key): return ["op": "removeProp", "id": .string(id), "key": .string(key)]28        case .setField(let id, let field, let value): return ["op": "setField", "id": .string(id), "field": .string(field), "value": value]29        case .setEvent(let id, let event, let actions):30            return ["op": "setEvent", "id": .string(id), "event": .string(event), "actions": .array(actions)]31        case .moveChild(let id, let toParent, let index):32            var d: [String: JSONValue] = ["op": "moveChild", "id": .string(id), "toParent": .string(toParent)]33            if let index { d["index"] = .int(index) }34            return .object(d)35        case .setBlueprintField(let field, let value): return ["op": "setBlueprintField", "field": .string(field), "value": value]36        }37    }3839    public init(json: JSONValue) throws {40        func str(_ k: String) throws -> String {41            guard let s = json[k]?.stringValue else { throw BlueprintError.patch("`\(k)` is required.") }42            return s43        }44        func val(_ k: String) throws -> JSONValue {45            guard let v = json[k] else { throw BlueprintError.patch("`\(k)` is required.") }46            return v47        }48        switch try str("op") {49        case "addObject":50            self = .addObject(try PrismObject(json: try val("object")), parent: json["parent"]?.stringValue, index: json["index"]?.intValue)51        case "removeObject": self = .removeObject(id: try str("id"))52        case "setProp": self = .setProp(id: try str("id"), key: try str("key"), value: try val("value"))53        case "removeProp": self = .removeProp(id: try str("id"), key: try str("key"))54        case "setField": self = .setField(id: try str("id"), field: try str("field"), value: try val("value"))55        case "setEvent":56            guard let actions = json["actions"]?.arrayValue else { throw BlueprintError.patch("`actions` must be an array.") }57            self = .setEvent(id: try str("id"), event: try str("event"), actions: actions)58        case "moveChild": self = .moveChild(id: try str("id"), toParent: try str("toParent"), index: json["index"]?.intValue)59        case "setBlueprintField": self = .setBlueprintField(field: try str("field"), value: try val("value"))60        case let other: throw BlueprintError.patch("Unknown operation `\(other)`.")61        }62    }63}6465extension AppBlueprint {66    /// Returns a new blueprint; the receiver is never mutated, so the caller keeps the old value for undo.67    public func applying(_ patch: BlueprintPatch) throws -> AppBlueprint {68        var bp = self69        func require(_ id: String) throws -> Int {70            guard let i = bp.index(of: id) else { throw BlueprintError.patch("There is no object `\(id)`.") }71            return i72        }73        switch patch {74        case .addObject(let object, let parent, let index):75            guard bp.index(of: object.id) == nil else { throw BlueprintError.patch("An object `\(object.id)` already exists.") }76            bp.objects.append(object)77            if let parent {78                let p = try require(parent)79                let at = min(max(index ?? bp.objects[p].children.count, 0), bp.objects[p].children.count)80                bp.objects[p].children.insert(object.id, at: at)81            }82        case .removeObject(let id):83            _ = try require(id)84            let doomed = Set(bp.subtree(id).map(\.id))85            bp.objects.removeAll { doomed.contains($0.id) }86            for i in bp.objects.indices {87                bp.objects[i].children.removeAll { doomed.contains($0) }88                bp.objects[i].dependencies.removeAll { doomed.contains($0) }89                if let ref = bp.objects[i].dataRef, doomed.contains(ref) { bp.objects[i].dataRef = nil }90            }91            if doomed.contains(bp.entrypoint) { bp.entrypoint = bp.pages.first?.id ?? "" }92        case .setProp(let id, let key, let value):93            bp.objects[try require(id)].props[key] = value94        case .removeProp(let id, let key):95            bp.objects[try require(id)].props[key] = nil96        case .setField(let id, let field, let value):97            let i = try require(id)98            guard field != "id", PrismObject.fieldNames.contains(field) else {99                throw BlueprintError.patch("`\(field)` is not an editable field.")100            }101            guard var o = bp.objects[i].json.objectValue else { break }102            if value.isNull { o[field] = nil } else { o[field] = value }103            do { bp.objects[i] = try PrismObject(json: .object(o)) }104            catch { throw BlueprintError.patch(error.localizedDescription) }105        case .setEvent(let id, let event, let actions):106            let i = try require(id)107            if actions.isEmpty { bp.objects[i].events[event] = nil } else { bp.objects[i].events[event] = actions }108        case .moveChild(let id, let toParent, let index):109            _ = try require(id)110            let p = try require(toParent)111            guard !bp.subtree(id).contains(where: { $0.id == toParent }) else {112                throw BlueprintError.patch("`\(id)` cannot be moved inside itself.")113            }114            for i in bp.objects.indices { bp.objects[i].children.removeAll { $0 == id } }115            let at = min(max(index ?? bp.objects[p].children.count, 0), bp.objects[p].children.count)116            bp.objects[p].children.insert(id, at: at)117        case .setBlueprintField(let field, let value):118            switch field {119            case "name": bp.name = value.stringValue ?? bp.name120            case "summary": bp.summary = value.stringValue ?? ""121            case "entrypoint": bp.entrypoint = value.stringValue ?? ""122            case "permissions": bp.permissions = (value.arrayValue ?? []).compactMap(\.stringValue)123            case "theme": bp.theme = value.objectValue ?? [:]124            case "state": bp.state = value.objectValue ?? [:]125            case "icon": bp.icon = value == .null ? nil : value126            default: throw BlueprintError.patch("`\(field)` is not an editable app field.")127            }128        }129        return bp130    }131132    public func applying(_ patches: [BlueprintPatch]) throws -> AppBlueprint {133        try patches.reduce(self) { try $0.applying($1) }134    }135}136137/// What changed between two versions of a blueprint, in a form a person can review.138public struct BlueprintDiff: Sendable, Hashable {139    public struct ObjectChange: Sendable, Hashable, Identifiable {140        public var id: String141        public var type: String142        public var name: String143        /// Field or `props.key` names whose value differs.144        public var fields: [String]145    }146147    public var added: [PrismObject] = []148    public var removed: [PrismObject] = []149    public var changed: [ObjectChange] = []150    public var appFields: [String] = []151    public var addedPermissions: [String] = []152    public var removedPermissions: [String] = []153154    public var isEmpty: Bool { added.isEmpty && removed.isEmpty && changed.isEmpty && appFields.isEmpty }155156    public init(from old: AppBlueprint, to new: AppBlueprint) {157        let oldByID = Dictionary(old.objects.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })158        let newByID = Dictionary(new.objects.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })159        added = new.objects.filter { oldByID[$0.id] == nil }160        removed = old.objects.filter { newByID[$0.id] == nil }161        for o in new.objects {162            guard let before = oldByID[o.id], before != o else { continue }163            var fields: [String] = []164            let a = before.json.objectValue ?? [:], b = o.json.objectValue ?? [:]165            for key in Set(a.keys).union(b.keys).sorted() where a[key] != b[key] {166                if key == "props" {167                    let pa = before.props, pb = o.props168                    fields += Set(pa.keys).union(pb.keys).sorted().filter { pa[$0] != pb[$0] }.map { "props.\($0)" }169                } else {170                    fields.append(key)171                }172            }173            changed.append(.init(id: o.id, type: o.type, name: o.name, fields: fields))174        }175        if old.name != new.name { appFields.append("name") }176        if old.summary != new.summary { appFields.append("summary") }177        if old.entrypoint != new.entrypoint { appFields.append("entrypoint") }178        if old.theme != new.theme { appFields.append("theme") }179        if old.state != new.state { appFields.append("state") }180        if old.permissions != new.permissions { appFields.append("permissions") }181        addedPermissions = new.permissions.filter { !old.permissions.contains($0) }182        removedPermissions = old.permissions.filter { !new.permissions.contains($0) }183    }184185    public var summaryLines: [String] {186        var lines: [String] = []187        for o in added { lines.append("+ \(o.type) “\(o.name.isEmpty ? o.id : o.name)”") }188        for o in removed { lines.append("− \(o.type) “\(o.name.isEmpty ? o.id : o.name)”") }189        for c in changed { lines.append("~ \(c.name.isEmpty ? c.id : c.name): \(c.fields.joined(separator: ", "))") }190        if !appFields.isEmpty { lines.append("~ app: \(appFields.joined(separator: ", "))") }191        for p in addedPermissions { lines.append("! new permission: \(p)") }192        return lines193    }194}195
Files main
Menu

Theme