tilo_actions/surface.rs
1//! A resource kind's public surface as data: its verbs with their
2//! parameters, kinds and the value each answers with, and its fields with
3//! their schema. An app's `surface.toml` holds it (written by `tilolang
4//! surface` from the code), and it is what a receiver without the app knows
5//! about the app's changes, and what another language compiles its actions
6//! and types against.
7//!
8//! The file keeps what receipt and the storage check need. The labels,
9//! descriptions, field titles and owners the code reports are for people and
10//! history; `tilolang surface` leaves them out of the file, so they read as
11//! empty here.
12
13use serde::{Deserialize, Serialize};
14
15use crate::PathStep;
16pub use crate::field_type::{FieldType, NamedType, TypeCase, TypeField, TypeSet};
17use tilo_action_policy::ActionKind;
18
19#[allow(
20 clippy::trivially_copy_pass_by_ref,
21 reason = "serde's skip_serializing_if passes the field by reference"
22)]
23const fn is_false(value: &bool) -> bool {
24 !*value
25}
26
27/// The record unit, as footprints and unit indexes name it.
28pub const RESOURCE_UNIT: &str = "record";
29
30/// The verb of a change that writes a record's content directly, with no finer action: typing
31/// in a cell, a list splice made from the window. The framework stamps such a change with it.
32pub const TYPE_VERB: &str = "type";
33
34/// The verbs the framework writes under on every record kind, which no app's action publishes:
35/// a direct content edit ([`TYPE_VERB`]). A storage migration is the store's own verb
36/// ([`crate::stamp::Stamp::MIGRATE_VERB`]), which no surface declares.
37pub const CONTENT_VERBS: [&str; 1] = [TYPE_VERB];
38
39/// The resource kinds the platform publishes on every app's surface rather than the app itself:
40/// the tilolang host, the person's place in an app, and the record an outside effect waits in.
41/// A program reaches them through the host, never as the app's own records, so they are neither
42/// types of the generated SDK nor resources of the API's description.
43pub const PLATFORM_KINDS: [&str; 3] = ["tl.host", "tilolang.personal", "tilolang.effect"];
44
45/// Whether `kind` is one the platform publishes rather than the app ([`PLATFORM_KINDS`]).
46#[must_use]
47pub fn platform_kind(kind: &str) -> bool {
48 PLATFORM_KINDS.contains(&kind)
49}
50
51/// The key under which a record of a reading that is a resource of its own (a Wi-Fi network in
52/// the network's reading) carries its address. Its type declares it as a field of that name,
53/// typed [`FieldType::Resource`] of the record's kind, and the kind's own surface lists the
54/// actions offered on it: a caller of another language calls them on that address, the way any
55/// caller does, so a row's `join` is its own action and never a root action taking its name.
56pub const ADDRESS_KEY: &str = "$address";
57
58/// The record kind in which the framework keeps each member's actions waiting
59/// for the part of a chain they go to (an app whose records are a chain's
60/// parts): one record per member, which an app keeping chains declares its
61/// members' own (`[resources] own`), so their waiting actions reach their own
62/// devices and nobody else's.
63pub const CHAIN_UNSENT_KIND: &str = "tilo.chain-unsent";
64
65/// The public surface of one resource kind. See the module docs.
66#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
67pub struct Surface {
68 pub kind: String,
69 pub label: String,
70 /// The storage version (`#[resource(version = N)]`).
71 pub version: u32,
72 /// A record of the person's own, kept in their store rather than the
73 /// workspace of the window showing it: one the app declares with itself
74 /// (its `ResourceApp::PERSON_RESOURCES`, as `PersonKind::profile`). Only
75 /// the kinds an app's surface marks so may it keep in, or read from, the
76 /// person's store.
77 #[serde(default, skip_serializing_if = "is_false")]
78 pub person: bool,
79 /// Who reads a record of the kind, when not every member of the workspace (core.md, "One set
80 /// of resources per workspace"): each record is sealed to exactly its readers' key group, and
81 /// the store works out who they are ([`ReaderRule`]). Absent for a kind every member reads.
82 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub readers: Option<ReaderRule>,
84 /// Absent from a surface file that lists none.
85 #[serde(default)]
86 pub verbs: Vec<VerbSurface>,
87 /// Every stored field, depth first; empty for a resource without a
88 /// model shape.
89 #[serde(default)]
90 pub fields: Vec<FieldSurface>,
91 /// The records and enums its fields' types name ([`FieldType::Named`]),
92 /// each declared once, by name.
93 #[serde(default, skip_serializing_if = "Vec::is_empty")]
94 pub types: Vec<NamedType>,
95 /// The actions that show something in a window of the app (its view
96 /// effects), on whatever resource of it they are invoked: a row the app
97 /// publishes for one person or item as much as the app itself. A closed
98 /// app asked for one is started with a window.
99 #[serde(default, skip_serializing_if = "Vec::is_empty")]
100 pub shows: Vec<String>,
101 /// When a resource of the kind is a live activity (a track playing, a timer running), and
102 /// the view that shows it then; `None` for a kind that never is.
103 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub live: Option<LiveSurface>,
105 /// Each of its fields is written by its own setter, `set-<field>`, and
106 /// by no field edit: the setters follow from the fields
107 /// ([`Self::with_setters`]), as a settings section publishes them.
108 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
109 pub setters: bool,
110}
111
112/// When a resource of a kind is live, as the resource index keeps it: what its type says
113/// (`live when state == .playing`) as filters over the fields the index holds, every one of
114/// which holds of a live resource.
115#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
116pub struct LiveSurface {
117 /// The store's filters (`collab_types::store::Filter`) as JSON: this crate does not know the
118 /// store's types, and the store reads them back when it declares the kind.
119 pub when: serde_json::Value,
120 /// The name of the view the shell shows a live resource with.
121 pub view: String,
122}
123
124pub use tilo_action_policy::ReaderRule;
125
126/// One verb.
127#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
128pub struct VerbSurface {
129 pub id: String,
130 /// The name the action API offers this action by, where that is not `id`: a tilolang app
131 /// offers its actions by the name its code declares (`new_note`), while a change of one
132 /// claims the id the declaration keeps (`qymo5lg2`), which is what a receiver holding the
133 /// surface decides it by. Empty where the two are the same, as for a native verb.
134 #[serde(default, skip_serializing_if = "String::is_empty")]
135 pub name: String,
136 #[serde(default, skip_serializing_if = "String::is_empty")]
137 pub label: String,
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub description: Option<String>,
140 pub kind: ActionKind,
141 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
142 pub destructive: bool,
143 /// It records a message someone received, so an incoming-message
144 /// trigger fires on its changes
145 /// ([`INCOMING_MESSAGE_TAG`](crate::INCOMING_MESSAGE_TAG)).
146 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
147 pub incoming_message: bool,
148 /// Left out of a surface file when it takes none.
149 #[serde(default)]
150 pub params: Vec<ParamSurface>,
151 /// What it answers its caller with, when it answers a value: a read
152 /// effect's fields, a verb's record. Absent when it answers nothing or a
153 /// job.
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub returns: Option<ReturnsSurface>,
156 /// The units it writes (`tilo_resource::footprint`), when more than the
157 /// record unit.
158 #[serde(default = "record_unit", skip_serializing_if = "only_resource")]
159 pub writes: Vec<String>,
160 /// The field it sits under in the tree (`#[action(field = "...")]`): a
161 /// comment verb under the comments it writes.
162 #[serde(default, skip_serializing_if = "Option::is_none")]
163 pub field: Option<String>,
164 /// The tags its declaration carries ([`crate::SECRET_ANSWER_TAG`]): what a host reading the
165 /// surface knows of the action without running the app.
166 #[serde(default, skip_serializing_if = "Vec::is_empty")]
167 pub tags: Vec<String>,
168 /// The outside capabilities its code can queue (`smtp.send`), as its `outside(...)` calls
169 /// name them: a change that writes an entry for one is admitted only from a verb that
170 /// declares it (a tilolang app's surface), so what an app may reach beyond the workspace is
171 /// known before any of its code runs.
172 #[serde(default, skip_serializing_if = "Vec::is_empty")]
173 pub outside: Vec<String>,
174 /// Whether its code can tell a person something (`notify(...)`): a change that writes a
175 /// notice is admitted only from a verb that says so.
176 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
177 pub notice: bool,
178 /// On the surface's origin verb ([`crate::stamp::Stamp::ORIGIN_VERB`]): the outside
179 /// service kind the surface's records are of, as its type declares it (`imap.message`).
180 /// `None` for every other verb, and for a surface whose records no service keeps in step.
181 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub origin: Option<String>,
183}
184
185fn stored_value() -> String {
186 STORED_VALUE.to_owned()
187}
188
189impl VerbSurface {
190 /// The name the action API offers this action by: [`Self::name`], or [`Self::id`] where the
191 /// two are the same.
192 #[must_use]
193 pub fn offered(&self) -> &str {
194 if self.name.is_empty() {
195 &self.id
196 } else {
197 &self.name
198 }
199 }
200
201 /// Whether the store writes this verb itself rather than an app declaring it as an action a
202 /// caller invokes: the framework's content edit on every kind ([`CONTENT_VERBS`]) and the
203 /// store's migration ([`Stamp::MIGRATE_VERB`]).
204 #[must_use]
205 pub fn is_store_verb(&self) -> bool {
206 let action = self.offered();
207 CONTENT_VERBS.contains(&action) || action == crate::stamp::Stamp::MIGRATE_VERB
208 }
209
210 /// Whether this is the platform's or the framework's own verb rather than an action a
211 /// caller invokes: the store's verbs ([`Self::is_store_verb`]), the names the platform
212 /// writes with `$` (`$create`, `$send`, `$settle`), and the bound-control edits a host
213 /// declares without the prefix (`edit-text`, `edit-flag`).
214 #[must_use]
215 pub fn is_platform(&self) -> bool {
216 let action = self.offered();
217 self.is_store_verb()
218 || action.starts_with('$')
219 || matches!(action, "edit-text" | "edit-flag")
220 }
221}
222
223/// How a field holding a plain value is stored.
224pub const STORED_VALUE: &str = "value";
225
226fn record_unit() -> Vec<String> {
227 vec![RESOURCE_UNIT.to_owned()]
228}
229
230fn only_resource(units: &[String]) -> bool {
231 units == [RESOURCE_UNIT]
232}
233
234/// One parameter of a verb.
235#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
236pub struct ParamSurface {
237 pub name: String,
238 pub required: bool,
239 /// Its JSON Schema, from its type.
240 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
241 pub schema: serde_json::Value,
242 /// Its type ([`FieldType`]), its named records and enums declared in
243 /// the surface's types; left out of a file, and absent from one written
244 /// before parameters had it, when the schema says all there is.
245 #[serde(
246 rename = "type",
247 default,
248 skip_serializing_if = "FieldType::is_any",
249 deserialize_with = "crate::field_type::field_type_or_text"
250 )]
251 pub ty: FieldType,
252 /// The parameter this one is a field of on the wire: a parameter that is a plain record
253 /// of named fields is published as those fields, and a call's arguments for them travel
254 /// nested under its name again ([`nest_arguments`]).
255 #[serde(default, skip_serializing_if = "Option::is_none")]
256 pub within: Option<String>,
257}
258
259/// What an action answers its caller with: its JSON Schema, and its type
260/// ([`FieldType`]) with the records and enums it names declared in the
261/// surface's types.
262///
263/// A surface is what another language compiles against, so the value an
264/// action gives back has to be described as precisely as it takes: a script
265/// reads the fields of a PDF's form without opening the PDF.
266#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
267pub struct ReturnsSurface {
268 /// Its JSON Schema, from its type.
269 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
270 pub schema: serde_json::Value,
271 /// Its type, left out when the schema says all there is (`any`).
272 #[serde(
273 rename = "type",
274 default,
275 skip_serializing_if = "FieldType::is_any",
276 deserialize_with = "crate::field_type::field_type_or_text"
277 )]
278 pub ty: FieldType,
279}
280
281/// The type a parameter is published as, from its wire type. A resource is a resource of the
282/// kind it names, or of any kind: code passes the value it has, never its id's text. An object
283/// or a list says nothing more than its schema does ([`FieldType::Any`]).
284#[must_use]
285pub fn param_type(param: &crate::ActionParam) -> FieldType {
286 use crate::ParamType;
287 match param.ty {
288 ParamType::Text | ParamType::DateTime => FieldType::Text,
289 ParamType::Secret => FieldType::Secret,
290 ParamType::Resource => {
291 FieldType::Resource(param.resource_kind().unwrap_or_default().to_owned())
292 }
293 ParamType::Integer => FieldType::Int,
294 ParamType::Number => FieldType::Float,
295 ParamType::Boolean => FieldType::Bool,
296 // A list or object whose schema says what it holds is typed by it, so code can give it
297 // (`List<Text>`); one that says nothing is any JSON value.
298 ParamType::Object | ParamType::Array => param
299 .schema
300 .as_deref()
301 .map_or(FieldType::Any, FieldType::from_schema),
302 }
303}
304
305/// `action` as a verb taking `params`: its id and kind, and whether it destroys. The words a
306/// person reads of it are the catalogue's, not the surface's.
307#[must_use]
308pub fn verb_of(action: &crate::ActionSpec, params: Vec<ParamSurface>) -> VerbSurface {
309 VerbSurface {
310 id: action.id.clone(),
311 name: String::new(),
312 label: String::new(),
313 description: None,
314 kind: action.contract.settled_kind(),
315 destructive: action.contract.risk == crate::RiskLevel::Destructive,
316 incoming_message: false,
317 params,
318 returns: result_of(&action.contract.result),
319 writes: record_unit(),
320 field: None,
321 tags: Vec::new(),
322 outside: Vec::new(),
323 notice: false,
324 origin: None,
325 }
326}
327
328/// What an action answers, as its surface says it: a call the surface declares a result for
329/// reads it back in tilolang.
330fn result_of(result: &crate::ResultSpec) -> Option<ReturnsSurface> {
331 match result {
332 crate::ResultSpec::Json { schema } => Some(ReturnsSurface {
333 schema: schema.clone(),
334 ty: crate::field_type::FieldType::from_schema(schema),
335 }),
336 crate::ResultSpec::None | crate::ResultSpec::Resource { .. } | crate::ResultSpec::Job => {
337 None
338 }
339 }
340}
341
342/// The resource `spec` as a surface: its kind and a verb for each of its actions, each
343/// parameter typed by its wire type ([`param_type`]). What a provider publishing it at a fixed
344/// address is compiled against: it stores no fields, so its verbs are called at that address.
345#[must_use]
346pub fn of_resource(spec: &crate::ResourceSpec) -> Surface {
347 let verbs = spec
348 .actions
349 .iter()
350 .map(|action| {
351 let params = action
352 .params()
353 .iter()
354 .map(|param| ParamSurface {
355 name: param.name.to_string(),
356 required: param.required,
357 schema: serde_json::Value::Null,
358 ty: param_type(param),
359 within: None,
360 })
361 .collect();
362 verb_of(action, params)
363 })
364 .collect();
365 Surface {
366 kind: spec.kind.clone(),
367 label: String::new(),
368 version: 0,
369 person: false,
370 readers: None,
371 verbs,
372 fields: Vec::new(),
373 types: Vec::new(),
374 shows: Vec::new(),
375 live: None,
376 setters: false,
377 }
378}
379
380/// The arguments of a call of `verb`, as `(name, value)`, with each argument of a parameter
381/// published as a field of another ([`ParamSurface::within`]) nested back under that
382/// parameter's name: what the action's API reads.
383#[must_use]
384pub fn nest_arguments(
385 verb: &VerbSurface,
386 arguments: Vec<(String, serde_json::Value)>,
387) -> serde_json::Map<String, serde_json::Value> {
388 let mut out = serde_json::Map::new();
389 for (name, value) in arguments {
390 let within = verb
391 .params
392 .iter()
393 .find(|param| param.name == name)
394 .and_then(|param| param.within.clone());
395 match within {
396 Some(outer) => {
397 let nested = out
398 .entry(outer)
399 .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
400 if let serde_json::Value::Object(fields) = nested {
401 fields.insert(name, value);
402 }
403 }
404 None => {
405 out.insert(name, value);
406 }
407 }
408 }
409 out
410}
411
412/// One stored field.
413#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
414#[expect(
415 clippy::struct_excessive_bools,
416 reason = "each flag is one mark a committed surface file writes for the field, read on its own"
417)]
418pub struct FieldSurface {
419 /// Where it is: stored keys from the root, `*` for every item of a
420 /// collection (`snippets.*.title`).
421 pub path: String,
422 /// The record type it belongs to, kebab case.
423 #[serde(default, skip_serializing_if = "String::is_empty")]
424 pub owner: String,
425 #[serde(default, skip_serializing_if = "String::is_empty")]
426 pub title: String,
427 /// How it is stored: `value` (left out of a surface file), `record` or
428 /// `collection`.
429 #[serde(default = "stored_value")]
430 pub stored: String,
431 /// Its type ([`FieldType`]); a surface file written before the
432 /// vocabulary holds its Rust type's text, read as
433 /// [`FieldType::from_rust_text`].
434 #[serde(
435 rename = "type",
436 deserialize_with = "crate::field_type::field_type_or_text"
437 )]
438 pub ty: FieldType,
439 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
440 pub readonly: bool,
441 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
442 pub unit: bool,
443 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
444 pub label: bool,
445 /// Set only whole: a change inside it could weaken the person's security,
446 /// so its setter takes no edit inside it ([`Surface::with_setters`]).
447 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
448 pub whole: bool,
449 /// The schema of the field's own operations, for a type with its own
450 /// vocabulary (rich text).
451 #[serde(default, skip_serializing_if = "Option::is_none")]
452 pub ops: Option<serde_json::Value>,
453}
454
455/// A map field of a declared kind, keeping its items under their keys: `path`, the record type
456/// `owner` it belongs to, and the `title` a person reads it by.
457#[must_use]
458pub fn map_field(path: &str, owner: &str, title: &str) -> FieldSurface {
459 FieldSurface {
460 path: path.to_owned(),
461 owner: owner.to_owned(),
462 title: title.to_owned(),
463 stored: "value".to_owned(),
464 ty: FieldType::Map(Box::new(FieldType::Any)),
465 readonly: false,
466 unit: false,
467 label: false,
468 whole: false,
469 ops: None,
470 }
471}
472
473/// The verb `id`, `label`led, that a change of a record's content names.
474#[must_use]
475pub fn content_verb(id: &str, label: &str) -> VerbSurface {
476 VerbSurface {
477 id: id.to_owned(),
478 name: String::new(),
479 label: label.to_owned(),
480 description: None,
481 kind: tilo_action_policy::ActionKind::Undoable,
482 destructive: false,
483 incoming_message: false,
484 params: Vec::new(),
485 returns: None,
486 writes: Vec::new(),
487 field: None,
488 tags: Vec::new(),
489 outside: Vec::new(),
490 notice: false,
491 origin: None,
492 }
493}
494
495/// The verb that sets the field `key` whole: `set-<key>`, in kebab case.
496#[must_use]
497pub fn setter_id(key: &str) -> String {
498 format!("set-{}", key.replace('_', "-"))
499}
500
501/// What a receiver without the app reads from its surface: each verb's kind
502/// and tree field, which paths offer field edits, and which storage units
503/// an action may write (`*` for any item).
504impl Surface {
505 /// This surface with a setter of each of its own fields that is not read
506 /// only and has no declared verb of the setter's id, as a settings section
507 /// publishes them: [`setter_id`], taking the field's whole new `value` (not
508 /// for a collection or a keyed map, which change item by item) and, unless
509 /// the field is set only [`FieldSurface::whole`], an `edit` inside it.
510 #[must_use]
511 pub fn with_setters(mut self) -> Self {
512 let setters: Vec<VerbSurface> = self
513 .fields
514 .iter()
515 .filter(|field| !field.readonly && !field.path.contains('.'))
516 .map(|field| (setter_id(&field.path), field))
517 .filter(|(id, _)| !self.verbs.iter().any(|verb| verb.id == *id))
518 .map(|(id, field)| {
519 let param = |name: &str, ty: FieldType| ParamSurface {
520 name: name.to_owned(),
521 required: false,
522 schema: serde_json::Value::Null,
523 ty,
524 within: None,
525 };
526 let mut params = Vec::new();
527 if !matches!(field.stored.as_str(), "collection" | "keyed") {
528 params.push(param("value", field.ty.clone()));
529 }
530 if !field.whole {
531 params.push(param("edit", FieldType::Any));
532 }
533 VerbSurface {
534 id,
535 name: String::new(),
536 label: format!("Set {}", field.path.replace('_', " ")),
537 description: None,
538 kind: ActionKind::Undoable,
539 destructive: false,
540 incoming_message: false,
541 params,
542 returns: None,
543 writes: vec![RESOURCE_UNIT.to_owned()],
544 field: None,
545 tags: Vec::new(),
546 outside: Vec::new(),
547 notice: false,
548 origin: None,
549 }
550 })
551 .collect();
552 self.verbs.extend(setters);
553 self
554 }
555
556 /// The named type `name` of [`Self::types`].
557 #[must_use]
558 pub fn named(&self, name: &str) -> Option<&NamedType> {
559 self.types.iter().find(|ty| ty.name == name)
560 }
561
562 /// The kind of the verb `action` and the field it sits under, or `None`
563 /// when the app publishes no such verb.
564 #[must_use]
565 pub fn verb(&self, action: &str) -> Option<(ActionKind, Option<String>)> {
566 self.verbs
567 .iter()
568 .find(|verb| verb.id == action)
569 .map(|verb| (verb.kind, verb.field.clone()))
570 }
571
572 /// The stored field a path (from the record's root) reaches: the
573 /// deepest one its steps name, items and keys as `*`.
574 fn field_at(&self, path: &[PathStep]) -> Option<&FieldSurface> {
575 let mut dotted = String::new();
576 let mut found = None;
577 for step in path {
578 let part = match step {
579 PathStep::Field(key) => key.as_str(),
580 PathStep::Item(_) | PathStep::Key(_) | PathStep::Cell(..) => "*",
581 };
582 if !dotted.is_empty() {
583 dotted.push('.');
584 }
585 dotted.push_str(part);
586 if let Some(field) = self.fields.iter().find(|field| field.path == dotted) {
587 found = Some(field);
588 }
589 }
590 found
591 }
592
593 /// Whether the field at `path` offers edits: stored, and neither it nor
594 /// a field above it read-only. Reactions are the exception: their only
595 /// edits record who invoked them, so they forge nothing a read-only
596 /// field protects, and the record refuses any other edit of them.
597 #[must_use]
598 pub fn editable(&self, path: &[PathStep]) -> bool {
599 let Some(field) = self.field_at(path) else {
600 return false;
601 };
602 if field.ty.is_reactions() {
603 return true;
604 }
605 !self.fields.iter().any(|candidate| {
606 candidate.readonly
607 && (field.path == candidate.path
608 || field.path.starts_with(&format!("{}.", candidate.path)))
609 })
610 }
611
612 /// The storage unit a field edit at `path` writes: the field's unit, an
613 /// item of a unit collection, else the record (the empty path).
614 #[must_use]
615 pub fn edit_unit(&self, path: &[PathStep]) -> Vec<PathStep> {
616 let mut dotted = String::new();
617 let mut unit = Vec::new();
618 for (index, step) in path.iter().enumerate() {
619 let PathStep::Field(key) = step else {
620 if !dotted.is_empty() {
621 dotted.push('.');
622 }
623 dotted.push('*');
624 continue;
625 };
626 if !dotted.is_empty() {
627 dotted.push('.');
628 }
629 dotted.push_str(key);
630 let Some(field) = self.fields.iter().find(|field| field.path == dotted) else {
631 continue;
632 };
633 if field.unit {
634 let through = if matches!(field.stored.as_str(), "collection" | "keyed") {
635 index.saturating_add(2)
636 } else {
637 index.saturating_add(1)
638 };
639 unit = path.iter().take(through).cloned().collect();
640 }
641 }
642 unit
643 }
644
645 /// The units the verb `action` may write, on the item `item` when it
646 /// acts on one: the record (the empty path), its item's unit, and the
647 /// units of the fields it declares, `*` for any item.
648 #[must_use]
649 pub fn footprint(&self, action: &str, item: Option<&str>) -> Vec<Vec<PathStep>> {
650 let Some(verb) = self.verbs.iter().find(|verb| verb.id == action) else {
651 return Vec::new();
652 };
653 verb.writes
654 .iter()
655 .map(|unit| {
656 if unit == RESOURCE_UNIT {
657 return Vec::new();
658 }
659 match unit.strip_suffix(".*") {
660 Some(field) => vec![
661 PathStep::Field(field.to_owned()),
662 PathStep::Item(item.unwrap_or("*").to_owned()),
663 ],
664 None => vec![PathStep::Field(unit.clone())],
665 }
666 })
667 .collect()
668 }
669}