Skip to main content

adk_surface/genui/
validate.rs

1//! The rule 5 validator (spec 3.3 §7.4 rule 5): agent-drawn UI never contains approval
2//! controls, never asks for a secret, and shows only what the home's catalog renders.
3//!
4//! A drawing is checked whole, every time it changes: its structure and every component
5//! against the catalog, then every string a person would read, resolved on the server from
6//! literals, data model bindings and `formatString` and `pluralize` results, against the
7//! reserved words of a decision after [`fold_display_text`].
8
9use std::collections::{BTreeMap, BTreeSet};
10use std::sync::LazyLock;
11
12use adk_harness::approvals::matcher::fold_display_text;
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15use serde_json::{Map, Value};
16
17use super::a2ui::DataModel;
18use super::catalog::{Catalog, ChildSlot, ExtensionComponent, HomeNode, ResolvedComponent};
19use super::drawn::{ChartAxis, ChartKind, DrawnChart, DrawnKind, RefusalKind};
20
21mod scenes;
22
23/// Phrases of a decision and of the controls every surface owns, refused anywhere in a
24/// drawing after folding (spec 3.3 §8.1, §8.2; wave 4 decision 20).
25pub const RESERVED_PHRASES: &[&str] = &[
26    "Allow once",
27    "Always allow",
28    "Waiting for you",
29    "You said yes",
30    "You said no",
31    "Confirm it's you",
32    "Stop all",
33    "Resume all",
34    "Take over",
35    "Add this agent",
36];
37
38/// Words of a decision refused when they are a whole label or heading, so "Edit address"
39/// is shown and "Edit" is not (wave 4 decision 20), and "Don't add sugar" is shown and the
40/// suggested agent's "Don't add" is not (spec 3.3 §8.2).
41pub const RESERVED_LABELS: &[&str] =
42    &["Edit", "Deny", "Done", "Approve", "Approved", "Decided", "Don't add"];
43
44/// The most components a drawing has.
45pub const MAX_COMPONENTS: usize = 256;
46/// The deepest a component tree nests.
47pub const MAX_DEPTH: usize = 16;
48/// The most components a drawing shows once its templates are expanded.
49pub const MAX_SHOWN: usize = 2_000;
50/// The most items a template renders from one list.
51pub const MAX_LIST_ITEMS: usize = 500;
52/// The longest string a drawing shows, in characters.
53pub const MAX_TEXT_CHARS: usize = 4_000;
54/// The most bytes a drawing's components, data model and actions take as JSON.
55pub const MAX_DRAWING_BYTES: usize = 128 * 1024;
56/// The most actions a drawing declares.
57pub const MAX_ACTIONS: usize = 8;
58/// The most bytes the resolved properties of a drawing's extension components take as JSON,
59/// bound data included, so a chart in a list template cannot multiply its data unchecked.
60pub const MAX_RESOLVED_BYTES: usize = 256 * 1024;
61/// The most 3D scenes a drawing shows, its templates' copies counted: each takes a WebGL
62/// context in the home.
63pub const MAX_SCENES: usize = 4;
64/// The most objects a scene has.
65pub const MAX_SCENE_OBJECTS: usize = 256;
66/// The most bars and points a scene draws, in all.
67pub const MAX_SCENE_INSTANCES: usize = 4_096;
68/// The most points a scene's lines pass through, in all.
69pub const MAX_SCENE_LINE_POINTS: usize = 4_096;
70/// The most points along one side of a scene's grid.
71pub const MAX_SCENE_GRID_SIDE: u16 = 96;
72/// The most strings a scene shows: labels, axis names and ticks.
73pub const MAX_SCENE_TEXTS: usize = 128;
74/// The longest string a scene shows, in characters.
75pub const MAX_SCENE_TEXT_CHARS: usize = 80;
76/// The most held components a scene shows beside its objects.
77pub const MAX_SCENE_PANELS: usize = 8;
78/// The most objects of a scene that move.
79pub const MAX_SCENE_MOTIONS: usize = 32;
80/// The most lights a scene adds to its preset.
81pub const MAX_SCENE_LIGHTS: usize = 3;
82/// The deepest a scene's groups nest.
83pub const MAX_SCENE_GROUP_DEPTH: usize = 4;
84/// The most bytes a scene takes as JSON.
85pub const MAX_SCENE_BYTES: usize = 256 * 1024;
86/// The most children a depth effect presents.
87pub const MAX_DEPTH_CHILDREN: usize = 12;
88/// The most nodes one extension component's home view has.
89const MAX_HOME_NODES: usize = 64;
90/// The deepest one extension component's home view nests.
91const MAX_HOME_DEPTH: usize = 4;
92/// The deepest an extension component's properties, or the data they bind, nest.
93const MAX_PROP_DEPTH: usize = 16;
94/// The most series a chart has: one per chart colour.
95const MAX_CHART_SERIES: usize = 8;
96/// The most slices a pie has.
97const MAX_PIE_SLICES: usize = 8;
98/// The most labelled ticks a chart's axis has.
99const MAX_CHART_TICKS: usize = 16;
100
101/// The functions a drawing may call to check a field.
102const CHECK_FUNCTIONS: &[&str] =
103    &["required", "regex", "length", "numeric", "email", "and", "or", "not"];
104/// The functions whose text the server resolves for display.
105const TEXT_FUNCTIONS: &[&str] = &["formatString", "pluralize"];
106/// The components a person types or picks a value in.
107const INPUTS: &[&str] = &["TextField", "CheckBox", "ChoicePicker", "Slider", "DateTimeInput"];
108
109/// Words that name a secret, matched as whole words of a field's label, id or path.
110const SECRET_WORDS: &[&str] = &[
111    "password",
112    "passwords",
113    "passcode",
114    "passphrase",
115    "pin",
116    "secret",
117    "token",
118    "apikey",
119    "otp",
120    "totp",
121    "2fa",
122    "mfa",
123    "cvv",
124    "cvc",
125    "ssn",
126    "mnemonic",
127];
128/// Phrases that name a secret.
129const SECRET_PHRASES: &[&str] = &[
130    "api key",
131    "secret key",
132    "private key",
133    "access key",
134    "card number",
135    "credit card",
136    "security code",
137    "one time code",
138    "one time password",
139    "verification code",
140    "recovery code",
141    "seed phrase",
142    "social security",
143];
144
145/// An argument of a [`DrawnAction`]: the value a person typed in a field, or a constant the
146/// drawing fixes.
147///
148/// An object with only `path` is a field binding; anything else is a constant.
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
150#[serde(untagged)]
151pub enum ActionArg {
152    /// The value at a field's data model path.
153    Field(FieldArg),
154    /// A constant.
155    Constant(Value),
156}
157
158/// The value at a field's data model path.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
160#[serde(deny_unknown_fields)]
161pub struct FieldArg {
162    /// The field's absolute data model path, such as `/to`.
163    pub path: String,
164}
165
166/// An action a drawing declares: a button `label` that asks to run `tool` with `args`
167/// (spec 3.3 §7.4 rule 5). Pressing it never runs the tool: it sends a requested call,
168/// which waits for the person's decision.
169///
170/// # Example
171///
172/// ```rust
173/// use adk_surface::genui::{ActionArg, DrawnAction, FieldArg};
174/// use serde_json::json;
175///
176/// let send: DrawnAction = serde_json::from_value(json!({
177///     "id": "send",
178///     "label": "Send",
179///     "tool": "send_invoice",
180///     "args": { "to": { "path": "/to" }, "invoice": "INV-10" }
181/// }))
182/// .unwrap();
183/// assert_eq!(send.args["to"], ActionArg::Field(FieldArg { path: "/to".into() }));
184/// assert_eq!(send.args["invoice"], ActionArg::Constant(json!("INV-10")));
185/// ```
186#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
187#[serde(rename_all = "camelCase", deny_unknown_fields)]
188pub struct DrawnAction {
189    /// The action's id, which a button's event names.
190    pub id: String,
191    /// The button's text.
192    pub label: String,
193    /// The tool the person asks to run: one of the drawing agent's own tools.
194    pub tool: String,
195    /// The tool's arguments.
196    #[serde(default)]
197    pub args: BTreeMap<String, ActionArg>,
198}
199
200/// A drawing before it is checked: its components, data model and actions (spec 3.3 §6.1
201/// `genui`).
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
203#[serde(rename_all = "camelCase")]
204pub struct SurfaceDraft {
205    /// The surface's id.
206    pub surface_id: String,
207    /// What it is.
208    pub kind: DrawnKind,
209    /// The title above it.
210    #[serde(default, skip_serializing_if = "Option::is_none")]
211    pub title: Option<String>,
212    /// Its A2UI components, one with id `root`.
213    pub components: Vec<Value>,
214    /// Its data model.
215    #[serde(default)]
216    pub data_model: Value,
217    /// Its actions.
218    #[serde(default, skip_serializing_if = "Vec::is_empty")]
219    pub actions: Vec<DrawnAction>,
220}
221
222/// A string a drawing shows, resolved on the server (spec 3.3 §7.4 rule 5).
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
224#[serde(rename_all = "camelCase")]
225pub struct ResolvedText {
226    /// The component, or `None` for the drawing's title and actions.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub component_id: Option<String>,
229    /// The list item a template rendered it for, as a data model path.
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub item: Option<String>,
232    /// The property, such as `text`, `label` or `options/0/label`.
233    pub field: String,
234    /// What a person reads.
235    pub text: String,
236}
237
238/// A drawing that passed every check, with every string it shows.
239#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
240#[serde(rename_all = "camelCase")]
241pub struct ValidatedSurface {
242    /// The drawing.
243    pub draft: SurfaceDraft,
244    /// Every string it shows, in tree order.
245    pub texts: Vec<ResolvedText>,
246    /// What it should say differently: dark patterns, at warning severity (it is shown).
247    #[serde(default, skip_serializing_if = "Vec::is_empty")]
248    pub warnings: Vec<ValidationResult>,
249    /// What each extension component shows, by component id and list item, as checked: the
250    /// projection draws these and never resolves or projects a component again.
251    #[serde(skip)]
252    pub(crate) extensions: BTreeMap<(String, String), ExtensionView>,
253}
254
255/// An extension component as checked: its resolved properties, what the home shows for it,
256/// and the ids its slots hold, in order.
257#[derive(Debug, Clone, PartialEq)]
258pub(crate) struct ExtensionView {
259    pub(crate) component: String,
260    pub(crate) props: Value,
261    pub(crate) home: HomeNode,
262    pub(crate) children: Vec<String>,
263}
264
265/// The component a refusal is about.
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
267#[serde(rename_all = "camelCase")]
268pub struct ComponentRef {
269    /// Its id.
270    pub id: String,
271    /// Its type, such as `Button`.
272    pub component: String,
273}
274
275/// A refused drawing: what it looked like to a person, and the technical reason the
276/// developer panel and the terminal show (spec 3.3 §7.4 rule 5).
277///
278/// # Example
279///
280/// ```rust
281/// use adk_surface::genui::{ComponentRef, DrawRefusal, RefusalKind};
282///
283/// let refusal = DrawRefusal {
284///     kind: RefusalKind::LooksLikeDecision,
285///     catalog: "forms 1.0".into(),
286///     component: Some(ComponentRef { id: "c7".into(), component: "Button".into() }),
287///     detail: "label matches reserved word \"Allow once\" after normalisation".into(),
288/// };
289/// assert_eq!(
290///     refusal.technical(),
291///     "catalog forms 1.0 · component c7 Button · label matches reserved word \"Allow once\" \
292///      after normalisation"
293/// );
294/// assert_eq!(refusal.code(), "genui.refused.looks_like_decision");
295/// ```
296#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, thiserror::Error)]
297#[serde(rename_all = "camelCase")]
298#[error("{}", self.message())]
299pub struct DrawRefusal {
300    /// What it looked like.
301    pub kind: RefusalKind,
302    /// The catalog it was checked against, such as `forms 1.0`.
303    pub catalog: String,
304    /// The component at fault, if one is.
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub component: Option<ComponentRef>,
307    /// What is wrong, in technical words.
308    pub detail: String,
309}
310
311impl DrawRefusal {
312    /// The technical reason: catalog, component and detail.
313    pub fn technical(&self) -> String {
314        match &self.component {
315            Some(component) => format!(
316                "catalog {} · component {} {} · {}",
317                self.catalog, component.id, component.component, self.detail
318            ),
319            None => format!("catalog {} · {}", self.catalog, self.detail),
320        }
321    }
322
323    /// The error code of the drawing tool's refusal.
324    pub fn code(&self) -> &'static str {
325        match self.kind {
326            RefusalKind::LooksLikeDecision => "genui.refused.looks_like_decision",
327            RefusalKind::AsksForSecret => "genui.refused.asks_for_secret",
328            RefusalKind::CannotShow => "genui.refused.cannot_show",
329        }
330    }
331
332    /// What the drawing agent is told: why it was not shown and what to do instead, then
333    /// the technical reason.
334    pub fn message(&self) -> String {
335        let plain = match self.kind {
336            RefusalKind::LooksLikeDecision => {
337                "Not shown: it looks like a decision. A drawing never shows approval controls or \
338                 a decision's words; the person decides on the home's own card. Draw it without \
339                 them"
340            }
341            RefusalKind::AsksForSecret => {
342                "Not shown: a drawn form never asks for a password or another secret. Ask the \
343                 person to use Take over for passwords"
344            }
345            RefusalKind::CannotShow => {
346                "Not shown: this home can't show it. Use only the catalog's components, no \
347                 links, and the declared actions"
348            }
349        };
350        format!("{plain}. ({})", self.technical())
351    }
352
353    /// The refusal in A2UI 1.0's `ValidationResult` shape: not valid, severity `error`, its
354    /// code, and its technical reason as the message.
355    pub fn validation_result(&self) -> ValidationResult {
356        ValidationResult {
357            valid: false,
358            severity: Severity::Error,
359            code: Some(self.code().to_string()),
360            message: Some(self.technical()),
361        }
362    }
363}
364
365/// How much a check's finding matters (A2UI 1.0 `ValidationResult.severity`).
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
367#[serde(rename_all = "lowercase")]
368pub enum Severity {
369    /// The drawing is refused.
370    #[default]
371    Error,
372    /// The drawing is shown; the agent is told what to change.
373    Warning,
374    /// A note.
375    Info,
376}
377
378/// A check's result in A2UI 1.0's `ValidationResult` shape: a refusal is `valid: false` with
379/// severity `error`; a drawing that is shown may carry warnings.
380///
381/// # Example
382///
383/// ```rust
384/// use adk_surface::genui::{Severity, ValidationResult};
385///
386/// let result = ValidationResult::warning("genui.warned.urgency", "Says 'only 2 left'.");
387/// let wire = serde_json::to_value(&result).unwrap();
388/// assert_eq!(wire["valid"], true);
389/// assert_eq!(wire["severity"], "warning");
390/// assert_eq!(result.severity, Severity::Warning);
391/// ```
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
393pub struct ValidationResult {
394    /// Whether the drawing passes.
395    pub valid: bool,
396    /// How much it matters.
397    #[serde(default)]
398    pub severity: Severity,
399    /// A machine-readable code.
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub code: Option<String>,
402    /// What to change, in words.
403    #[serde(default, skip_serializing_if = "Option::is_none")]
404    pub message: Option<String>,
405}
406
407impl ValidationResult {
408    /// A warning on a drawing that is still shown.
409    pub fn warning(code: impl Into<String>, message: impl Into<String>) -> Self {
410        Self {
411            valid: true,
412            severity: Severity::Warning,
413            code: Some(code.into()),
414            message: Some(message.into()),
415        }
416    }
417}
418
419/// Checks drawings against a catalog and rule 5 (spec 3.3 §7.4 rule 5).
420///
421/// # Example
422///
423/// ```rust
424/// use adk_surface::genui::{DrawnKind, RefusalKind, SurfaceDraft, Validator};
425/// use serde_json::json;
426///
427/// let validator = Validator::forms();
428/// let card = |text: &str| SurfaceDraft {
429///     surface_id: "status".into(),
430///     kind: DrawnKind::Card,
431///     title: None,
432///     components: vec![json!({ "id": "root", "component": "Text", "text": text })],
433///     data_model: json!({}),
434///     actions: Vec::new(),
435/// };
436/// assert!(validator.validate(&card("Invoice sent to ACME")).is_ok());
437/// let refused = validator.validate(&card("Approved")).unwrap_err();
438/// assert_eq!(refused.kind, RefusalKind::LooksLikeDecision);
439/// ```
440#[derive(Debug, Clone)]
441pub struct Validator {
442    catalog: &'static Catalog,
443    bindable: Option<BTreeSet<String>>,
444}
445
446impl Validator {
447    /// A validator for `catalog`.
448    pub fn new(catalog: &'static Catalog) -> Self {
449        Self { catalog, bindable: None }
450    }
451
452    /// A validator for the `forms` 1.0 catalog.
453    pub fn forms() -> Self {
454        Self::new(Catalog::forms())
455    }
456
457    /// Accepts actions bound to `tools` only: the drawing agent's own tools. Without it, an
458    /// action may name any tool but the kernel's and the drawing tools, and the agent
459    /// refuses a tool it does not have when the person sends. Given twice, an action may
460    /// name only a tool both give. The render tools also take the drawing agent's tools from
461    /// its runtime when it gives them ([`ToolContext::agent_tool_names`]).
462    ///
463    /// [`ToolContext::agent_tool_names`]: adk_core::ToolContext::agent_tool_names
464    #[must_use]
465    pub fn with_bindable_tools(
466        mut self,
467        tools: impl IntoIterator<Item = impl Into<String>>,
468    ) -> Self {
469        let tools: BTreeSet<String> = tools.into_iter().map(Into::into).collect();
470        self.bindable = Some(match self.bindable.take() {
471            Some(earlier) => earlier.intersection(&tools).cloned().collect(),
472            None => tools,
473        });
474        self
475    }
476
477    /// The catalog drawings are checked against.
478    pub fn catalog(&self) -> &'static Catalog {
479        self.catalog
480    }
481
482    /// Checks `draft` whole.
483    ///
484    /// # Errors
485    ///
486    /// Returns the first [`DrawRefusal`] found.
487    pub fn validate(&self, draft: &SurfaceDraft) -> Result<ValidatedSurface, DrawRefusal> {
488        let check =
489            Check { catalog: self.catalog, model: DataModel::new(draft.data_model.clone()) };
490        check.limits(draft)?;
491        let components = check.components(draft)?;
492        check.links(draft)?;
493        let mut texts = Vec::new();
494        if let Some(title) = &draft.title {
495            texts.push(check.display(None, None, "title", title)?);
496        }
497        let mut walk = Walk {
498            check: &check,
499            components: &components,
500            shown: 0,
501            texts,
502            extensions: BTreeMap::new(),
503            resolved_bytes: 0,
504            scenes: 0,
505            selects: Vec::new(),
506            choices: BTreeMap::new(),
507            root_pass: false,
508        };
509        walk.tree()?;
510        let Walk { mut texts, mut extensions, selects, choices, .. } = walk;
511        check.selects(draft, &selects, &choices, &mut extensions)?;
512        check.actions(draft, &components, self.bindable.as_ref(), &mut texts)?;
513        let warnings = super::patterns::dark_patterns(&texts);
514        Ok(ValidatedSurface { draft: draft.clone(), texts, warnings, extensions })
515    }
516}
517
518/// One component of a drawing: its type and properties.
519struct Component<'a> {
520    name: &'a str,
521    props: &'a Map<String, Value>,
522}
523
524/// The checks of one drawing.
525struct Check {
526    catalog: &'static Catalog,
527    model: DataModel,
528}
529
530impl Check {
531    fn refuse(
532        &self,
533        kind: RefusalKind,
534        component: Option<(&str, &str)>,
535        detail: String,
536    ) -> DrawRefusal {
537        DrawRefusal {
538            kind,
539            catalog: self.catalog.label(),
540            component: component
541                .map(|(id, name)| ComponentRef { id: id.to_string(), component: name.to_string() }),
542            detail,
543        }
544    }
545
546    fn cannot_show(
547        &self,
548        component: Option<(&str, &str)>,
549        detail: impl Into<String>,
550    ) -> DrawRefusal {
551        self.refuse(RefusalKind::CannotShow, component, detail.into())
552    }
553
554    /// Sizes and identifiers.
555    fn limits(&self, draft: &SurfaceDraft) -> Result<(), DrawRefusal> {
556        if !is_identifier(&draft.surface_id) {
557            return Err(self.cannot_show(
558                None,
559                format!(
560                    "surface id '{}' is not 1 to 64 letters, digits, '.', '_' or '-'",
561                    draft.surface_id
562                ),
563            ));
564        }
565        if draft.components.is_empty() || draft.components.len() > MAX_COMPONENTS {
566            return Err(self.cannot_show(
567                None,
568                format!(
569                    "a drawing has 1 to {MAX_COMPONENTS} components, not {}",
570                    draft.components.len()
571                ),
572            ));
573        }
574        if draft.actions.len() > MAX_ACTIONS {
575            return Err(
576                self.cannot_show(None, format!("a drawing declares at most {MAX_ACTIONS} actions"))
577            );
578        }
579        let bytes = serde_json::to_vec(&(&draft.components, &draft.data_model, &draft.actions))
580            .map_or(usize::MAX, |bytes| bytes.len());
581        if bytes > MAX_DRAWING_BYTES {
582            return Err(self.cannot_show(
583                None,
584                format!("the drawing takes {bytes} bytes; at most {MAX_DRAWING_BYTES}"),
585            ));
586        }
587        Ok(())
588    }
589
590    /// Every component: an object with a unique id, a type the catalog renders, no secret
591    /// field, only allowed functions and declared actions, and its catalog schema.
592    fn components<'a>(
593        &self,
594        draft: &'a SurfaceDraft,
595    ) -> Result<BTreeMap<&'a str, Component<'a>>, DrawRefusal> {
596        let mut components = BTreeMap::new();
597        for value in &draft.components {
598            let Some(props) = value.as_object() else {
599                return Err(self.cannot_show(None, "a component is not a JSON object"));
600            };
601            let (Some(id), Some(name)) = (
602                props.get("id").and_then(Value::as_str),
603                props.get("component").and_then(Value::as_str),
604            ) else {
605                return Err(
606                    self.cannot_show(None, "a component has no string id or component type")
607                );
608            };
609            let at = Some((id, name));
610            if components.insert(id, Component { name, props }).is_some() {
611                return Err(self.cannot_show(at, format!("id '{id}' is used twice")));
612            }
613            if !self.catalog.has_component(name) {
614                return Err(self.cannot_show(at, format!("{name} is not in the catalog")));
615            }
616            self.secrets(id, name, props)?;
617            // What a send carries is never hidden from a screen reader (A2UI 1.0
618            // `accessibility.hidden`).
619            if INPUTS.contains(&name) || name == "Button" {
620                let hidden = props
621                    .get("accessibility")
622                    .and_then(|accessibility| accessibility.get("hidden"));
623                if hidden.is_some_and(|hidden| hidden != &Value::Bool(false)) {
624                    return Err(self
625                        .cannot_show(at, "a field or button is never hidden from screen readers"));
626                }
627            }
628            if name == "Button" {
629                self.button(id, props, draft)?;
630            }
631            self.functions(id, name, value)?;
632            if self.catalog.extension(name).is_some() {
633                self.shows_only(id, name, value)?;
634            }
635            if let Some(error) = self.catalog.schema_error(name, value) {
636                return Err(self.cannot_show(at, format!("does not match the catalog: {error}")));
637            }
638        }
639        if !components.contains_key("root") {
640            return Err(self.cannot_show(None, "no component has the id 'root'"));
641        }
642        Ok(components)
643    }
644
645    /// A field that asks for a secret: an obscured text field, or one whose label, id or
646    /// bound path names a secret.
647    fn secrets(&self, id: &str, name: &str, props: &Map<String, Value>) -> Result<(), DrawRefusal> {
648        if name != "TextField" {
649            return Ok(());
650        }
651        let refuse =
652            |detail: String| Err(self.refuse(RefusalKind::AsksForSecret, Some((id, name)), detail));
653        if props.get("variant").and_then(Value::as_str) == Some("obscured") {
654            return refuse("an obscured field asks for a secret".to_string());
655        }
656        let mut names = vec![id.to_string()];
657        if let Some(label) = props.get("label").and_then(Value::as_str) {
658            names.push(label.to_string());
659        }
660        if let Some(path) =
661            props.get("value").and_then(|value| value.get("path")).and_then(Value::as_str)
662        {
663            names.push(path.to_string());
664        }
665        for name in names {
666            if let Some(secret) = names_secret(&name) {
667                return refuse(format!("'{name}' names a secret ({secret})"));
668            }
669        }
670        Ok(())
671    }
672
673    /// Function calls: the catalog's checks, and `formatString` and `pluralize` for text.
674    fn functions(&self, id: &str, name: &str, value: &Value) -> Result<(), DrawRefusal> {
675        let mut found = Vec::new();
676        calls(value, &mut found);
677        for call in found {
678            if !CHECK_FUNCTIONS.contains(&call.as_str()) && !TEXT_FUNCTIONS.contains(&call.as_str())
679            {
680                return Err(self.cannot_show(
681                    Some((id, name)),
682                    format!("calls the function '{call}', which a drawing may not use"),
683                ));
684            }
685        }
686        // The server checks a sent value against the pattern, so one it cannot read would
687        // refuse every send; the page leaves the check to the server.
688        let mut patterns = Vec::new();
689        regex_patterns(value, &mut patterns);
690        for pattern in patterns {
691            if regex::Regex::new(&format!("^(?:{pattern})$")).is_err() {
692                return Err(self.cannot_show(
693                    Some((id, name)),
694                    format!(
695                        "its regex check's pattern '{}' can't be read here: use one without \
696                         look-around or back-references",
697                        truncate(pattern)
698                    ),
699                ));
700            }
701        }
702        Ok(())
703    }
704
705    /// An extension component only shows: no action, event or check anywhere in it, and no
706    /// function but the text functions (spec 3.3 §7.4 rule 5).
707    fn shows_only(&self, id: &str, name: &str, value: &Value) -> Result<(), DrawRefusal> {
708        let at = Some((id, name));
709        if let Some(key) = keys_named(value, &["action", "event", "checks"]) {
710            return Err(self.cannot_show(
711                at,
712                format!("carries '{key}'; a component of an extension catalog only shows"),
713            ));
714        }
715        let mut found = Vec::new();
716        calls(value, &mut found);
717        if let Some(call) = found.iter().find(|call| !TEXT_FUNCTIONS.contains(&call.as_str())) {
718            return Err(self.cannot_show(
719                at,
720                format!("calls '{call}'; a component of an extension catalog makes text only"),
721            ));
722        }
723        Ok(())
724    }
725
726    /// A button dispatches one of the drawing's declared actions and nothing else.
727    fn button(
728        &self,
729        id: &str,
730        props: &Map<String, Value>,
731        draft: &SurfaceDraft,
732    ) -> Result<(), DrawRefusal> {
733        let at = Some((id, "Button"));
734        if matches!(draft.kind, DrawnKind::Card | DrawnKind::Table) {
735            return Err(self.cannot_show(at, "a card or table has no buttons"));
736        }
737        let event = props.get("action").and_then(|action| action.get("event"));
738        let Some(event) = event else {
739            return Err(self.cannot_show(at, "a button runs only a declared action"));
740        };
741        let name = event.get("name").and_then(Value::as_str).unwrap_or_default();
742        // A2UI 1.0 lets an event put words in the person's mouth; a drawing never does.
743        if event.get("userMessage").is_some() {
744            return Err(self.cannot_show(
745                at,
746                "a button never speaks as the person (userMessage); the declared action carries \
747                 the fields",
748            ));
749        }
750        if !draft.actions.iter().any(|action| action.id == name) {
751            return Err(
752                self.cannot_show(at, format!("the button's action '{name}' is not declared"))
753            );
754        }
755        if event
756            .get("context")
757            .is_some_and(|context| context.as_object().is_none_or(|map| !map.is_empty()))
758        {
759            return Err(self.cannot_show(
760                at,
761                "a button carries no event context; the declared action binds the fields",
762            ));
763        }
764        Ok(())
765    }
766
767    /// No string anywhere in the drawing is a link.
768    fn links(&self, draft: &SurfaceDraft) -> Result<(), DrawRefusal> {
769        let mut strings = Vec::new();
770        for component in &draft.components {
771            strings_of(component, &mut strings);
772        }
773        strings_of(&draft.data_model, &mut strings);
774        let actions = serde_json::to_value(&draft.actions).unwrap_or_default();
775        strings_of(&actions, &mut strings);
776        if let Some(title) = &draft.title {
777            strings.push(title.as_str());
778        }
779        match strings.into_iter().find(|text| looks_like_link(text)) {
780            Some(link) => Err(self.cannot_show(None, format!("'{}' is a link", truncate(link)))),
781            None => Ok(()),
782        }
783    }
784
785    /// A string a person reads: no longer than [`MAX_TEXT_CHARS`] and free of reserved words.
786    fn display(
787        &self,
788        component: Option<(&str, &str)>,
789        item: Option<&str>,
790        field: &str,
791        text: &str,
792    ) -> Result<ResolvedText, DrawRefusal> {
793        if text.chars().count() > MAX_TEXT_CHARS {
794            return Err(self.cannot_show(
795                component,
796                format!("{field} is longer than {MAX_TEXT_CHARS} characters"),
797            ));
798        }
799        if let Some(reserved) = reserved(text) {
800            return Err(self.refuse(
801                RefusalKind::LooksLikeDecision,
802                component,
803                format!("{field} matches reserved word \"{reserved}\" after normalisation"),
804            ));
805        }
806        Ok(ResolvedText {
807            component_id: component.map(|(id, _)| id.to_string()),
808            item: item.map(str::to_string),
809            field: field.to_string(),
810            text: text.to_string(),
811        })
812    }
813
814    /// Declared actions: unique ids, a label free of reserved words, a tool the agent may be
815    /// asked to run, and arguments bound to fields the drawing has.
816    fn actions(
817        &self,
818        draft: &SurfaceDraft,
819        components: &BTreeMap<&str, Component<'_>>,
820        bindable: Option<&BTreeSet<String>>,
821        texts: &mut Vec<ResolvedText>,
822    ) -> Result<(), DrawRefusal> {
823        if matches!(draft.kind, DrawnKind::Card | DrawnKind::Table) {
824            if !draft.actions.is_empty() {
825                return Err(self.cannot_show(None, "a card or table declares no actions"));
826            }
827            if let Some((id, component)) =
828                components.iter().find(|(_, component)| INPUTS.contains(&component.name))
829            {
830                return Err(
831                    self.cannot_show(Some((id, component.name)), "a card or table has no fields")
832                );
833            }
834        }
835        let fields: BTreeSet<&str> = components
836            .values()
837            .filter(|component| INPUTS.contains(&component.name))
838            .filter_map(|component| component.props.get("value")?.get("path")?.as_str())
839            .filter(|path| path.starts_with('/'))
840            .collect();
841        let mut ids = BTreeSet::new();
842        for action in &draft.actions {
843            let detail = |what: String| format!("action '{}' {what}", action.id);
844            if !is_identifier(&action.id) || !ids.insert(action.id.as_str()) {
845                return Err(
846                    self.cannot_show(None, detail("has an id that is not unique or valid".into()))
847                );
848            }
849            texts.push(self.display(
850                None,
851                None,
852                &format!("actions/{}/label", action.id),
853                &action.label,
854            )?);
855            if let Some(why) = adk_core::RequestedCall::refused_tool(&action.tool) {
856                return Err(
857                    self.cannot_show(None, detail(format!("runs '{}': {why}", action.tool)))
858                );
859            }
860            if bindable.is_some_and(|tools| !tools.contains(&action.tool)) {
861                return Err(self.cannot_show(
862                    None,
863                    detail(format!(
864                        "runs '{}', which is not one of the agent's tools",
865                        action.tool
866                    )),
867                ));
868            }
869            for (name, arg) in &action.args {
870                if let ActionArg::Field(field) = arg
871                    && !fields.contains(field.path.as_str())
872                {
873                    return Err(self.cannot_show(
874                        None,
875                        detail(format!("binds '{name}' to {}, which no field fills", field.path)),
876                    ));
877                }
878            }
879        }
880        Ok(())
881    }
882
883    /// The values a choice picker or a slider shows as text: a chosen value that matches
884    /// none of the picker's options, or a slider's bound value.
885    fn shown_values(&self, scope: &str, name: &str, props: &Map<String, Value>) -> Vec<String> {
886        let value = match props.get("value") {
887            Some(Value::Object(binding)) => binding
888                .get("path")
889                .and_then(Value::as_str)
890                .and_then(|path| self.lookup(scope, path)),
891            other => other,
892        };
893        match (name, value) {
894            ("Slider", Some(value)) => vec![shown(Some(value))],
895            ("ChoicePicker", Some(value)) => {
896                let options: Vec<&str> = props
897                    .get("options")
898                    .and_then(Value::as_array)
899                    .into_iter()
900                    .flatten()
901                    .filter_map(|option| option.get("value")?.as_str())
902                    .collect();
903                let chosen = match value {
904                    Value::Array(items) => items.iter().collect(),
905                    one => vec![one],
906                };
907                chosen
908                    .into_iter()
909                    .filter(|chosen| !chosen.as_str().is_some_and(|value| options.contains(&value)))
910                    .map(|chosen| shown(Some(chosen)))
911                    .collect()
912            }
913            _ => Vec::new(),
914        }
915    }
916
917    /// The value at `path`, absolute or relative to the list item `scope`.
918    fn lookup(&self, scope: &str, path: &str) -> Option<&Value> {
919        if path.starts_with('/') {
920            self.model.get(path)
921        } else {
922            self.model.get(&format!("{scope}/{path}"))
923        }
924    }
925
926    /// Every string `value` may show, the one shown first: a literal, a binding, or a
927    /// `formatString` or `pluralize` result.
928    fn texts(
929        &self,
930        at: (&str, &str),
931        scope: &str,
932        value: &Value,
933        depth: usize,
934    ) -> Result<Vec<String>, DrawRefusal> {
935        if depth > 8 {
936            return Err(self.cannot_show(Some(at), "text functions nest too deeply"));
937        }
938        match value {
939            Value::String(text) => Ok(vec![text.clone()]),
940            Value::Object(map) if map.contains_key("path") => {
941                let path = map.get("path").and_then(Value::as_str).unwrap_or_default();
942                Ok(vec![shown(self.lookup(scope, path))])
943            }
944            Value::Object(map) if map.contains_key("call") => {
945                let call = map.get("call").and_then(Value::as_str).unwrap_or_default();
946                let args = map.get("args").and_then(Value::as_object);
947                let arg = |name: &str| args.and_then(|args| args.get(name));
948                match call {
949                    "formatString" => {
950                        let mut out = Vec::new();
951                        for template in
952                            self.texts(at, scope, arg("value").unwrap_or(&Value::Null), depth + 1)?
953                        {
954                            out.push(self.interpolate(at, scope, &template)?);
955                        }
956                        Ok(out)
957                    }
958                    "pluralize" => {
959                        let count = match arg("value") {
960                            Some(Value::Number(number)) => number.as_f64(),
961                            Some(Value::Object(binding)) if binding.contains_key("path") => binding
962                                .get("path")
963                                .and_then(Value::as_str)
964                                .and_then(|path| self.lookup(scope, path))
965                                .and_then(Value::as_f64),
966                            _ => None,
967                        };
968                        let category = match count {
969                            Some(count) if count == 0.0 && arg("zero").is_some() => "zero",
970                            Some(count) if count == 1.0 && arg("one").is_some() => "one",
971                            _ => "other",
972                        };
973                        let mut chosen = Vec::new();
974                        let mut others = Vec::new();
975                        for name in ["zero", "one", "two", "few", "many", "other"] {
976                            if let Some(variant) = arg(name) {
977                                let texts = self.texts(at, scope, variant, depth + 1)?;
978                                if name == category {
979                                    chosen.extend(texts)
980                                } else {
981                                    others.extend(texts)
982                                }
983                            }
984                        }
985                        chosen.extend(others);
986                        Ok(chosen)
987                    }
988                    other => Err(self.cannot_show(
989                        Some(at),
990                        format!("only formatString and pluralize make text; '{other}' does not"),
991                    )),
992                }
993            }
994            Value::Null => Ok(vec![String::new()]),
995            other => Ok(vec![shown(Some(other))]),
996        }
997    }
998
999    /// `template` with every `${path}` replaced by the value at the path; `\${` is a
1000    /// literal `${`.
1001    fn interpolate(
1002        &self,
1003        at: (&str, &str),
1004        scope: &str,
1005        template: &str,
1006    ) -> Result<String, DrawRefusal> {
1007        let mut out = String::new();
1008        let mut rest = template;
1009        while let Some(start) = rest.find("${") {
1010            if rest[..start].ends_with('\\') {
1011                out.push_str(&rest[..start - 1]);
1012                out.push_str("${");
1013                rest = &rest[start + 2..];
1014                continue;
1015            }
1016            out.push_str(&rest[..start]);
1017            let after = &rest[start + 2..];
1018            let Some(end) = after.find('}') else {
1019                return Err(self.cannot_show(Some(at), "formatString has an unclosed '${'"));
1020            };
1021            let expression = after[..end].trim();
1022            if expression.contains("${") || expression.contains('(') {
1023                return Err(self.cannot_show(
1024                    Some(at),
1025                    "formatString interpolates data paths only, never function calls",
1026                ));
1027            }
1028            out.push_str(&shown(self.lookup(scope, expression)));
1029            rest = &after[end + 1..];
1030        }
1031        out.push_str(rest);
1032        Ok(out)
1033    }
1034
1035    /// A string an extension component shows, or its projection writes: [`Self::display`],
1036    /// and never a link, even one a `formatString` put together.
1037    fn shows(
1038        &self,
1039        at: (&str, &str),
1040        item: Option<&str>,
1041        field: &str,
1042        text: &str,
1043    ) -> Result<ResolvedText, DrawRefusal> {
1044        if looks_like_link(text) {
1045            return Err(
1046                self.cannot_show(Some(at), format!("{field} '{}' is a link", truncate(text)))
1047            );
1048        }
1049        self.display(Some(at), item, field, text)
1050    }
1051
1052    /// An extension component's property `value`, resolved and checked whole (spec 3.3 §7.4
1053    /// rule 5): every string and every key goes through [`Self::shows`]; a binding is replaced
1054    /// by the data it reads, every string and key of which is checked the same way, however
1055    /// it nests; a text function is replaced by the text it shows, every variant checked.
1056    fn resolve(
1057        &self,
1058        at: (&str, &str),
1059        scope: &str,
1060        field: &str,
1061        value: &Value,
1062        depth: usize,
1063        texts: &mut Vec<ResolvedText>,
1064    ) -> Result<Value, DrawRefusal> {
1065        if depth > MAX_PROP_DEPTH {
1066            return Err(self.cannot_show(Some(at), format!("{field} nests too deeply")));
1067        }
1068        let item = (!scope.is_empty()).then_some(scope);
1069        match value {
1070            Value::String(text) => {
1071                texts.push(self.shows(at, item, field, text)?);
1072                Ok(value.clone())
1073            }
1074            Value::Object(map) if is_binding(map) => {
1075                let path = map.get("path").and_then(Value::as_str).unwrap_or_default();
1076                let bound = self.lookup(scope, path).cloned().unwrap_or(Value::Null);
1077                self.bound(at, item, field, &bound, 0, texts)?;
1078                Ok(bound)
1079            }
1080            Value::Object(map) if map.contains_key("call") => {
1081                let mut first = None;
1082                for text in self.texts(at, scope, value, 0)? {
1083                    let resolved = self.shows(at, item, field, &text)?;
1084                    first.get_or_insert_with(|| resolved.text.clone());
1085                    texts.push(resolved);
1086                }
1087                Ok(Value::String(first.unwrap_or_default()))
1088            }
1089            Value::Object(map) => {
1090                let mut out = Map::new();
1091                for (key, value) in map {
1092                    let field = format!("{field}/{key}");
1093                    self.shows(at, item, &field, key)?;
1094                    out.insert(
1095                        key.clone(),
1096                        self.resolve(at, scope, &field, value, depth + 1, texts)?,
1097                    );
1098                }
1099                Ok(Value::Object(out))
1100            }
1101            Value::Array(items) => items
1102                .iter()
1103                .enumerate()
1104                .map(|(index, value)| {
1105                    self.resolve(at, scope, &format!("{field}/{index}"), value, depth + 1, texts)
1106                })
1107                .collect::<Result<Vec<_>, _>>()
1108                .map(Value::Array),
1109            other => Ok(other.clone()),
1110        }
1111    }
1112
1113    /// Data an extension component binds, checked whole: every string and every key,
1114    /// however it nests. Data is data: an object in it is never read as a binding.
1115    fn bound(
1116        &self,
1117        at: (&str, &str),
1118        item: Option<&str>,
1119        field: &str,
1120        value: &Value,
1121        depth: usize,
1122        texts: &mut Vec<ResolvedText>,
1123    ) -> Result<(), DrawRefusal> {
1124        if depth > MAX_PROP_DEPTH {
1125            return Err(
1126                self.cannot_show(Some(at), format!("the data {field} binds nests too deeply"))
1127            );
1128        }
1129        match value {
1130            Value::String(text) => texts.push(self.shows(at, item, field, text)?),
1131            Value::Object(map) => {
1132                for (key, value) in map {
1133                    let field = format!("{field}/{key}");
1134                    self.shows(at, item, &field, key)?;
1135                    self.bound(at, item, &field, value, depth + 1, texts)?;
1136                }
1137            }
1138            Value::Array(items) => {
1139                for (index, value) in items.iter().enumerate() {
1140                    self.bound(at, item, &format!("{field}/{index}"), value, depth + 1, texts)?;
1141                }
1142            }
1143            _ => {}
1144        }
1145        Ok(())
1146    }
1147
1148    /// What an extension component's projection shows, checked as a drawing's own strings
1149    /// are, every child it holds shown exactly once, and its charts within their limits.
1150    fn home(
1151        &self,
1152        at: (&str, &str),
1153        item: Option<&str>,
1154        node: HomeNode,
1155        depth: usize,
1156        seen: &mut HomeSeen,
1157        place: Place,
1158    ) -> Result<HomeNode, DrawRefusal> {
1159        seen.nodes += 1;
1160        if seen.nodes > MAX_HOME_NODES {
1161            return Err(self.cannot_show(
1162                Some(at),
1163                format!("its home view has more than {MAX_HOME_NODES} parts"),
1164            ));
1165        }
1166        if depth > MAX_HOME_DEPTH {
1167            return Err(self.cannot_show(
1168                Some(at),
1169                format!("its home view nests deeper than {MAX_HOME_DEPTH}"),
1170            ));
1171        }
1172        let nested = |children: Vec<HomeNode>, seen: &mut HomeSeen| {
1173            children
1174                .into_iter()
1175                .map(|child| self.home(at, item, child, depth + 1, seen, place))
1176                .collect::<Result<Vec<_>, _>>()
1177        };
1178        Ok(match node {
1179            HomeNode::Text { text, variant } => {
1180                self.shows(at, item, "home", &text)?;
1181                HomeNode::Text { text, variant }
1182            }
1183            HomeNode::Row(children) => HomeNode::Row(nested(children, seen)?),
1184            HomeNode::Column(children) => HomeNode::Column(nested(children, seen)?),
1185            HomeNode::Card(children) => HomeNode::Card(nested(children, seen)?),
1186            HomeNode::Tabs(tabs) => HomeNode::Tabs(
1187                tabs.into_iter()
1188                    .map(|(title, child)| {
1189                        self.shows(at, item, "home/tab", &title)?;
1190                        Ok((title, self.home(at, item, child, depth + 1, seen, place)?))
1191                    })
1192                    .collect::<Result<Vec<_>, DrawRefusal>>()?,
1193            ),
1194            HomeNode::Divider => HomeNode::Divider,
1195            HomeNode::Child(index) => {
1196                match place {
1197                    Place::TextView => {
1198                        return Err(self.cannot_show(
1199                            Some(at),
1200                            "its scene's text view holds a component; it says in words what the \
1201                             scene shows",
1202                        ));
1203                    }
1204                    Place::Panel | Place::Depth { shows_only: true } => seen.show_only.push(index),
1205                    Place::View | Place::Depth { shows_only: false } => {}
1206                }
1207                match seen.children.get_mut(index) {
1208                    None => {
1209                        return Err(self.cannot_show(
1210                            Some(at),
1211                            format!(
1212                                "its home view shows child {index}; it holds {}",
1213                                seen.children.len()
1214                            ),
1215                        ));
1216                    }
1217                    Some(true) => {
1218                        return Err(self.cannot_show(
1219                            Some(at),
1220                            format!("its home view shows child {index} twice"),
1221                        ));
1222                    }
1223                    Some(shown) => *shown = true,
1224                }
1225                HomeNode::Child(index)
1226            }
1227            HomeNode::Chart(chart) => {
1228                if place == Place::TextView {
1229                    return Err(self.cannot_show(
1230                        Some(at),
1231                        "its scene's text view holds a chart; it says in words what the scene \
1232                         shows",
1233                    ));
1234                }
1235                HomeNode::Chart(self.chart(at, item, chart)?)
1236            }
1237            HomeNode::Scene(scene) => {
1238                if place != Place::View {
1239                    return Err(self.cannot_show(
1240                        Some(at),
1241                        "its home view puts a scene inside a panel, a text view or a depth effect",
1242                    ));
1243                }
1244                seen.scenes += 1;
1245                HomeNode::Scene(Box::new(self.scene(at, item, *scene, depth, seen)?))
1246            }
1247            HomeNode::Depth { depth: effect, children } => {
1248                if place != Place::View {
1249                    return Err(self.cannot_show(
1250                        Some(at),
1251                        "its home view puts a depth effect inside a scene or another depth effect",
1252                    ));
1253                }
1254                let effect = self.depth(at, item, effect, children.len())?;
1255                let place = Place::Depth { shows_only: effect.effect.shows_only() };
1256                let children = children
1257                    .into_iter()
1258                    .map(|child| self.home(at, item, child, depth + 1, seen, place))
1259                    .collect::<Result<Vec<_>, _>>()?;
1260                HomeNode::Depth { depth: effect, children }
1261            }
1262        })
1263    }
1264
1265    /// A chart within its limits, every string it shows checked, its summary written here.
1266    fn chart(
1267        &self,
1268        at: (&str, &str),
1269        item: Option<&str>,
1270        mut chart: DrawnChart,
1271    ) -> Result<DrawnChart, DrawRefusal> {
1272        let refuse = |detail: String| self.cannot_show(Some(at), format!("its chart {detail}"));
1273        if chart.series.is_empty() || chart.series.len() > MAX_CHART_SERIES {
1274            return Err(refuse(format!(
1275                "has {} series; a chart has 1 to {MAX_CHART_SERIES}",
1276                chart.series.len()
1277            )));
1278        }
1279        if matches!(chart.kind, ChartKind::Pie | ChartKind::Sparkline) && chart.series.len() != 1 {
1280            return Err(refuse("of this kind has exactly one series".to_string()));
1281        }
1282        if chart.ticks.len() > MAX_CHART_TICKS {
1283            return Err(refuse(format!("has more than {MAX_CHART_TICKS} ticks")));
1284        }
1285        let mut points = 0;
1286        let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
1287        for series in &chart.series {
1288            if series.y.len() > MAX_LIST_ITEMS {
1289                return Err(refuse(format!(
1290                    "series '{}' has {} values; at most {MAX_LIST_ITEMS}",
1291                    truncate(&series.name),
1292                    series.y.len()
1293                )));
1294            }
1295            let expected = match &chart.x {
1296                ChartAxis::Category { labels } => {
1297                    if !series.x.is_empty() {
1298                        return Err(refuse("has x values on a category axis".to_string()));
1299                    }
1300                    labels.len()
1301                }
1302                ChartAxis::Number | ChartAxis::Time => series.x.len(),
1303            };
1304            if series.y.len() != expected {
1305                return Err(refuse(format!(
1306                    "series '{}' has {} values for {expected} places on its axis",
1307                    truncate(&series.name),
1308                    series.y.len()
1309                )));
1310            }
1311            points += series.y.len();
1312            for value in series.y.iter().filter_map(serde_json::Number::as_f64) {
1313                if chart.kind == ChartKind::Pie && value < 0.0 {
1314                    return Err(refuse("has a negative slice".to_string()));
1315                }
1316                low = low.min(value);
1317                high = high.max(value);
1318            }
1319            self.shows(at, item, "chart/series", &series.name)?;
1320        }
1321        if points > MAX_SHOWN {
1322            return Err(refuse(format!("has {points} values; at most {MAX_SHOWN}")));
1323        }
1324        if let ChartAxis::Category { labels } = &chart.x {
1325            if chart.kind == ChartKind::Pie && labels.len() > MAX_PIE_SLICES {
1326                return Err(refuse(format!(
1327                    "has {} slices; at most {MAX_PIE_SLICES}",
1328                    labels.len()
1329                )));
1330            }
1331            for label in labels {
1332                self.shows(at, item, "chart/label", label)?;
1333            }
1334        } else if chart.kind == ChartKind::Pie {
1335            return Err(refuse("of kind pie has a category axis".to_string()));
1336        }
1337        for tick in &chart.ticks {
1338            self.shows(at, item, "chart/tick", &tick.text)?;
1339        }
1340        for label in [&chart.x_label, &chart.y_label].into_iter().flatten() {
1341            self.shows(at, item, "chart/axis", label)?;
1342        }
1343        let kind = match chart.kind {
1344            ChartKind::Line => "Line",
1345            ChartKind::Area => "Area",
1346            ChartKind::Bar => "Bar",
1347            ChartKind::Scatter => "Scatter",
1348            ChartKind::Pie => "Pie",
1349            ChartKind::Sparkline => "Trend",
1350        };
1351        let names: Vec<&str> = chart.series.iter().map(|series| series.name.as_str()).collect();
1352        let range = (low <= high).then_some((low, high));
1353        chart.summary = crate::words::chart_summary(kind, &names, points, range);
1354        // Names checked one by one can still spell a decision's words once joined.
1355        self.shows(at, item, "chart/summary", &chart.summary)?;
1356        Ok(chart)
1357    }
1358}
1359
1360/// What an extension component's projection has shown so far.
1361struct HomeSeen {
1362    nodes: usize,
1363    children: Vec<bool>,
1364    /// The children placed where only what shows may be: a scene's panels, a wall or stage.
1365    show_only: Vec<usize>,
1366    /// The scenes it draws.
1367    scenes: usize,
1368    /// What its scenes' picks fill.
1369    selects: Vec<Select>,
1370}
1371
1372/// Where a home view node is placed.
1373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1374enum Place {
1375    /// In the view itself.
1376    View,
1377    /// In a scene's panel: only what shows.
1378    Panel,
1379    /// In a scene's text view: words only.
1380    TextView,
1381    /// Presented by a depth effect; a wall or a stage holds only what shows.
1382    Depth { shows_only: bool },
1383}
1384
1385/// A scene's pick: the component whose scene it is, the absolute path it fills and the
1386/// values its objects pick.
1387#[derive(Debug, Clone)]
1388struct Select {
1389    id: String,
1390    component: String,
1391    path: String,
1392    values: Vec<String>,
1393}
1394
1395/// A choice field the drawing shows: its label and its options' values.
1396#[derive(Debug, Clone)]
1397struct Choice {
1398    label: String,
1399    options: Vec<String>,
1400}
1401
1402/// The walk over the component tree from `root`, expanding templates against the data model.
1403struct Walk<'a> {
1404    check: &'a Check,
1405    components: &'a BTreeMap<&'a str, Component<'a>>,
1406    shown: usize,
1407    texts: Vec<ResolvedText>,
1408    extensions: BTreeMap<(String, String), ExtensionView>,
1409    resolved_bytes: usize,
1410    /// The scenes the drawing draws.
1411    scenes: usize,
1412    /// What its scenes' picks fill.
1413    selects: Vec<Select>,
1414    /// The choice fields it shows, by absolute path: recorded on the walk from `root`.
1415    choices: BTreeMap<String, Choice>,
1416    /// The walk is from `root`: what it visits is shown.
1417    root_pass: bool,
1418}
1419
1420impl<'a> Walk<'a> {
1421    fn tree(&mut self) -> Result<(), DrawRefusal> {
1422        let mut visited = BTreeSet::new();
1423        self.root_pass = true;
1424        self.visit("root", "", 0, &mut Vec::new(), &mut visited)?;
1425        self.root_pass = false;
1426        // A component no one shows yet is checked too, so a later change that shows it
1427        // cannot bring a reserved word in unchecked.
1428        let unshown: Vec<&str> =
1429            self.components.keys().copied().filter(|id| !visited.contains(*id)).collect();
1430        for id in unshown {
1431            self.visit(id, "", 0, &mut Vec::new(), &mut visited)?;
1432        }
1433        Ok(())
1434    }
1435
1436    fn visit(
1437        &mut self,
1438        id: &'a str,
1439        scope: &str,
1440        depth: usize,
1441        path: &mut Vec<&'a str>,
1442        visited: &mut BTreeSet<String>,
1443    ) -> Result<(), DrawRefusal> {
1444        let check = self.check;
1445        let components = self.components;
1446        let Some(component) = components.get(id) else {
1447            let parent =
1448                path.last().and_then(|parent| components.get(parent).map(|c| (*parent, c.name)));
1449            return Err(check.cannot_show(parent, format!("child '{id}' does not exist")));
1450        };
1451        let at = (id, component.name);
1452        if depth > MAX_DEPTH {
1453            return Err(check.cannot_show(Some(at), format!("the tree is deeper than {MAX_DEPTH}")));
1454        }
1455        if path.contains(&id) {
1456            return Err(check.cannot_show(Some(at), "the component tree loops"));
1457        }
1458        self.shown += 1;
1459        if self.shown > MAX_SHOWN {
1460            return Err(check.cannot_show(
1461                Some(at),
1462                format!("the drawing shows more than {MAX_SHOWN} components"),
1463            ));
1464        }
1465        visited.insert(id.to_string());
1466        let item = (!scope.is_empty()).then_some(scope);
1467        if let Some(extension) = check.catalog.extension(component.name) {
1468            self.extension(extension, at, scope, component)?;
1469        } else {
1470            let mut label = None;
1471            for (field, value) in display_fields(component.name, component.props) {
1472                for text in check.texts(at, scope, value, 0)? {
1473                    let resolved = check.display(Some(at), item, &field, &text)?;
1474                    if field == "label" && label.is_none() {
1475                        label = Some(resolved.text.clone());
1476                    }
1477                    self.texts.push(resolved);
1478                }
1479            }
1480            if self.root_pass && component.name == "ChoicePicker" {
1481                self.choice(scope, component, label);
1482            }
1483            // A choice that matches no option, or a slider's value, is shown as it is.
1484            for text in check.shown_values(scope, component.name, component.props) {
1485                check.display(Some(at), item, "value", &text)?;
1486            }
1487        }
1488        path.push(id);
1489        for child in children(check.catalog, component.name, component.props) {
1490            match child {
1491                Child::Id(child) => self.visit(child, scope, depth + 1, path, visited)?,
1492                Child::Template { component: child, list } => {
1493                    let list = if list.starts_with('/') {
1494                        list.to_string()
1495                    } else {
1496                        format!("{scope}/{list}")
1497                    };
1498                    let items =
1499                        check.model.get(&list).and_then(Value::as_array).map_or(0, Vec::len);
1500                    if items > MAX_LIST_ITEMS {
1501                        return Err(check.cannot_show(
1502                            Some(at),
1503                            format!("a list renders at most {MAX_LIST_ITEMS} items, not {items}"),
1504                        ));
1505                    }
1506                    for index in 0..items {
1507                        self.visit(child, &format!("{list}/{index}"), depth + 1, path, visited)?;
1508                    }
1509                }
1510            }
1511        }
1512        path.pop();
1513        Ok(())
1514    }
1515
1516    /// An extension component (spec 3.3 §6.1 `genui`, extension catalogs): its properties
1517    /// resolved and checked whole, then what the home shows for it checked, both kept for
1518    /// the projection. Its slots' component ids are structure, not text.
1519    fn extension(
1520        &mut self,
1521        extension: &dyn ExtensionComponent,
1522        at: (&str, &str),
1523        scope: &str,
1524        component: &Component<'_>,
1525    ) -> Result<(), DrawRefusal> {
1526        let check = self.check;
1527        let item = (!scope.is_empty()).then_some(scope);
1528        let slots = extension.children();
1529        let mut props = Map::new();
1530        for (key, value) in component.props {
1531            let holds_ids = key == "id"
1532                || key == "component"
1533                || slots.iter().any(|slot| {
1534                    matches!(slot, ChildSlot::One(name) | ChildSlot::Many(name) if name == key)
1535                });
1536            if holds_ids {
1537                props.insert(key.clone(), value.clone());
1538                continue;
1539            }
1540            let each_of = slots.iter().find_map(|slot| match slot {
1541                ChildSlot::EachOf { array, child } if array == key => Some(*child),
1542                _ => None,
1543            });
1544            check.shows(at, item, key, key)?;
1545            let resolved = match (each_of, value.as_array()) {
1546                (Some(child), Some(entries)) => {
1547                    let mut out = Vec::with_capacity(entries.len());
1548                    for (index, entry) in entries.iter().enumerate() {
1549                        let field = format!("{key}/{index}");
1550                        let Some(map) = entry.as_object() else {
1551                            out.push(check.resolve(
1552                                at,
1553                                scope,
1554                                &field,
1555                                entry,
1556                                1,
1557                                &mut self.texts,
1558                            )?);
1559                            continue;
1560                        };
1561                        let mut resolved = Map::new();
1562                        for (name, value) in map {
1563                            if name == child {
1564                                resolved.insert(name.clone(), value.clone());
1565                                continue;
1566                            }
1567                            let field = format!("{field}/{name}");
1568                            check.shows(at, item, &field, name)?;
1569                            resolved.insert(
1570                                name.clone(),
1571                                check.resolve(at, scope, &field, value, 2, &mut self.texts)?,
1572                            );
1573                        }
1574                        out.push(Value::Object(resolved));
1575                    }
1576                    Value::Array(out)
1577                }
1578                _ => check.resolve(at, scope, key, value, 0, &mut self.texts)?,
1579            };
1580            props.insert(key.clone(), resolved);
1581        }
1582        let props = Value::Object(props);
1583        let bytes = serde_json::to_vec(&props).map_or(usize::MAX, |bytes| bytes.len());
1584        self.resolved_bytes = self.resolved_bytes.saturating_add(bytes);
1585        if self.resolved_bytes > MAX_RESOLVED_BYTES {
1586            return Err(check.cannot_show(
1587                Some(at),
1588                format!(
1589                    "the drawing's extension components resolve to more than \
1590                     {MAX_RESOLVED_BYTES} bytes"
1591                ),
1592            ));
1593        }
1594        let ids: Vec<String> = children(check.catalog, component.name, component.props)
1595            .into_iter()
1596            .filter_map(|child| match child {
1597                Child::Id(id) => Some(id.to_string()),
1598                Child::Template { .. } => None,
1599            })
1600            .collect();
1601        let resolved =
1602            ResolvedComponent { id: at.0, component: at.1, props: &props, children: ids.len() };
1603        let home = extension
1604            .home(&resolved)
1605            .map_err(|why| check.cannot_show(Some(at), format!("its home view: {why}")))?;
1606        let mut seen = HomeSeen {
1607            nodes: 0,
1608            children: vec![false; ids.len()],
1609            show_only: Vec::new(),
1610            scenes: 0,
1611            selects: Vec::new(),
1612        };
1613        let home = check.home(at, item, home, 0, &mut seen, Place::View)?;
1614        if let Some(index) = seen.children.iter().position(|shown| !shown) {
1615            return Err(
1616                check.cannot_show(Some(at), format!("its home view leaves out child {index}"))
1617            );
1618        }
1619        for index in &seen.show_only {
1620            if let Some((id, name)) = ids.get(*index).and_then(|id| self.interactive(id)) {
1621                return Err(check.cannot_show(
1622                    Some(at),
1623                    format!(
1624                        "its home view shows {name} '{id}' in a scene's panel, on a wall or on a \
1625                         stage, where things move under the pointer; those only show"
1626                    ),
1627                ));
1628            }
1629        }
1630        self.scenes += seen.scenes;
1631        if self.scenes > MAX_SCENES {
1632            return Err(check.cannot_show(
1633                Some(at),
1634                format!("the drawing shows more than {MAX_SCENES} scenes"),
1635            ));
1636        }
1637        self.selects.extend(seen.selects);
1638        self.shown += seen.nodes;
1639        if self.shown > MAX_SHOWN {
1640            return Err(check.cannot_show(
1641                Some(at),
1642                format!("the drawing shows more than {MAX_SHOWN} components"),
1643            ));
1644        }
1645        self.extensions.insert(
1646            (at.0.to_string(), scope.to_string()),
1647            ExtensionView { component: at.1.to_string(), props, home, children: ids },
1648        );
1649        Ok(())
1650    }
1651}
1652
1653/// A component's child: by id, or a template rendered once per item of a data model list.
1654pub(super) enum Child<'a> {
1655    Id(&'a str),
1656    Template { component: &'a str, list: &'a str },
1657}
1658
1659/// The children of a component of `catalog`: a forms component's by its type, an extension
1660/// component's by its slots.
1661pub(super) fn children<'a>(
1662    catalog: &Catalog,
1663    name: &str,
1664    props: &'a Map<String, Value>,
1665) -> Vec<Child<'a>> {
1666    let mut out = Vec::new();
1667    if let Some(extension) = catalog.extension(name) {
1668        for slot in extension.children() {
1669            match *slot {
1670                ChildSlot::One(slot) => {
1671                    out.extend(props.get(slot).and_then(Value::as_str).map(Child::Id));
1672                }
1673                ChildSlot::Many(slot) => out.extend(
1674                    props
1675                        .get(slot)
1676                        .and_then(Value::as_array)
1677                        .into_iter()
1678                        .flatten()
1679                        .filter_map(Value::as_str)
1680                        .map(Child::Id),
1681                ),
1682                ChildSlot::EachOf { array, child } => out.extend(
1683                    props
1684                        .get(array)
1685                        .and_then(Value::as_array)
1686                        .into_iter()
1687                        .flatten()
1688                        .filter_map(|entry| entry.get(child)?.as_str())
1689                        .map(Child::Id),
1690                ),
1691            }
1692        }
1693        return out;
1694    }
1695    match name {
1696        "Row" | "Column" | "List" => match props.get("children") {
1697            Some(Value::Array(ids)) => {
1698                out.extend(ids.iter().filter_map(Value::as_str).map(Child::Id))
1699            }
1700            Some(Value::Object(template)) => {
1701                if let (Some(component), Some(list)) = (
1702                    template.get("componentId").and_then(Value::as_str),
1703                    template.get("path").and_then(Value::as_str),
1704                ) {
1705                    out.push(Child::Template { component, list });
1706                }
1707            }
1708            _ => {}
1709        },
1710        "Card" | "Button" => out.extend(props.get("child").and_then(Value::as_str).map(Child::Id)),
1711        "Tabs" => out.extend(
1712            props
1713                .get("tabs")
1714                .and_then(Value::as_array)
1715                .into_iter()
1716                .flatten()
1717                .filter_map(|tab| tab.get("child")?.as_str())
1718                .map(Child::Id),
1719        ),
1720        _ => {}
1721    }
1722    out
1723}
1724
1725/// The properties of `name` a person reads, by field.
1726fn display_fields<'a>(name: &str, props: &'a Map<String, Value>) -> Vec<(String, &'a Value)> {
1727    let mut fields = Vec::new();
1728    let mut take = |field: &str| {
1729        if let Some(value) = props.get(field) {
1730            fields.push((field.to_string(), value));
1731        }
1732    };
1733    match name {
1734        "Text" => take("text"),
1735        "TextField" | "DateTimeInput" => {
1736            take("label");
1737            take("value");
1738            take("placeholder");
1739        }
1740        "CheckBox" | "Slider" | "ChoicePicker" => take("label"),
1741        _ => {}
1742    }
1743    if name == "ChoicePicker" {
1744        for (index, option) in
1745            props.get("options").and_then(Value::as_array).into_iter().flatten().enumerate()
1746        {
1747            if let Some(label) = option.get("label") {
1748                fields.push((format!("options/{index}/label"), label));
1749            }
1750        }
1751    }
1752    if name == "Tabs" {
1753        for (index, tab) in
1754            props.get("tabs").and_then(Value::as_array).into_iter().flatten().enumerate()
1755        {
1756            if let Some(title) = tab.get("title") {
1757                fields.push((format!("tabs/{index}/title"), title));
1758            }
1759        }
1760    }
1761    if let Some(accessibility) = props.get("accessibility").and_then(Value::as_object) {
1762        for field in ["label", "description"] {
1763            if let Some(value) = accessibility.get(field) {
1764                fields.push((format!("accessibility/{field}"), value));
1765            }
1766        }
1767    }
1768    for (index, check) in
1769        props.get("checks").and_then(Value::as_array).into_iter().flatten().enumerate()
1770    {
1771        if let Some(message) = check.get("message") {
1772            fields.push((format!("checks/{index}/message"), message));
1773        }
1774    }
1775    fields
1776}
1777
1778/// Whether `map` is a data binding: an object whose only key is a string `path`.
1779fn is_binding(map: &Map<String, Value>) -> bool {
1780    map.len() == 1 && map.get("path").is_some_and(Value::is_string)
1781}
1782
1783/// The first key of `names` anywhere in `value`.
1784fn keys_named(value: &Value, names: &[&str]) -> Option<String> {
1785    match value {
1786        Value::Object(map) => map
1787            .keys()
1788            .find(|key| names.contains(&key.as_str()))
1789            .cloned()
1790            .or_else(|| map.values().find_map(|value| keys_named(value, names))),
1791        Value::Array(items) => items.iter().find_map(|value| keys_named(value, names)),
1792        _ => None,
1793    }
1794}
1795
1796/// Every function a component calls, by name.
1797fn calls(value: &Value, found: &mut Vec<String>) {
1798    match value {
1799        Value::Object(map) => {
1800            if let Some(call) = map.get("call").and_then(Value::as_str) {
1801                found.push(call.to_string());
1802            }
1803            map.values().for_each(|value| calls(value, found));
1804        }
1805        Value::Array(items) => items.iter().for_each(|value| calls(value, found)),
1806        _ => {}
1807    }
1808}
1809
1810/// The pattern of every `regex` check in `value`.
1811fn regex_patterns<'a>(value: &'a Value, found: &mut Vec<&'a str>) {
1812    match value {
1813        Value::Object(map) => {
1814            if map.get("call").and_then(Value::as_str) == Some("regex")
1815                && let Some(pattern) =
1816                    map.get("args").and_then(|args| args.get("pattern")).and_then(Value::as_str)
1817            {
1818                found.push(pattern);
1819            }
1820            map.values().for_each(|value| regex_patterns(value, found));
1821        }
1822        Value::Array(items) => items.iter().for_each(|value| regex_patterns(value, found)),
1823        _ => {}
1824    }
1825}
1826
1827/// Every string in `value`, keys included.
1828fn strings_of<'a>(value: &'a Value, out: &mut Vec<&'a str>) {
1829    match value {
1830        Value::String(text) => out.push(text),
1831        Value::Object(map) => {
1832            for (key, value) in map {
1833                out.push(key);
1834                strings_of(value, out);
1835            }
1836        }
1837        Value::Array(items) => items.iter().for_each(|value| strings_of(value, out)),
1838        _ => {}
1839    }
1840}
1841
1842/// The text a data model value shows.
1843fn shown(value: Option<&Value>) -> String {
1844    match value {
1845        None | Some(Value::Null) => String::new(),
1846        Some(Value::String(text)) => text.clone(),
1847        Some(Value::Number(number)) => number.to_string(),
1848        Some(Value::Bool(flag)) => flag.to_string(),
1849        Some(other) => other.to_string(),
1850    }
1851}
1852
1853/// Whether `id` is 1 to 64 ASCII letters, digits, `.`, `_` or `-`.
1854fn is_identifier(id: &str) -> bool {
1855    (1..=64).contains(&id.len())
1856        && id.bytes().all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
1857}
1858
1859/// `text` cut for a refusal's detail.
1860fn truncate(text: &str) -> String {
1861    let mut chars = text.chars();
1862    let head: String = chars.by_ref().take(80).collect();
1863    if chars.next().is_some() { format!("{head}…") } else { head }
1864}
1865
1866/// The words of folded text, apostrophes inside a word kept.
1867fn words(folded: &str) -> Vec<&str> {
1868    folded
1869        .split(|c: char| !(c.is_alphanumeric() || c == '\''))
1870        .map(|word| word.trim_matches('\''))
1871        .filter(|word| !word.is_empty())
1872        .collect()
1873}
1874
1875/// The reserved phrases as folded words, each with its wording.
1876type FoldedPhrases = Vec<(Vec<String>, &'static str)>;
1877
1878/// The reserved labels as folded words, each with its wording.
1879type FoldedLabels = Vec<(Vec<String>, &'static str)>;
1880
1881/// The reserved wording, folded once.
1882static RESERVED: LazyLock<(FoldedPhrases, FoldedLabels)> = LazyLock::new(|| {
1883    let fold = |text: &str| {
1884        words(&fold_display_text(text)).into_iter().map(str::to_string).collect::<Vec<_>>()
1885    };
1886    let phrases = RESERVED_PHRASES.iter().map(|phrase| (fold(phrase), *phrase)).collect();
1887    let labels = RESERVED_LABELS.iter().map(|label| (fold(label), *label)).collect();
1888    (phrases, labels)
1889});
1890
1891/// The reserved wording `text` shows, if any: a phrase anywhere, or a label as the whole
1892/// text.
1893///
1894/// # Example
1895///
1896/// ```rust
1897/// use adk_surface::genui::reserved;
1898///
1899/// assert_eq!(reserved("Tap Аllow  once to send"), Some("Allow once"));
1900/// assert_eq!(reserved("Approved ✓"), Some("Approved"));
1901/// assert_eq!(reserved("Edit address"), None);
1902/// ```
1903pub fn reserved(text: &str) -> Option<&'static str> {
1904    let folded = fold_display_text(text);
1905    let words = words(&folded);
1906    let (phrases, labels) = &*RESERVED;
1907    for (phrase, original) in phrases {
1908        if words
1909            .windows(phrase.len())
1910            .any(|window| window.iter().zip(phrase).all(|(word, part)| *word == part.as_str()))
1911        {
1912            return Some(original);
1913        }
1914    }
1915    labels
1916        .iter()
1917        .find(|(label, _)| {
1918            label.len() == words.len() && label.iter().zip(&words).all(|(part, word)| part == word)
1919        })
1920        .map(|(_, original)| *original)
1921}
1922
1923/// The secret a field's label, id or path names, if any.
1924fn names_secret(text: &str) -> Option<&'static str> {
1925    let folded = fold_display_text(&text.replace(['_', '-', '/', '.'], " "));
1926    let words = words(&folded);
1927    if let Some(word) = SECRET_WORDS.iter().find(|secret| words.contains(secret)) {
1928        return Some(word);
1929    }
1930    let joined = words.join(" ");
1931    SECRET_PHRASES
1932        .iter()
1933        .find(|phrase| {
1934            joined == **phrase
1935                || joined.starts_with(&format!("{phrase} "))
1936                || joined.ends_with(&format!(" {phrase}"))
1937                || joined.contains(&format!(" {phrase} "))
1938        })
1939        .copied()
1940}
1941
1942/// Whether `text` holds a link: `://`, `www.`, or a scheme such as `javascript:` or
1943/// `mailto:` followed by more than a space.
1944fn looks_like_link(text: &str) -> bool {
1945    let folded = fold_display_text(text);
1946    if folded.contains("://") || folded.contains("www.") || folded.contains(":\\\\") {
1947        return true;
1948    }
1949    const SCHEMES: &[&str] = &[
1950        "javascript",
1951        "vbscript",
1952        "data",
1953        "mailto",
1954        "tel",
1955        "sms",
1956        "file",
1957        "blob",
1958        "intent",
1959        "ftp",
1960        "http",
1961        "https",
1962    ];
1963    SCHEMES.iter().any(|scheme| {
1964        folded.match_indices(&format!("{scheme}:")).any(|(at, matched)| {
1965            let before = folded[..at].chars().next_back();
1966            let after = folded[at + matched.len()..].chars().next();
1967            before.is_none_or(|c| !c.is_alphanumeric()) && after.is_some_and(|c| !c.is_whitespace())
1968        })
1969    })
1970}
1971
1972#[cfg(test)]
1973mod tests {
1974    use super::*;
1975
1976    #[test]
1977    fn reserved_wording_is_found_whatever_its_spelling() {
1978        let cases = [
1979            ("Allow once", Some("Allow once")),
1980            ("ALLOW ONCE", Some("Allow once")),
1981            ("Allow once", Some("Allow once")),
1982            ("A\u{200B}llow\u{2060} once", Some("Allow once")),
1983            ("\u{202E}Allow once\u{202C}", Some("Allow once")),
1984            ("Аllоw оnce", Some("Allow once")),
1985            ("A11ow 0nce", Some("Allow once")),
1986            ("Allów once", Some("Allow once")),
1987            ("Always allow for this person", Some("Always allow")),
1988            ("Confirm it’s you and approve", Some("Confirm it's you")),
1989            ("Stop all", Some("Stop all")),
1990            ("Take over", Some("Take over")),
1991            ("You said yes in Telegram", Some("You said yes")),
1992            ("Edit", Some("Edit")),
1993            ("  deny! ", Some("Deny")),
1994            ("✓ Approved", Some("Approved")),
1995            ("Edit address", None),
1996            ("Approve the October invoice?", None),
1997            ("Done at 10:04", None),
1998            ("Invoice INV-10", None),
1999            ("Allowance once a month", None),
2000        ];
2001        for (text, expected) in cases {
2002            assert_eq!(reserved(text), expected, "{text:?}");
2003        }
2004    }
2005
2006    #[test]
2007    fn links_are_found_in_their_disguises() {
2008        for link in [
2009            "https://example.com",
2010            "see www.example.com",
2011            "javascript:alert(1)",
2012            "mailto:ana@example.com",
2013            "HTTPS://example.com",
2014            "data:text/html,hi",
2015        ] {
2016            assert!(looks_like_link(link), "{link}");
2017        }
2018        for text in ["Data: 5 items", "Tel: +254 700", "ana@example.com", "10:03", "Total: 4200"] {
2019            assert!(!looks_like_link(text), "{text}");
2020        }
2021    }
2022
2023    #[test]
2024    fn secrets_are_named_by_words_not_by_letters() {
2025        for name in ["Password", "/user/pin", "api_key", "Card number", "one-time code", "PIN"] {
2026            assert!(names_secret(name).is_some(), "{name}");
2027        }
2028        for name in ["Shipping address", "Spinach", "To", "/amount", "Tokenizer settings"] {
2029            assert_eq!(names_secret(name), None, "{name}");
2030        }
2031    }
2032}