Repository Public License
1import Foundation2import PrismCore3import PrismObjectModel45public struct ManifestError: Error, LocalizedError, Sendable, Equatable {6 public let message: String7 public init(_ message: String) { self.message = message }8 public var errorDescription: String? { message }9}1011/// One configurable property of a component.12public struct PropSpec: Sendable, Hashable {13 public enum Kind: String, Sendable, CaseIterable {14 case string, number, boolean, `enum`, list, object, query, any15 }16 public enum Binding: String, Sendable { case none, optional, required }1718 public var name: String19 public var kind: Kind20 public var summary: String21 public var required: Bool22 public var defaultValue: JSONValue?23 public var enumValues: [String]24 /// Whether `{"$expr": …}` is accepted.25 public var dynamic: Bool26 /// Whether `{"$bind": …}` is accepted or required (two-way state binding).27 public var binding: Binding2829 public init(30 _ name: String, _ kind: Kind, _ summary: String, required: Bool = false, default defaultValue: JSONValue? = nil,31 values: [String] = [], dynamic: Bool = true, binding: Binding = .none32 ) {33 self.name = name; self.kind = kind; self.summary = summary; self.required = required34 self.defaultValue = defaultValue; self.enumValues = values; self.dynamic = dynamic; self.binding = binding35 }3637 var json: JSONValue {38 var o: [String: JSONValue] = [39 "name": .string(name), "kind": .string(kind.rawValue), "summary": .string(summary), "required": .bool(required),40 "dynamic": .bool(dynamic), "binding": .string(binding.rawValue),41 ]42 if let defaultValue { o["default"] = defaultValue }43 if !enumValues.isEmpty { o["values"] = .array(enumValues.map(JSONValue.string)) }44 return .object(o)45 }4647 init(json: JSONValue) throws {48 guard let name = json["name"]?.stringValue, PrismID.isValid(name) else { throw ManifestError("A prop needs a valid `name`.") }49 guard let kindName = json["kind"]?.stringValue, let kind = Kind(rawValue: kindName) else {50 throw ManifestError("Prop `\(name)` has an unknown `kind`.")51 }52 let binding = Binding(rawValue: json["binding"]?.stringValue ?? "none")53 guard let binding else { throw ManifestError("Prop `\(name)` has an unknown `binding`.") }54 let values = (json["values"]?.arrayValue ?? []).compactMap(\.stringValue)55 if kind == .enum && values.isEmpty { throw ManifestError("Enum prop `\(name)` lists no values.") }56 self.init(57 name, kind, json["summary"]?.stringValue ?? "", required: json["required"]?.boolValue ?? false,58 default: json["default"], values: values, dynamic: json["dynamic"]?.boolValue ?? true, binding: binding59 )60 }61}6263/// The contract of a catalog component (spec §7).64public struct ComponentManifest: Sendable, Hashable, Identifiable {65 public static let schemaVersion = 16667 public var type: String68 public var name: String69 public var category: String70 public var summary: String71 /// Semantic version of the component's contract.72 public var version: String73 public var props: [PropSpec]74 public var events: [String]75 public var acceptsChildren: Bool76 public var maxChildren: Int?77 public var permissions: [String]78 public var keywords: [String]79 /// VoiceOver role and the prop that provides the accessible label.80 public var accessibilityRole: String81 public var accessibilityLabelProp: String?82 /// Ready-to-copy object snippets returned by `catalog.examples`.83 public var examples: [JSONValue]84 /// A self-contained preview: `{root, objects[], state?}`. Rendered in tests and in the Library.85 public var fixture: JSONValue8687 public var id: String { type }8889 public static let categories = ["foundation", "forms", "data", "charts", "navigation", "layout", "display", "feedback", "input", "media", "productivity", "commerce", "social", "time", "maps", "text", "logic", "custom"]90 public static let knownEvents: Set<String> = ["click", "change", "submit", "select", "imported", "exported", "saved", "deleted", "cancelled", "appear", "tick", "complete", "open", "close", "drop", "reorder", "toggle", "rate", "copy", "focus", "blur", "expand", "collapse", "dismiss", "confirm", "page", "sort", "remove", "add", "edit", "start", "stop", "reset"]9192 public init(93 type: String, name: String, category: String, summary: String, version: String = "1.0.0", props: [PropSpec] = [],94 events: [String] = [], acceptsChildren: Bool = false, maxChildren: Int? = nil, permissions: [String] = [],95 keywords: [String] = [], accessibilityRole: String, accessibilityLabelProp: String? = nil,96 examples: [JSONValue] = [], fixture: JSONValue97 ) {98 self.type = type; self.name = name; self.category = category; self.summary = summary; self.version = version99 self.props = props; self.events = events; self.acceptsChildren = acceptsChildren; self.maxChildren = maxChildren100 self.permissions = permissions; self.keywords = keywords; self.accessibilityRole = accessibilityRole101 self.accessibilityLabelProp = accessibilityLabelProp; self.examples = examples; self.fixture = fixture102 }103104 public func prop(_ name: String) -> PropSpec? { props.first { $0.name == name } ?? CommonProps.all.first { $0.name == name } }105106 public var json: JSONValue {107 var o: [String: JSONValue] = [108 "schemaVersion": .int(Self.schemaVersion), "type": .string(type), "name": .string(name), "category": .string(category),109 "summary": .string(summary), "version": .string(version), "props": .array(props.map(\.json)),110 "events": .array(events.map(JSONValue.string)), "acceptsChildren": .bool(acceptsChildren),111 "permissions": .array(permissions.map(JSONValue.string)), "keywords": .array(keywords.map(JSONValue.string)),112 "accessibility": ["role": .string(accessibilityRole), "labelProp": accessibilityLabelProp.map(JSONValue.string) ?? .null],113 "examples": .array(examples), "fixture": fixture,114 ]115 if let maxChildren { o["maxChildren"] = .int(maxChildren) }116 return .object(o)117 }118119 /// SHA-256 of the canonical manifest: what the registry verifies at load.120 public var contentHash: String { ContentHash.sha256(json) }121122 /// Strict decoding: a malformed manifest is rejected with a message naming the problem.123 public init(json: JSONValue) throws {124 guard let o = json.objectValue else { throw ManifestError("A manifest must be a JSON object.") }125 guard o["schemaVersion"]?.intValue == Self.schemaVersion else {126 throw ManifestError("Unsupported manifest `schemaVersion` (expected \(Self.schemaVersion)).")127 }128 func str(_ k: String) throws -> String {129 guard let s = o[k]?.stringValue, !s.isEmpty else { throw ManifestError("Manifest field `\(k)` is missing.") }130 return s131 }132 let type = try str("type")133 guard type.hasPrefix("prism."), type.split(separator: ".").allSatisfy({ PrismID.isValid(String($0)) }) else {134 throw ManifestError("`\(type)` is not a valid component type.")135 }136 let category = try str("category")137 guard Self.categories.contains(category) else { throw ManifestError("`\(type)`: unknown category `\(category)`.") }138 let version = try str("version")139 guard version.split(separator: ".").count == 3, version.split(separator: ".").allSatisfy({ Int($0) != nil }) else {140 throw ManifestError("`\(type)`: version `\(version)` is not a semantic version.")141 }142 guard let propList = o["props"]?.arrayValue else { throw ManifestError("`\(type)`: `props` must be an array.") }143 let props = try propList.map(PropSpec.init(json:))144 guard Set(props.map(\.name)).count == props.count else { throw ManifestError("`\(type)` declares a prop twice.") }145 let events = (o["events"]?.arrayValue ?? []).compactMap(\.stringValue)146 if let bad = events.first(where: { !Self.knownEvents.contains($0) }) { throw ManifestError("`\(type)`: unknown event `\(bad)`.") }147 guard let role = o["accessibility"]?["role"]?.stringValue, !role.isEmpty else {148 throw ManifestError("`\(type)` has no accessibility role.")149 }150 guard let fixture = o["fixture"], fixture["root"]?.stringValue != nil, fixture["objects"]?.arrayValue?.isEmpty == false else {151 throw ManifestError("`\(type)` has no preview fixture.")152 }153 self.init(154 type: type, name: try str("name"), category: category, summary: try str("summary"), version: version, props: props,155 events: events, acceptsChildren: o["acceptsChildren"]?.boolValue ?? false, maxChildren: o["maxChildren"]?.intValue,156 permissions: (o["permissions"]?.arrayValue ?? []).compactMap(\.stringValue),157 keywords: (o["keywords"]?.arrayValue ?? []).compactMap(\.stringValue), accessibilityRole: role,158 accessibilityLabelProp: o["accessibility"]?["labelProp"]?.stringValue,159 examples: o["examples"]?.arrayValue ?? [], fixture: fixture160 )161 }162163 /// A complete single-page app showing this component, built from the fixture.164 public func fixtureBlueprint() throws -> AppBlueprint {165 guard let root = fixture["root"]?.stringValue, let list = fixture["objects"]?.arrayValue else {166 throw ManifestError("`\(type)` has no preview fixture.")167 }168 var bp = AppBlueprint(id: "fixture_" + PrismID.slug(type), name: name, entrypoint: "fixture_page")169 bp.state = fixture["state"]?.objectValue ?? [:]170 bp.permissions = Array(Set(permissions + (fixture["permissions"]?.arrayValue ?? []).compactMap(\.stringValue))).sorted()171 bp.objects = [PrismObject(id: "fixture_page", type: ObjectType.page, name: name, children: [root])] + (try list.map(PrismObject.init(json:)))172 return bp173 }174}175176/// Props every component accepts.177public enum CommonProps {178 public static let all: [PropSpec] = [179 PropSpec("visible", .boolean, "Shown only while this is true.", default: true),180 PropSpec("padding", .number, "Space around the component, in points.", dynamic: false),181 PropSpec("width", .number, "Fixed width in points.", dynamic: false),182 PropSpec("height", .number, "Fixed height in points.", dynamic: false),183 PropSpec("grow", .boolean, "Take all available space in its container.", dynamic: false),184 PropSpec("accessibilityLabel", .string, "Spoken label for VoiceOver when the visible text is not enough."),185 PropSpec("help", .string, "Tooltip shown on hover."),186 ]187}188189/// Capabilities an app can hold (spec §12). Everything not listed here is denied in V1.190public enum Permission {191 public static let storageLocal = "storage.local"192 public static let filesImport = "files.import.userSelected"193 public static let filesExport = "files.export.userSelected"194 public static let scripts = "logic.scripts"195196 public static let grantable: [String: String] = [197 storageLocal: "Keep its data in a private database on this Mac.",198 filesImport: "Read a file you pick in an Open dialog.",199 filesExport: "Write a file where you choose in a Save dialog.",200 scripts: "Run logic and components written for this app. They are confined to the app: its own state and data, no files, no network.",201 ]202203 /// Recognized but not available in this version: asking for one is a validation error.204 public static let unavailable: Set<String> = [205 "network.client", "files.readWrite.all", "camera", "microphone", "contacts", "automation", "shell", "accessibility",206 ]207}208