Repository Public License
1import Foundation2import PrismComponentCatalog3import PrismComponentSDK4import PrismCore5import PrismDataRuntime6import PrismObjectModel7import PrismRenderer8import Testing9@testable import PrismAIOrchestrator1011@MainActor @Suite struct DesignAndCustomTests {12 private func workspace() async -> BuildWorkspace {13 let ws = BuildWorkspace(registry: Catalog.registry)14 _ = await ws.execute("project.create", ["name": "Game Night", "summary": "Score keeper", "acceptanceCriteria": ["Scores can be changed"]])15 _ = await ws.execute("catalog.search", ["query": "button"])16 _ = await ws.execute("logic.bind", ["state": ["score": 3, "label": "Team A"]])17 _ = await ws.execute("ui.createPage", ["id": "home", "name": "Home"])18 _ = await ws.execute("ui.addComponent", ["parent": "home", "id": "root", "type": "prism.stack", "props": ["align": "stretch", "grow": true]])19 return ws20 }2122 static let counterSource = """23 function render(props) {24 var extra = app.local('extra', 0);25 return { type: 'vstack', spacing: 8, children: [26 { type: 'text', text: props.title + ': ' + (props.value + extra), size: 22, weight: 'bold', color: 'accent' },27 { type: 'hstack', children: [28 { type: 'button', title: 'Add', symbol: 'plus', onTap: { call: 'add', args: [1] } },29 { type: 'button', title: 'Local', onTap: 'bumpLocal' } ] },30 { type: 'canvas', width: 120, height: 40, commands: [{ op: 'rect', x: 0, y: 0, width: 12 * props.value, height: 40, fill: 'accent', radius: 6 }] } ] };31 }32 function add(n, event) { app.setProp('value', event.props.value + n); app.emit('change', event.props.value + n); }33 function bumpLocal() { app.setLocal('extra', app.local('extra', 0) + 10); }34 """3536 @Test func aThemeIsValidatedAndApplied() async throws {37 let ws = await workspace()38 let listed = await ws.execute("design.listThemes", .emptyObject)39 #expect(listed.content["presets"]?.arrayValue?.count ?? 0 >= 12)40 let unreadable = await ws.execute("design.setTheme", ["theme": ["palette": ["background": "#101010", "text": "#1A1A1A"]]])41 #expect(!unreadable.ok && unreadable.summary.contains("not readable"))42 let unknown = await ws.execute("design.setTheme", ["theme": ["preset": "nope", "colour": "red"]])43 #expect(!unknown.ok)44 let ok = await ws.execute("design.setTheme", ["theme": ["preset": "aurora", "accent": "#FF7AD9", "palette": ["text": "#FFFFFF"]]])45 #expect(ok.ok)46 let theme = PrismTheme(try #require(ws.blueprint).theme)47 #expect(theme.surface == "glass" && theme.fontDesign == .rounded && theme.colorScheme == .dark && theme.backgroundGradient.count == 3)48 #expect(ok.content["resolved"]?["palette"]?["text"] == "#FFFFFF")49 }5051 @Test func theDesignedIconComesBackAsAPicture() async throws {52 let ws = await workspace()53 let bad = await ws.execute("design.setIcon", ["icon": ["background": ["colors": ["#123456"]], "layers": [["symbol": "no.such.symbol.anywhere"]]]])54 #expect(!bad.ok && bad.summary.contains("SF Symbol") && ws.blueprint?.icon == nil)55 let icon: JSONValue = ["background": ["colors": ["#1B1035", "#6D28D9", "#22D3EE"], "style": "mesh"],56 "layers": [["symbol": "dice.fill", "size": 58, "fill": ["colors": ["#FFFFFF", "#E9D5FF"], "angle": 90], "shadow": true, "rotation": -12]], "finish": "glass"]57 let ok = await ws.execute("design.setIcon", ["icon": icon])58 #expect(ok.ok && ws.blueprint?.icon == icon)59 let png = try #require(ok.imagePNG)60 #expect(png.prefix(4) == Data([0x89, 0x50, 0x4E, 0x47]) && png.count > 5_000)61 }6263 @Test func anOnDemandComponentIsDefinedTestedPlacedAndWorks() async throws {64 let ws = await workspace()65 let noRender = await ws.execute("component.define", ["id": "tally", "summary": "x", "source": "function draw() {}"])66 #expect(!noRender.ok && noRender.summary.contains("render"))67 let syntax = await ws.execute("component.define", ["id": "tally", "summary": "x", "source": "function render( {"])68 #expect(!syntax.ok && syntax.errorCode == "script.syntax")69 let defined = await ws.execute("component.define", [70 "id": "tally", "name": "Tally", "summary": "A score with a bar and an Add button.", "source": .string(Self.counterSource), "events": ["change"],71 "props": [["name": "title", "kind": "string", "summary": "Label.", "default": "Score"], ["name": "value", "kind": "number", "summary": "State key with the score.", "required": true, "binding": "required", "dynamic": false]],72 ])73 #expect(defined.ok && defined.content["type"] == "custom.tally")74 #expect(ws.blueprint?.permissions.contains(Permission.scripts) == true && ws.requestedPermissions.contains(Permission.scripts))7576 let tested = await ws.execute("component.test", ["id": "tally", "props": ["title": "Team A", "value": 4]])77 #expect(tested.ok, "\(tested.content)")78 #expect(tested.content["nodes"]?["button"] == 2 && tested.content["sampleText"]?.arrayValue?.contains("Team A: 4") == true)7980 // A wrong prop and an unknown custom type are rejected like catalog mistakes.81 let wrong = await ws.execute("ui.addComponent", ["parent": "root", "id": "t0", "type": "custom.missing"])82 #expect(!wrong.ok)83 let placed = await ws.execute("ui.addComponent", ["parent": "root", "id": "t1", "type": "custom.tally", "props": ["title": ["$expr": "state.label"], "value": ["$bind": "score"]],84 "events": ["change": [["type": "showNotification", "message": ["$expr": "concat('Now ', value)"]]]]])85 #expect(placed.ok, "\(placed.content)")86 let literal = await ws.execute("ui.setProperties", ["id": "t1", "props": ["value": 5]])87 #expect(literal.ok)88 let invalid = await ws.execute("ui.preview", .emptyObject)89 #expect(!invalid.ok && invalid.content.canonicalString().contains("$bind"))90 _ = await ws.execute("ui.setProperties", ["id": "t1", "props": ["value": ["$bind": "score"]]])91 let preview = await ws.execute("ui.preview", .emptyObject)92 #expect(preview.ok, "\(preview.content)")93 #expect(preview.content["customComponents"] == 1 && (preview.content["coverage"]?.doubleValue ?? 1) < 1)9495 // The real runtime: the handler writes the bound state, emits the event, and local state is per instance.96 let bp = try #require(ws.blueprint)97 let rt = try AppRuntime(blueprint: bp, store: AppDataStore(url: nil), registry: Catalog.registry)98 let props: JSONValue = ["title": "Team A", "value": 3]99 #expect(rt.callComponent("tally", "render", [props], instance: "t1", readOnly: true)?["children"]?[0]?["text"] == "Team A: 3")100 rt.callComponent("tally", "add", [1, ["props": props]], instance: "t1")101 #expect(rt.state["score"] == 4 && rt.notices.last?.message == "Now 4")102 rt.callComponent("tally", "bumpLocal", [["props": props]], instance: "t1")103 #expect(rt.localState["t1"]?["extra"] == 10 && rt.localState["other"] == nil)104 // Rendering can never change anything.105 rt.callComponent("tally", "add", [1, ["props": props]], instance: "t1", readOnly: true)106 #expect(rt.state["score"] == 4 && rt.logs.contains { $0.message.contains("while rendering") })107108 let shot = await ws.execute("ui.screenshot", .emptyObject)109 #expect(shot.ok && (shot.imagePNG?.count ?? 0) > 3_000)110 }111112 @Test func scriptsServeActionsAndExpressionsAndCannotEscape() async throws {113 let ws = await workspace()114 _ = await ws.execute("data.createSchema", ["id": "rounds", "columns": [["name": "points", "type": "integer"]], "seed": [["points": 2], ["points": 5]]])115 let script = """116 function total() { return app.query({ table: 'rounds' }).reduce(function (s, r) { return s + r.points }, 0) }117 function record(points) { if (points <= 0) { app.notify('Points must be positive', 'warning'); return false } app.insert('rounds', { points: points }); app.set('score', total()); }118 function sneaky() { app.set('score', 99); return 1 }119 function forever() { for (;;) {} }120 """121 #expect(await ws.execute("logic.createScript", ["id": "rules", "source": .string(script)]).ok)122 #expect(await ws.execute("code.run", ["function": "total"]).content["result"] == 7)123 _ = await ws.execute("ui.addComponent", ["parent": "root", "id": "sum", "type": "prism.text", "props": ["text": ["$expr": "concat('Total ', js('total'))"]]])124 _ = await ws.execute("ui.addComponent", ["parent": "root", "id": "go", "type": "prism.button", "props": ["title": "Record"],125 "events": ["click": [["type": "runScript", "function": "record", "args": [["$expr": "state.score"]]], ["type": "setState", "key": "label", "value": "done"]]]])126 let preview = await ws.execute("ui.preview", .emptyObject)127 #expect(preview.ok, "\(preview.content)")128 #expect(await ws.execute("code.read", ["id": "rules"]).content["source"]?.stringValue?.contains("function total") == true)129130 let rt = try AppRuntime(blueprint: try #require(ws.blueprint), store: AppDataStore(url: nil), registry: Catalog.registry)131 #expect(rt.string(["$expr": "concat('Total ', js('total'))"]) == "Total 7")132 rt.fire("click", on: "go")133 #expect(rt.state["score"] == 10 && rt.state["label"] == "done" && rt.rows(["table": "rounds"]).count == 3)134 // A script returning false stops the remaining actions.135 rt.setState("score", 0); rt.setState("label", "start")136 rt.fire("click", on: "go")137 #expect(rt.state["label"] == "start" && rt.notices.last?.message == "Points must be positive")138 // Expressions are read-only, undeclared state is refused, an endless loop is stopped.139 #expect(rt.resolve(["$expr": "js('sneaky')"]) == .null && rt.state["score"] == 0)140 #expect(throws: (any Error).self) { try rt.callScript("forever") }141 #expect(try rt.callScript("total") == 10)142143 // Without the permission nothing runs.144 var stripped = try #require(ws.blueprint)145 stripped.permissions.removeAll { $0 == Permission.scripts }146 #expect(BlueprintValidator.validate(stripped, registry: Catalog.registry).errors.contains { $0.message.contains(Permission.scripts) })147 }148}149