1pub use tilo_actions::surface::{
9 CONTENT_VERBS, FieldSurface, FieldType, NamedType, ParamSurface, ReturnsSurface, Surface,
10 TYPE_VERB, TypeCase, TypeField, TypeSet, VerbSurface,
11};
12
13use crate::resource::Resource;
14use crate::shape::Shape;
15use crate::vocabulary::{Declaration, vocabulary};
16
17pub type FlatTypes = fn(&mut TypeSet) -> Vec<(String, FieldType)>;
20
21fn params_of(
24 params: &[tilo_actions::ActionParam],
25 param_types: &[(&'static str, FieldTypeOf)],
26 flat_types: Option<FlatTypes>,
27 types: &mut TypeSet,
28) -> Vec<ParamSurface> {
29 let flat: Vec<(String, FieldType)> = flat_types.map_or_else(Vec::new, |flat| flat(types));
33 params
34 .iter()
35 .map(|param| {
36 let schema = param
37 .schema
38 .as_deref()
39 .cloned()
40 .unwrap_or(serde_json::Value::Null);
41 let declared = param_types
42 .iter()
43 .find(|(name, _)| *name == param.name.as_ref());
44 let ty = if param.ty == tilo_actions::ParamType::Secret {
45 FieldType::Secret
47 } else {
48 match declared {
49 Some((_, ty)) => ty(types),
50 None => flat
51 .iter()
52 .find(|(name, _)| name == param.name.as_ref())
53 .map_or_else(|| FieldType::from_schema(&schema), |(_, ty)| ty.clone()),
54 }
55 };
56 ParamSurface {
57 name: param.name.to_string(),
58 required: param.required,
59 schema,
60 ty,
61 within: None,
62 }
63 })
64 .collect()
65}
66
67fn returns_of(
70 result: Option<&tilo_actions::ResultSpec>,
71 declared: Option<FieldTypeOf>,
72 types: &mut TypeSet,
73) -> Option<ReturnsSurface> {
74 let tilo_actions::ResultSpec::Json { schema } = result? else {
75 return None;
76 };
77 Some(ReturnsSurface {
78 schema: schema.clone(),
79 ty: declared.map_or_else(|| FieldType::from_schema(schema), |ty| ty(types)),
80 })
81}
82
83fn verb_of(decl: &Declaration, types: &mut TypeSet) -> VerbSurface {
84 VerbSurface {
85 id: decl.id.to_owned(),
86 name: String::new(),
87 label: decl.shown_label(),
88 description: decl.description.clone(),
89 kind: decl.kind,
90 destructive: decl.destructive,
91 incoming_message: decl
92 .tags
93 .iter()
94 .any(|tag| tag == tilo_actions::INCOMING_MESSAGE_TAG),
95 params: params_of(&decl.params, &decl.param_types, decl.flat_types, types),
96 returns: returns_of(decl.result.as_ref(), decl.result_type, types),
97 writes: decl.writes.clone(),
98 field: decl.field.map(str::to_owned),
99 tags: Vec::new(),
100 outside: Vec::new(),
101 notice: false,
102 origin: None,
103 }
104}
105
106fn framework_verb(id: &str, writes: Vec<String>) -> VerbSurface {
109 VerbSurface {
110 id: id.to_owned(),
111 name: String::new(),
112 label: String::new(),
113 description: None,
114 kind: crate::ActionKind::Undoable,
115 destructive: false,
116 incoming_message: false,
117 params: Vec::new(),
118 returns: None,
119 writes,
120 field: None,
121 tags: Vec::new(),
122 outside: Vec::new(),
123 notice: false,
124 origin: None,
125 }
126}
127
128fn units_of(shape: Shape) -> Vec<String> {
131 let mut units = vec![tilo_actions::surface::RESOURCE_UNIT.to_owned()];
132 if let Shape::Record(fields) = shape {
133 for field in fields.iter().filter(|field| field.unit) {
134 let unit = match field.shape {
135 Shape::Collection(_) | Shape::Keyed(_) => format!("{}.*", field.key),
136 _ => field.key.to_owned(),
137 };
138 if !units.contains(&unit) {
139 units.push(unit);
140 }
141 }
142 }
143 units
144}
145
146fn edits_content(shape: Shape) -> bool {
150 match shape {
151 Shape::Record(fields) => fields
152 .iter()
153 .any(|field| !field.readonly && edits_content(field.shape)),
154 Shape::Collection(_) | Shape::Keyed(_) | Shape::Map(_) | Shape::Value => true,
155 }
156}
157
158fn stored(shape: Shape) -> &'static str {
159 match shape {
160 Shape::Value | Shape::Map(_) => "value",
162 Shape::Record(_) => "record",
163 Shape::Collection(_) => "collection",
164 Shape::Keyed(_) => "keyed",
165 }
166}
167
168fn fields_of(shape: Shape, prefix: &str, types: &mut TypeSet, out: &mut Vec<FieldSurface>) {
169 let (fields, item) = match shape {
170 Shape::Record(fields) => (fields, false),
171 Shape::Collection(item) | Shape::Keyed(item) => {
172 fields_of(*item, &format!("{prefix}*."), types, out);
173 return;
174 }
175 Shape::Value | Shape::Map(_) => return,
176 };
177 let _ = item;
178 for field in fields {
179 let path = format!("{prefix}{}", field.key);
180 out.push(FieldSurface {
181 path: path.clone(),
182 owner: field.owner.to_owned(),
183 title: field.title.to_owned(),
184 stored: stored(field.shape).to_owned(),
185 ty: (field.field_type)(types),
186 readonly: field.readonly,
187 unit: field.unit,
188 label: field.label,
189 whole: false,
190 ops: None,
191 });
192 fields_of(field.shape, &format!("{path}."), types, out);
193 }
194}
195
196#[must_use]
198pub fn surface_of<R: Resource>() -> Surface {
199 surface_in(vocabulary::<R>(), R::VERSION)
200}
201
202fn surface_in(vocabulary: &crate::Vocabulary, version: u32) -> Surface {
204 let mut fields = Vec::new();
205 let mut types = TypeSet::new();
206 let shape = (vocabulary.shape)();
207 if let Some(shape) = shape {
208 fields_of(shape, "", &mut types, &mut fields);
209 }
210 for (path, schema) in (vocabulary.op_schemas)() {
211 if let Some(field) = fields.iter_mut().find(|field| field.path == path) {
212 field.ops = Some(schema);
213 }
214 }
215 let mut verbs = Vec::new();
216 for decl in vocabulary.declarations().iter() {
217 verbs.push(verb_of(decl, &mut types));
218 }
219 if let Some(shape) = shape
223 && edits_content(shape)
224 {
225 verbs.push(framework_verb(TYPE_VERB, units_of(shape)));
226 }
227 Surface {
228 kind: vocabulary.kind.to_owned(),
229 label: vocabulary.label.to_owned(),
230 version,
231 person: false,
232 readers: reader_rule(vocabulary.readers),
233 verbs,
234 fields,
235 types: types.into_types(),
236 shows: Vec::new(),
237 live: None,
238 setters: false,
239 }
240}
241
242fn reader_rule(readers: &str) -> Option<tilo_actions::surface::ReaderRule> {
245 tilo_actions::surface::ReaderRule::parse(readers)
246}
247
248#[must_use]
255pub fn reading_surface<R: crate::JsonSchema, E: crate::Effect>(kind: &str, label: &str) -> Surface {
256 let mut types = TypeSet::new();
257 let root = R::field_type(&mut types);
258 let verbs: Vec<VerbSurface> = E::declarations()
259 .iter()
260 .map(|decl| effect_verb(decl, &mut types))
261 .collect();
262 let mut declared = types.into_types();
263 let own = match &root {
266 FieldType::Named(name) => declared
267 .iter()
268 .position(|ty| ty.name == *name && !ty.is_enum())
269 .map(|at| declared.remove(at)),
270 _ => None,
271 };
272 let fields = own
273 .map(|own| {
274 own.fields
275 .into_iter()
276 .map(|field| FieldSurface {
277 path: field.name,
278 owner: String::new(),
279 title: field.title,
280 stored: "value".to_owned(),
281 ty: field.ty,
282 readonly: true,
283 unit: false,
284 label: false,
285 whole: false,
286 ops: None,
287 })
288 .collect()
289 })
290 .unwrap_or_default();
291 Surface {
292 kind: kind.to_owned(),
293 label: label.to_owned(),
294 version: 1,
295 person: false,
296 readers: None,
297 verbs,
298 fields,
299 types: declared,
300 shows: Vec::new(),
301 live: None,
302 setters: false,
303 }
304}
305
306#[must_use]
311pub fn row_surface<R: crate::words::RowType, E: crate::Effect>() -> Surface {
312 let mut types = TypeSet::new();
313 let verbs = E::declarations()
314 .iter()
315 .map(|decl| effect_verb(decl, &mut types))
316 .collect();
317 Surface {
318 kind: R::KIND.to_owned(),
319 label: R::LABEL.to_owned(),
320 version: 1,
321 person: false,
322 readers: None,
323 verbs,
324 fields: Vec::new(),
325 types: types.into_types(),
326 shows: Vec::new(),
327 live: None,
328 setters: false,
329 }
330}
331
332#[must_use]
335pub fn effect_verb(decl: &crate::EffectDecl, types: &mut TypeSet) -> VerbSurface {
336 VerbSurface {
337 id: decl.id.to_owned(),
338 name: String::new(),
339 label: decl.label.read(),
340 description: (!decl.description.is_empty()).then(|| decl.description.to_owned()),
341 kind: decl.action_kind,
342 destructive: decl.risk == tilo_actions::RiskLevel::Destructive,
343 incoming_message: false,
344 params: params_of(&decl.params, &decl.param_types, None, types),
345 returns: decl.result.map(|result| ReturnsSurface {
346 schema: (result.schema)(),
347 ty: result.ty.map_or_else(|| FieldType::Any, |ty| ty(types)),
348 }),
349 writes: vec!["record".to_owned()],
350 field: None,
351 tags: Vec::new(),
352 outside: Vec::new(),
353 notice: false,
354 origin: None,
355 }
356}
357
358#[must_use]
361pub fn view_effects(rows: &[crate::effect::EffectRow]) -> Vec<String> {
362 let mut shows: Vec<String> = rows
363 .iter()
364 .filter(|row| row.kind == tilo_actions::OperationKind::View)
365 .map(|row| row.id.to_owned())
366 .collect();
367 shows.sort();
368 shows.dedup();
369 shows
370}
371
372#[must_use]
380pub fn effect_verbs(rows: &[crate::effect::EffectRow], types: &mut TypeSet) -> Vec<VerbSurface> {
381 rows.iter()
382 .filter(|row| row.kind != tilo_actions::OperationKind::View)
383 .filter(|row| row.action_kind == crate::ActionKind::Read)
384 .filter(|row| !row.row)
385 .filter(|row| {
386 !row.items
387 .iter()
388 .any(|target| matches!(target, crate::effect::EffectTarget::Field(_)))
389 })
390 .map(|row| effect_verb(&crate::EffectDecl::of_row(row), types))
391 .collect()
392}
393
394#[doc(hidden)]
398pub fn resource_type(
399 types: &mut TypeSet,
400 identity: &str,
401 name: &str,
402 doc: &str,
403 shape: Shape,
404) -> FieldType {
405 types.named(identity, name, |types| NamedType {
406 tag: None,
407 name: name.to_owned(),
408 doc: doc.to_owned(),
409 fields: shape
410 .fields()
411 .iter()
412 .map(|field| TypeField {
413 name: field.key.to_owned(),
414 ty: (field.field_type)(types),
415 title: field.title.to_owned(),
416 })
417 .collect(),
418 cases: Vec::new(),
419 })
420}
421
422pub type FieldTypeOf = fn(&mut TypeSet) -> FieldType;
425
426#[doc(hidden)]
430pub fn resource_of(
431 types: &mut TypeSet,
432 identity: &str,
433 name: &str,
434 doc: &str,
435 fields: &[(&str, FieldTypeOf)],
436) -> FieldType {
437 types.named(identity, name, |types| NamedType {
438 tag: None,
439 name: name.to_owned(),
440 doc: doc.to_owned(),
441 fields: fields
442 .iter()
443 .map(|(field, ty)| TypeField {
444 name: (*field).to_owned(),
445 ty: ty(types),
446 title: String::new(),
447 })
448 .collect(),
449 cases: Vec::new(),
450 })
451}
452
453#[doc(hidden)]
456pub type CaseOf<'a> = (&'a str, &'a str, &'a [(&'a str, FieldTypeOf)]);
457
458#[doc(hidden)]
462pub fn enum_type(
463 types: &mut TypeSet,
464 identity: &str,
465 name: &str,
466 doc: &str,
467 cases: &[CaseOf<'_>],
468) -> FieldType {
469 types.named(identity, name, |types| NamedType {
470 tag: None,
471 name: name.to_owned(),
472 doc: doc.to_owned(),
473 fields: Vec::new(),
474 cases: cases
475 .iter()
476 .map(|(case, label, fields)| TypeCase {
477 name: (*case).to_owned(),
478 label: if label.is_empty() {
479 tilo_actions::field_type::label_of(case)
480 } else {
481 (*label).trim_end_matches('.').to_owned()
482 },
483 fields: fields
484 .iter()
485 .map(|(field, ty)| TypeField {
486 name: (*field).to_owned(),
487 ty: ty(types),
488 title: String::new(),
489 })
490 .collect(),
491 })
492 .collect(),
493 })
494}