Repository Public License
1import Foundation2import Observation3import PrismComponentSDK4import PrismCore5import PrismDataRuntime6import PrismLogicRuntime7import PrismObjectModel8import PrismScriptRuntime910/// File dialogs are behind a protocol so tests and the builder agent can drive apps without UI.11@MainActor12public protocol FileDialogs: AnyObject {13 func chooseFileToOpen(allowedExtensions: [String]) -> URL?14 func chooseFileToSave(suggestedName: String) -> URL?15}1617public struct Notice: Identifiable, Sendable, Equatable {18 public let id: Int19 public var message: String20 public var tone: String21 public var date: Date22}2324public struct RuntimeLogEntry: Identifiable, Sendable, Equatable {25 public enum Level: String, Sendable { case info, warning, error }26 public let id: Int27 public var level: Level28 public var message: String29 public var date: Date30}3132/// Mutable runtime state of one running app. The blueprint it interprets is an immutable value (ADR 0002).33@MainActor34@Observable35public final class AppRuntime {36 public private(set) var blueprint: AppBlueprint37 public let store: AppDataStore38 public let registry: ComponentRegistry39 public private(set) var state: [String: JSONValue]40 public var currentPage: String41 public private(set) var notices: [Notice] = []42 public private(set) var logs: [RuntimeLogEntry] = []43 /// Mirrors the store's revision so views re-evaluate after writes.44 public private(set) var dataRevision = 04546 /// Transient per-instance state of on-demand components (`app.local`); not saved.47 public internal(set) var localState: [String: [String: JSONValue]] = [:]48 @ObservationIgnored var engine: ScriptEngine?49 /// The component instance whose code is running, and whether it may change anything (rendering and expressions may not).50 @ObservationIgnored var scriptInstance: String?51 @ObservationIgnored var scriptReadOnly = false52 @ObservationIgnored var reportedScriptErrors: Set<String> = []5354 @ObservationIgnored public weak var dialogs: FileDialogs?55 @ObservationIgnored public var locale: Locale = .current56 @ObservationIgnored public var currencyCode: String = Locale.current.currency?.identifier ?? "USD"57 @ObservationIgnored private var queryCache: [String: [[String: JSONValue]]] = [:]58 @ObservationIgnored private var cacheRevision = -159 @ObservationIgnored private var counter = 060 @ObservationIgnored private var persistTask: Task<Void, Never>?6162 public init(blueprint: AppBlueprint, store: AppDataStore, registry: ComponentRegistry) throws {63 self.blueprint = blueprint64 self.store = store65 self.registry = registry66 try store.sync(with: blueprint)67 self.state = AppRuntime.mergedState(defaults: blueprint.state, saved: store.meta("state"))68 self.currentPage = blueprint.entrypoint69 self.dataRevision = store.revision70 log(.info, "Started “\(blueprint.name)” with \(blueprint.components.count) components and \(blueprint.tables.count) tables.")71 }7273 /// Saved values win for keys the blueprint still declares; everything else comes from the defaults.74 static func mergedState(defaults: [String: JSONValue], saved: String?) -> [String: JSONValue] {75 guard let saved, let o = (try? JSONValue.parse(saved))?.objectValue else { return defaults }76 var out = defaults77 for (k, v) in o where defaults[k] != nil { out[k] = v }78 return out79 }8081 /// Swaps in a new blueprint version (after an approved change), migrating the schema additively.82 public func reload(_ next: AppBlueprint) throws {83 try store.sync(with: next)84 blueprint = next85 var merged = next.state86 for (k, v) in state where next.state[k] != nil && self.blueprintDeclared(k, in: next) { merged[k] = v }87 state = merged88 if next.object(currentPage)?.isPage != true { currentPage = next.entrypoint }89 engine = nil90 reportedScriptErrors = []91 invalidate()92 log(.info, "Reloaded blueprint version \(next.version).")93 }9495 private func blueprintDeclared(_ key: String, in bp: AppBlueprint) -> Bool { bp.state[key] != nil }9697 // MARK: Logging and notices9899 public func log(_ level: RuntimeLogEntry.Level, _ message: String) {100 counter += 1101 logs.append(RuntimeLogEntry(id: counter, level: level, message: message, date: Date()))102 if logs.count > 500 { logs.removeFirst(logs.count - 500) }103 }104105 public func notify(_ message: String, tone: String = "info") {106 counter += 1107 notices.append(Notice(id: counter, message: message, tone: tone, date: Date()))108 if notices.count > 20 { notices.removeFirst(notices.count - 20) }109 log(tone == "danger" ? .error : .info, "Notice: \(message)")110 }111112 public func dismissNotice(_ id: Int) { notices.removeAll { $0.id == id } }113114 // MARK: Expressions and state115116 public func scope(_ extra: [String: JSONValue] = [:]) -> ExpressionScope {117 var roots = extra118 roots["state"] = .object(state)119 let resolver: @Sendable (String) -> JSONValue = { [weak self] id in120 MainActor.assumeIsolated { .array((self?.namedQueryRows(id) ?? []).map(JSONValue.object)) }121 }122 var scope = ExpressionScope(roots: roots, queryResolver: resolver, locale: locale, currencyCode: currencyCode)123 if !blueprint.scripts.isEmpty {124 scope.scriptCaller = { [weak self] name, args in125 try MainActor.assumeIsolated { try self?.callScript(name, args, readOnly: true) ?? .null }126 }127 }128 return scope129 }130131 /// Resolves a prop value. A failing expression is logged once per message and yields null: the UI never crashes on bad logic.132 public func resolve(_ value: JSONValue?, _ extra: [String: JSONValue] = [:]) -> JSONValue {133 guard let value else { return .null }134 let dynamic = DynamicValue(value)135 guard dynamic.isDynamic else { return value }136 do { return try dynamic.resolve(in: scope(extra)) } catch {137 let message = "Expression failed: \(error.localizedDescription)"138 if logs.last?.message != message { log(.warning, message) }139 return .null140 }141 }142143 public func string(_ value: JSONValue?, _ extra: [String: JSONValue] = [:]) -> String { resolve(value, extra).displayString }144 public func bool(_ value: JSONValue?, default d: Bool, _ extra: [String: JSONValue] = [:]) -> Bool {145 guard value != nil else { return d }146 return resolve(value, extra).isTruthy147 }148 public func number(_ value: JSONValue?, _ extra: [String: JSONValue] = [:]) -> Double? { resolve(value, extra).numericValue }149150 /// The state path a prop is bound to, if it is a `$bind`.151 public func bindingPath(_ value: JSONValue?) -> String? {152 guard let value, case .binding(let path) = DynamicValue(value) else { return nil }153 return path154 }155156 public func setState(_ path: String, _ value: JSONValue) {157 let clean = path.hasPrefix("state.") ? String(path.dropFirst(6)) : path158 guard StatePath.isValid(clean), StatePath.get(clean, in: .object(state)) != value else { return }159 StatePath.set(clean, to: value, in: &state)160 schedulePersist()161 }162163 private func schedulePersist() {164 persistTask?.cancel()165 persistTask = Task { [weak self] in166 try? await Task.sleep(for: .milliseconds(300))167 guard !Task.isCancelled else { return }168 self?.persistStateNow()169 }170 }171172 public func persistStateNow() {173 persistTask?.cancel()174 try? store.setMeta("state", JSONValue.object(state).canonicalString())175 }176177 // MARK: Data178179 func invalidate() {180 dataRevision = store.revision181 queryCache.removeAll()182 }183184 private func touchCache() {185 if cacheRevision != store.revision { queryCache.removeAll(); cacheRevision = store.revision }186 }187188 func namedQueryRows(_ id: String) -> [[String: JSONValue]] {189 guard let object = blueprint.object(id), object.isQuery, let json = object.props["query"] else { return [] }190 return rows(json)191 }192193 /// Rows of an inline query or a `{$ref}` to a query object. Errors are logged and yield no rows.194 public func rows(_ queryJSON: JSONValue?, _ extra: [String: JSONValue] = [:], sort: DataQuery.Sort? = nil) -> [[String: JSONValue]] {195 _ = dataRevision196 guard let queryJSON else { return [] }197 if let ref = queryJSON["$ref"]?.stringValue { return namedQueryRows(ref) }198 do {199 var query = try DataQuery(json: queryJSON)200 if let sort { query.sort = [sort] }201 let schema = try store.schema(query.table)202 let compiled = try query.compile(schema: schema, scope: scope(extra))203 touchCache()204 let key = compiled.sql + "\u{1}" + JSONValue.array(compiled.params).canonicalString()205 if let cached = queryCache[key] { return cached }206 let result = try store.db.query(compiled.sql, compiled.params)207 queryCache[key] = result208 return result209 } catch {210 let message = "Query failed: \(error.localizedDescription)"211 if logs.last?.message != message { log(.error, message) }212 return []213 }214 }215216 public func schema(_ table: String?) -> TableSchema? { table.flatMap { try? store.schema($0) } }217218 public func distinctValues(table: String, column: String) -> [JSONValue] {219 _ = dataRevision220 return (try? store.distinctValues(table, column: column)) ?? []221 }222223 /// Runs a write and refreshes dependants. Returns false and notifies on failure.224 @discardableResult225 public func write(_ what: String, _ body: () throws -> Void) -> Bool {226 do { try body(); invalidate(); return true } catch {227 notify("\(what) failed: \(error.localizedDescription)", tone: "danger")228 return false229 }230 }231232 public func has(_ permission: String) -> Bool { blueprint.permissions.contains(permission) }233234 @discardableResult235 public func importCSV(into table: String) -> CSVImportReport? {236 guard has(Permission.filesImport) else { notify("This app is not allowed to read files.", tone: "danger"); return nil }237 guard let dialogs else { notify("File dialogs are not available here.", tone: "warning"); return nil }238 guard let url = dialogs.chooseFileToOpen(allowedExtensions: ["csv", "tsv", "txt"]) else { return nil }239 return importCSV(from: url, into: table)240 }241242 @discardableResult243 public func importCSV(from url: URL, into table: String) -> CSVImportReport? {244 var report: CSVImportReport?245 let ok = write("Import") {246 let scoped = url.startAccessingSecurityScopedResource()247 defer { if scoped { url.stopAccessingSecurityScopedResource() } }248 report = try store.importCSV(try Data(contentsOf: url), into: table)249 }250 guard ok, let report else { return nil }251 var message = "Imported \(report.imported) row\(report.imported == 1 ? "" : "s") from \(url.lastPathComponent)."252 if report.skipped > 0 { message += " Skipped \(report.skipped): \(report.problems.first ?? "")" }253 notify(message, tone: report.skipped > 0 ? "warning" : "success")254 return report255 }256257 @discardableResult258 public func exportCSV(query: JSONValue, suggestedName: String) -> URL? {259 guard has(Permission.filesExport) else { notify("This app is not allowed to write files.", tone: "danger"); return nil }260 guard let dialogs else { notify("File dialogs are not available here.", tone: "warning"); return nil }261 guard let url = dialogs.chooseFileToSave(suggestedName: suggestedName) else { return nil }262 do {263 let q = try DataQuery(json: query)264 let schema = try store.schema(q.table)265 let outputs = q.outputColumns(schema: schema).filter { $0 != "id" }266 let columns = outputs.map { schema.column($0) ?? ColumnSchema(name: $0, type: .number) }267 try store.exportCSV(rows: rows(query), columns: columns).write(to: url, options: .atomic)268 notify("Exported to \(url.lastPathComponent).", tone: "success")269 return url270 } catch {271 notify("Export failed: \(error.localizedDescription)", tone: "danger")272 return nil273 }274 }275276 // MARK: Actions (ADR 0003, rung 1)277278 /// Fires an object's event. `payload` becomes `value`, `row` the record in context.279 public func fire(_ event: String, on objectID: String, value: JSONValue = .null, row: JSONValue? = nil) {280 guard let actions = blueprint.object(objectID)?.events[event], !actions.isEmpty else { return }281 var extra: [String: JSONValue] = ["value": value]282 if let row { extra["row"] = row }283 run(actions, extra)284 }285286 /// Runs actions in order; a failed validation or a failing action stops the sequence.287 @discardableResult288 public func run(_ actions: [JSONValue], _ extra: [String: JSONValue] = [:], depth: Int = 0) -> Bool {289 guard depth < 8 else { return false }290 for a in actions { if !runOne(a, extra, depth: depth) { return false } }291 return true292 }293294 private func recordID(_ a: JSONValue, _ extra: [String: JSONValue]) -> Int? { resolve(a["id"], extra).intValue }295296 private func values(_ a: JSONValue, _ extra: [String: JSONValue]) -> [String: JSONValue] {297 (a["values"]?.objectValue ?? [:]).mapValues { resolve($0, extra) }298 }299300 private func runOne(_ a: JSONValue, _ extra: [String: JSONValue], depth: Int) -> Bool {301 guard let type = a["type"]?.stringValue else { return false }302 switch type {303 case "setState":304 guard let key = a["key"]?.stringValue else { return false }305 setState(key, resolve(a["value"], extra))306 case "toggleState":307 guard let key = a["key"]?.stringValue else { return false }308 let clean = key.hasPrefix("state.") ? String(key.dropFirst(6)) : key309 setState(clean, .bool(!StatePath.get(clean, in: .object(state)).isTruthy))310 case "navigate":311 guard let page = a["page"]?.stringValue, blueprint.object(page)?.isPage == true else { return false }312 currentPage = page313 case "createRecord":314 guard let table = a["table"]?.stringValue else { return false }315 return write("Saving") { try store.insert(into: table, values: values(a, extra)) }316 case "updateRecord":317 guard let table = a["table"]?.stringValue, let id = recordID(a, extra) else { notify("No record is selected.", tone: "warning"); return false }318 return write("Saving") { try store.update(table, id: id, values: values(a, extra)) }319 case "deleteRecord":320 guard let table = a["table"]?.stringValue, let id = recordID(a, extra) else { notify("No record is selected.", tone: "warning"); return false }321 return write("Deleting") { try store.delete(from: table, id: id) }322 case "importCSV":323 guard let table = a["table"]?.stringValue else { return false }324 return importCSV(into: table) != nil325 case "exportCSV":326 let query = a["query"] ?? a["table"].map { ["table": $0] } ?? .null327 return exportCSV(query: query, suggestedName: a["filename"]?.stringValue ?? "export.csv") != nil328 case "showNotification":329 notify(string(a["message"], extra), tone: a["tone"]?.stringValue ?? "info")330 case "validate":331 let failed = (a["rules"]?.arrayValue ?? []).filter { resolve($0["when"], extra).isTruthy }.map { string($0["message"], extra) }332 if !failed.isEmpty { notify(failed.joined(separator: " "), tone: "warning"); return false }333 case "runScript":334 guard let fn = a["function"]?.stringValue else { return false }335 do {336 // A script that returns false stops the remaining actions, like a failed validation.337 return try callScript(fn, (a["args"]?.arrayValue ?? []).map { resolve($0, extra) } + [.object(extra)]) != .bool(false)338 } catch {339 notify(error.localizedDescription, tone: "danger")340 return false341 }342 case "when":343 let branch = resolve(a["condition"], extra).isTruthy ? a["then"] : a["else"]344 return run(branch?.arrayValue ?? [], extra, depth: depth + 1)345 default:346 log(.error, "Unknown action `\(type)` was ignored.")347 return false348 }349 return true350 }351}352