Skip to main content

alpha2_compose/
template.rs

1//! Templates are compose documents with typed parameters, bound to data into plain specs.
2//!
3//! A template is a compose document with a `template` header and `params`. Binding validates
4//! the data, then replaces `{"$param": name}` values, `{{name}}` in strings, and the `$if`,
5//! `$switch` and `$each` directives, and expands `owner/name` template nodes, leaving a spec
6//! with no `$` left in it. Binding is logic-less and works on the JSON before it is parsed, so
7//! every compose field can be a parameter. One binding makes at most [`MAX_BOUND_VALUES`] values
8//! in template bodies.
9
10use std::collections::{BTreeMap, BTreeSet};
11
12use alpha2_diagnose::{Code, Diagnostic};
13use serde_json::{Map, Value, json};
14
15use crate::ComposeError;
16use crate::diagnose::{
17    TEMPLATE_BIND, TEMPLATE_HEADER, TEMPLATE_LITERAL_COLOR, TEMPLATE_LITERAL_MEDIA,
18    TEMPLATE_LITERAL_TEXT, TEMPLATE_PARAM_TYPE, TEMPLATE_PARAMS, TEMPLATE_SPEC,
19    TEMPLATE_UNKNOWN_PARAM, TEMPLATE_UNUSED_PARAM, path_of,
20};
21
22/// Template nodes nest at most this deep.
23const MAX_DEPTH: usize = 16;
24
25/// Values one binding may make in template bodies, a string counting one per 64 bytes.
26pub const MAX_BOUND_VALUES: usize = 100_000;
27
28/// Bytes of a string that count as one bound value.
29const STRING_BYTES_PER_VALUE: usize = 64;
30
31/// Keys whose string values are names, not text, so `{{...}}` in them is left alone.
32const NAME_KEYS: [&str; 2] = ["type", "id"];
33
34/// Keys whose string values are text a viewer reads, checked for literal copy in templates.
35const TEXT_KEYS: [&str; 8] = [
36    "text", "subtitle", "title", "name", "role", "label", "cta", "caption",
37];
38
39/// Keys whose string values are files, checked for literal media in templates.
40const FILE_KEYS: [&str; 4] = ["path", "file", "logo", "fit_to"];
41
42/// What binding takes besides the template and its data.
43#[derive(Clone, Debug, Default)]
44pub struct BindOptions {
45    /// A theme for a video template, replacing the one it names.
46    pub theme: Option<Value>,
47    /// Node templates the document may name, by their header ids.
48    pub templates: Vec<Value>,
49}
50
51/// A template's header.
52#[derive(Clone, Debug)]
53struct Header {
54    id: String,
55    version: u64,
56    kind: Kind,
57    title: Option<String>,
58    description: Option<String>,
59}
60
61#[derive(Clone, Copy, Debug, Eq, PartialEq)]
62enum Kind {
63    Video,
64    Node,
65}
66
67/// One declared parameter.
68#[derive(Clone, Debug)]
69struct Param {
70    name: String,
71    kind: ParamKind,
72    title: Option<String>,
73    description: Option<String>,
74    default: Option<Value>,
75    required: bool,
76}
77
78#[derive(Clone, Debug)]
79enum ParamKind {
80    Text {
81        min_chars: Option<u64>,
82        max_chars: Option<u64>,
83        multiline: bool,
84    },
85    Media {
86        accept: Vec<String>,
87        rules: Map<String, Value>,
88    },
89    Audio {
90        rules: Map<String, Value>,
91    },
92    Number {
93        min: Option<f64>,
94        max: Option<f64>,
95    },
96    Bool,
97    Enum(Vec<String>),
98    Color,
99    Font,
100    List {
101        min_items: Option<u64>,
102        max_items: Option<u64>,
103        item: Vec<Param>,
104    },
105    /// A compose node: what a wrapping template (a reveal, a frame) draws its effect on.
106    Node,
107}
108
109impl ParamKind {
110    const fn name(&self) -> &'static str {
111        match self {
112            Self::Text { .. } => "text",
113            Self::Media { .. } => "media",
114            Self::Audio { .. } => "audio",
115            Self::Number { .. } => "number",
116            Self::Bool => "bool",
117            Self::Enum(_) => "enum",
118            Self::Color => "color",
119            Self::Font => "font",
120            Self::List { .. } => "list",
121            Self::Node => "node",
122        }
123    }
124}
125
126fn error(path: &str, message: impl Into<String>) -> ComposeError {
127    ComposeError::new(path, message)
128}
129
130fn header(document: &Value) -> Result<Option<Header>, ComposeError> {
131    let Some(value) = document.get("template") else {
132        return Ok(None);
133    };
134    let path = "template.template";
135    let object = value
136        .as_object()
137        .ok_or_else(|| error(path, "a template header is an object"))?;
138    if let Some(field) = object
139        .keys()
140        .find(|field| !["id", "version", "kind", "title", "description"].contains(&field.as_str()))
141    {
142        return Err(error(
143            &format!("{path}.{field}"),
144            "not a template header field",
145        ));
146    }
147    let id = object
148        .get("id")
149        .and_then(Value::as_str)
150        .ok_or_else(|| error(&format!("{path}.id"), "a template has an `owner/name` id"))?;
151    let parts = id.split('/').collect::<Vec<_>>();
152    let well_named = |part: &&str| {
153        !part.is_empty()
154            && part
155                .chars()
156                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
157    };
158    if parts.len() != 2 || !parts.iter().all(well_named) {
159        return Err(error(
160            &format!("{path}.id"),
161            format!("\"{id}\" is not `owner/name` in lower-case letters, digits, `-` and `_`"),
162        ));
163    }
164    let version = object
165        .get("version")
166        .and_then(Value::as_u64)
167        .filter(|version| *version > 0)
168        .ok_or_else(|| {
169            error(
170                &format!("{path}.version"),
171                "a version is a positive integer",
172            )
173        })?;
174    let kind = match object.get("kind").and_then(Value::as_str) {
175        Some("video") | None => Kind::Video,
176        Some("node") => Kind::Node,
177        Some(other) => {
178            return Err(error(
179                &format!("{path}.kind"),
180                format!("a template is a `video` or a `node`, not \"{other}\""),
181            ));
182        }
183    };
184    let text = |field: &str| object.get(field).and_then(Value::as_str).map(str::to_owned);
185    Ok(Some(Header {
186        id: id.to_owned(),
187        version,
188        kind,
189        title: text("title"),
190        description: text("description"),
191    }))
192}
193
194fn params(value: Option<&Value>, path: &str) -> Result<Vec<Param>, ComposeError> {
195    let Some(value) = value else {
196        return Ok(Vec::new());
197    };
198    let list = value
199        .as_array()
200        .ok_or_else(|| error(path, "`params` is a list"))?;
201    let mut seen = BTreeSet::new();
202    let mut parsed = Vec::with_capacity(list.len());
203    for (index, entry) in list.iter().enumerate() {
204        let at = format!("{path}[{index}]");
205        let param = param(entry, &at)?;
206        if !seen.insert(param.name.clone()) {
207            return Err(error(
208                &format!("{at}.name"),
209                format!("{} is declared twice", param.name),
210            ));
211        }
212        parsed.push(param);
213    }
214    Ok(parsed)
215}
216
217fn param(entry: &Value, path: &str) -> Result<Param, ComposeError> {
218    let object = entry
219        .as_object()
220        .ok_or_else(|| error(path, "a parameter is an object"))?;
221    let name = object
222        .get("name")
223        .and_then(Value::as_str)
224        .filter(|name| {
225            let mut chars = name.chars();
226            chars
227                .next()
228                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
229                && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
230        })
231        .ok_or_else(|| {
232            error(
233                &format!("{path}.name"),
234                "a parameter's name is a letter or `_`, then letters, digits or `_`",
235            )
236        })?
237        .to_owned();
238    let kind = param_kind(object, path)?;
239    let default = object.get("default").cloned();
240    let required = object
241        .get("required")
242        .and_then(Value::as_bool)
243        .unwrap_or(default.is_none());
244    let text = |field: &str| object.get(field).and_then(Value::as_str).map(str::to_owned);
245    let param = Param {
246        name,
247        kind,
248        title: text("title"),
249        description: text("description"),
250        default,
251        required,
252    };
253    if let Some(default) = &param.default {
254        check_value(&param, default, &format!("{path}.default"))?;
255    }
256    Ok(param)
257}
258
259/// A parameter's type and the checks it declares.
260fn param_kind(object: &Map<String, Value>, path: &str) -> Result<ParamKind, ComposeError> {
261    let u64_field = |field: &str| object.get(field).and_then(Value::as_u64);
262    let f64_field = |field: &str| object.get(field).and_then(Value::as_f64);
263    // A minimum no binding can meet is refused here, before sample data is made for it.
264    let minimum = |field: &str| match u64_field(field) {
265        Some(least) if least > MAX_BOUND_VALUES as u64 => Err(error(
266            &format!("{path}.{field}"),
267            format!("{least} is more than a binding makes ({MAX_BOUND_VALUES} values)"),
268        )),
269        least => Ok(least),
270    };
271    Ok(match object.get("type").and_then(Value::as_str) {
272        Some("text") => ParamKind::Text {
273            min_chars: minimum("min_chars")?,
274            max_chars: u64_field("max_chars"),
275            multiline: object
276                .get("multiline")
277                .and_then(Value::as_bool)
278                .unwrap_or(false),
279        },
280        Some("media") => ParamKind::Media {
281            accept: match object.get("accept") {
282                None => vec!["image".to_owned(), "video".to_owned()],
283                Some(Value::Array(kinds)) => kinds
284                    .iter()
285                    .map(|kind| match kind.as_str() {
286                        Some(kind @ ("image" | "video")) => Ok(kind.to_owned()),
287                        _ => Err(error(
288                            &format!("{path}.accept"),
289                            "accept lists `image` and `video`",
290                        )),
291                    })
292                    .collect::<Result<Vec<_>, _>>()?,
293                Some(_) => return Err(error(&format!("{path}.accept"), "accept is a list")),
294            },
295            rules: rules(
296                object,
297                &[
298                    "aspect",
299                    "min_width",
300                    "min_height",
301                    "min_duration",
302                    "max_duration",
303                ],
304            ),
305        },
306        Some("audio") => ParamKind::Audio {
307            rules: rules(object, &["min_duration", "max_duration"]),
308        },
309        Some("number") => ParamKind::Number {
310            min: f64_field("min"),
311            max: f64_field("max"),
312        },
313        Some("bool") => ParamKind::Bool,
314        Some("enum") => {
315            let values = object
316                .get("values")
317                .and_then(Value::as_array)
318                .filter(|values| !values.is_empty())
319                .ok_or_else(|| error(&format!("{path}.values"), "an enum lists its values"))?
320                .iter()
321                .map(|value| {
322                    value
323                        .as_str()
324                        .or_else(|| value.get("value").and_then(Value::as_str))
325                        .map(str::to_owned)
326                        .ok_or_else(|| {
327                            error(
328                                &format!("{path}.values"),
329                                "a value is a string or `{value, title}`",
330                            )
331                        })
332                })
333                .collect::<Result<Vec<_>, _>>()?;
334            ParamKind::Enum(values)
335        }
336        Some("color") => ParamKind::Color,
337        Some("font") => ParamKind::Font,
338        Some("node") => ParamKind::Node,
339        Some("list") => ParamKind::List {
340            min_items: minimum("min_items")?,
341            max_items: u64_field("max_items"),
342            item: params(object.get("item"), &format!("{path}.item"))?,
343        },
344        other => {
345            return Err(error(
346                &format!("{path}.type"),
347                format!(
348                    "{} is not a parameter type; the types are text, media, audio, number, bool, \
349                     enum, color, font, list and node",
350                    other.map_or_else(|| "nothing".to_owned(), |name| format!("\"{name}\""))
351                ),
352            ));
353        }
354    })
355}
356
357fn rules(object: &Map<String, Value>, names: &[&str]) -> Map<String, Value> {
358    object
359        .iter()
360        .filter(|(field, _)| names.contains(&field.as_str()))
361        .map(|(field, value)| (field.clone(), value.clone()))
362        .collect()
363}
364
365/// Checks `value` against `param` where it can be checked without facts about files.
366fn check_value(param: &Param, value: &Value, path: &str) -> Result<(), ComposeError> {
367    let wrong = || {
368        error(
369            path,
370            format!(
371                "{} takes a {} value, not {value}",
372                param.name,
373                param.kind.name()
374            ),
375        )
376    };
377    match &param.kind {
378        ParamKind::Text {
379            min_chars,
380            max_chars,
381            multiline,
382        } => {
383            let text = value.as_str().ok_or_else(wrong)?;
384            let count = text.chars().count() as u64;
385            if min_chars.is_some_and(|min| count < min) || max_chars.is_some_and(|max| count > max)
386            {
387                return Err(error(
388                    path,
389                    format!(
390                        "{} takes {}{} characters, not {count}",
391                        param.name,
392                        min_chars.map_or_else(String::new, |min| format!("at least {min} ")),
393                        max_chars.map_or_else(String::new, |max| format!("at most {max}"))
394                    ),
395                ));
396            }
397            if !multiline && text.contains('\n') {
398                return Err(error(path, format!("{} is one line", param.name)));
399            }
400        }
401        ParamKind::Media { .. } | ParamKind::Audio { .. } | ParamKind::Font => {
402            if value.as_str().is_none_or(str::is_empty) {
403                return Err(wrong());
404            }
405        }
406        ParamKind::Number { min, max } => {
407            let number = value.as_f64().ok_or_else(wrong)?;
408            if min.is_some_and(|min| number < min) || max.is_some_and(|max| number > max) {
409                return Err(error(
410                    path,
411                    format!("{} is out of its range: {number}", param.name),
412                ));
413            }
414        }
415        ParamKind::Bool => {
416            value.as_bool().ok_or_else(wrong)?;
417        }
418        ParamKind::Enum(values) => {
419            let chosen = value.as_str().ok_or_else(wrong)?;
420            if !values.iter().any(|value| value == chosen) {
421                return Err(error(
422                    path,
423                    format!(
424                        "{} is one of {}, not \"{chosen}\"",
425                        param.name,
426                        values.join(", ")
427                    ),
428                ));
429            }
430        }
431        ParamKind::Color => {
432            serde_json::from_value::<crate::spec::SolidColor>(value.clone())
433                .map_err(|_| wrong())?;
434        }
435        ParamKind::Node => {
436            if value.get("type").and_then(Value::as_str).is_none() {
437                return Err(wrong());
438            }
439        }
440        ParamKind::List {
441            min_items,
442            max_items,
443            item,
444        } => {
445            let items = value.as_array().ok_or_else(wrong)?;
446            let count = items.len() as u64;
447            if min_items.is_some_and(|min| count < min) || max_items.is_some_and(|max| count > max)
448            {
449                return Err(error(
450                    path,
451                    format!(
452                        "{} holds a number of items out of its range: {count}",
453                        param.name
454                    ),
455                ));
456            }
457            for (index, entry) in items.iter().enumerate() {
458                resolve(item, entry, &format!("{path}[{index}]"))?;
459            }
460        }
461    }
462    Ok(())
463}
464
465/// The data for `params`: each given value checked, each missing one defaulted, refused when
466/// required, or absent.
467fn resolve(params: &[Param], data: &Value, path: &str) -> Result<Map<String, Value>, ComposeError> {
468    let empty = Map::new();
469    let given = match data {
470        Value::Null => &empty,
471        Value::Object(object) => object,
472        _ => return Err(error(path, "data is an object of parameter values")),
473    };
474    if let Some(unknown) = given
475        .keys()
476        .find(|name| !params.iter().any(|param| &param.name == *name))
477    {
478        let names = params
479            .iter()
480            .map(|param| param.name.as_str())
481            .collect::<Vec<_>>();
482        return Err(error(
483            &format!("{path}.{unknown}"),
484            format!(
485                "{unknown} is not a parameter; they are {}",
486                if names.is_empty() {
487                    "none".to_owned()
488                } else {
489                    names.join(", ")
490                }
491            ),
492        ));
493    }
494    let mut resolved = Map::new();
495    for param in params {
496        let at = format!("{path}.{}", param.name);
497        match given.get(&param.name).filter(|value| !value.is_null()) {
498            Some(value) => {
499                check_value(param, value, &at)?;
500                let value = match &param.kind {
501                    ParamKind::List { item, .. } => Value::Array(
502                        value
503                            .as_array()
504                            .into_iter()
505                            .flatten()
506                            .enumerate()
507                            .map(|(index, entry)| {
508                                resolve(item, entry, &format!("{at}[{index}]")).map(Value::Object)
509                            })
510                            .collect::<Result<Vec<_>, _>>()?,
511                    ),
512                    _ => value.clone(),
513                };
514                resolved.insert(param.name.clone(), value);
515            }
516            None => match &param.default {
517                Some(default) => {
518                    resolved.insert(param.name.clone(), default.clone());
519                }
520                None if param.required => {
521                    return Err(error(&at, format!("{} is required", param.name)));
522                }
523                None => {}
524            },
525        }
526    }
527    Ok(resolved)
528}
529
530/// What evaluating a piece of the template gives.
531enum Eval {
532    Value(Value),
533    Absent,
534    /// Several values, spliced into the list that holds them.
535    Splice(Vec<Value>),
536}
537
538/// The values in scope: parameters at the root, and one `$each` item in each frame over it.
539#[derive(Default)]
540struct Scope<'a> {
541    values: Map<String, Value>,
542    /// An `$each` item: its alias, the item, and its index as `{alias}.$index` reads it.
543    item: Option<(&'a str, &'a Value, Value)>,
544    parent: Option<&'a Scope<'a>>,
545    /// Set inside a template body, the only place directives and `{{name}}` are evaluated.
546    template: bool,
547}
548
549impl Scope<'_> {
550    /// The value at `name`, a dotted path from a parameter or alias.
551    fn lookup(&self, name: &str) -> Option<&Value> {
552        let (first, rest) = name
553            .split_once('.')
554            .map_or((name, None), |(first, rest)| (first, Some(rest)));
555        let mut scope = self;
556        let mut value = loop {
557            if let Some((alias, item, index)) = &scope.item
558                && *alias == first
559            {
560                if rest == Some("$index") && item.is_object() {
561                    return Some(index);
562                }
563                break *item;
564            }
565            match scope.parent {
566                Some(parent) => scope = parent,
567                None => break scope.values.get(first)?,
568            }
569        };
570        for part in rest.into_iter().flat_map(|rest| rest.split('.')) {
571            value = value.get(part)?;
572        }
573        Some(value)
574    }
575}
576
577/// What `value` counts against [`MAX_BOUND_VALUES`], counted no further than `limit`.
578fn cost(value: &Value, limit: usize) -> usize {
579    match value {
580        Value::String(text) => string_cost(text),
581        Value::Array(items) => items.iter().fold(1, |total, item| {
582            if total > limit {
583                total
584            } else {
585                total + cost(item, limit - total)
586            }
587        }),
588        Value::Object(object) => object.values().fold(1, |total, item| {
589            if total > limit {
590                total
591            } else {
592                total + cost(item, limit - total)
593            }
594        }),
595        _ => 1,
596    }
597}
598
599const fn string_cost(text: &str) -> usize {
600    1 + text.len() / STRING_BYTES_PER_VALUE
601}
602
603struct Binder<'a> {
604    templates: BTreeMap<String, &'a Value>,
605    stack: Vec<String>,
606    /// Values made in template bodies so far.
607    made: usize,
608}
609
610impl Binder<'_> {
611    /// Counts `count` more values made at `path`, refused past [`MAX_BOUND_VALUES`].
612    fn make(&mut self, count: usize, path: &str) -> Result<(), ComposeError> {
613        self.made = self.made.saturating_add(count);
614        if self.made > MAX_BOUND_VALUES {
615            return Err(error(
616                path,
617                format!(
618                    "binding makes more than {MAX_BOUND_VALUES} values here (a string counts one \
619                     per {STRING_BYTES_PER_VALUE} bytes)"
620                ),
621            ));
622        }
623        Ok(())
624    }
625
626    fn room(&self) -> usize {
627        MAX_BOUND_VALUES.saturating_sub(self.made)
628    }
629
630    fn eval(
631        &mut self,
632        value: &Value,
633        scope: &Scope<'_>,
634        key: Option<&str>,
635        path: &str,
636    ) -> Result<Eval, ComposeError> {
637        if scope.template && !matches!(value, Value::String(_)) {
638            self.make(1, path)?;
639        }
640        match value {
641            Value::Object(object) => self.eval_object(object, scope, path),
642            Value::Array(items) => {
643                let mut out = Vec::with_capacity(items.len());
644                for (index, item) in items.iter().enumerate() {
645                    match self.eval(item, scope, None, &format!("{path}[{index}]"))? {
646                        Eval::Value(value) => out.push(value),
647                        Eval::Absent => {}
648                        Eval::Splice(values) => out.extend(values),
649                    }
650                }
651                Ok(Eval::Value(Value::Array(out)))
652            }
653            Value::String(text) if scope.template => {
654                let text = if key.is_some_and(|key| NAME_KEYS.contains(&key)) {
655                    text.clone()
656                } else {
657                    interpolate(text, scope, path)?
658                };
659                self.make(string_cost(&text), path)?;
660                Ok(Eval::Value(Value::String(text)))
661            }
662            other => Ok(Eval::Value(other.clone())),
663        }
664    }
665
666    /// A `$param`, `$if`, `$switch` or `$each` object evaluated, or `None` for any other object.
667    fn directive(
668        &mut self,
669        object: &Map<String, Value>,
670        scope: &Scope<'_>,
671        path: &str,
672    ) -> Result<Option<Eval>, ComposeError> {
673        if let Some(name) = object.get("$param") {
674            let name = name
675                .as_str()
676                .ok_or_else(|| error(path, "`$param` names a parameter"))?;
677            if object.len() != 1 {
678                return Err(error(path, "a `$param` object has no other fields"));
679            }
680            return match scope.lookup(name) {
681                None => Ok(Some(Eval::Absent)),
682                Some(value) => {
683                    // The directive object itself was counted as one value.
684                    self.make(cost(value, self.room()).saturating_sub(1), path)?;
685                    Ok(Some(Eval::Value(value.clone())))
686                }
687            };
688        }
689        if let Some(name) = object.get("$if") {
690            let name = name
691                .as_str()
692                .ok_or_else(|| error(path, "`$if` names a parameter"))?;
693            let branch = if is_set(scope.lookup(name)) {
694                "then"
695            } else {
696                "else"
697            };
698            return match object.get(branch) {
699                Some(node) => self
700                    .eval(node, scope, None, &format!("{path}.{branch}"))
701                    .map(Some),
702                None => Ok(Some(Eval::Absent)),
703            };
704        }
705        if let Some(name) = object.get("$switch") {
706            let name = name
707                .as_str()
708                .ok_or_else(|| error(path, "`$switch` names an enum parameter"))?;
709            let chosen = scope.lookup(name).and_then(Value::as_str);
710            let cases = object.get("cases").and_then(Value::as_object);
711            let picked = chosen
712                .and_then(|chosen| {
713                    cases
714                        .and_then(|cases| cases.get(chosen))
715                        .map(|node| (node, format!("{path}.cases.{chosen}")))
716                })
717                .or_else(|| {
718                    object
719                        .get("default")
720                        .map(|node| (node, format!("{path}.default")))
721                });
722            return match picked {
723                Some((node, at)) => self.eval(node, scope, None, &at).map(Some),
724                None => Ok(Some(Eval::Absent)),
725            };
726        }
727        if let Some(name) = object.get("$each") {
728            let name = name
729                .as_str()
730                .ok_or_else(|| error(path, "`$each` names a list parameter"))?;
731            let alias = object
732                .get("as")
733                .and_then(Value::as_str)
734                .ok_or_else(|| error(path, "`$each` names each item with `as`"))?;
735            let node = object
736                .get("node")
737                .ok_or_else(|| error(path, "`$each` repeats a `node`"))?;
738            let items = scope
739                .lookup(name)
740                .and_then(Value::as_array)
741                .map_or(&[][..], Vec::as_slice);
742            let mut out = Vec::with_capacity(items.len());
743            for (index, item) in items.iter().enumerate() {
744                let inner = Scope {
745                    values: Map::new(),
746                    item: Some((alias, item, json!(index))),
747                    parent: Some(scope),
748                    template: scope.template,
749                };
750                match self.eval(node, &inner, None, &format!("{path}.node"))? {
751                    Eval::Value(value) => out.push(value),
752                    Eval::Absent => {}
753                    Eval::Splice(values) => out.extend(values),
754                }
755            }
756            return Ok(Some(Eval::Splice(out)));
757        }
758        Ok(None)
759    }
760
761    fn eval_object(
762        &mut self,
763        object: &Map<String, Value>,
764        scope: &Scope<'_>,
765        path: &str,
766    ) -> Result<Eval, ComposeError> {
767        if scope.template
768            && let Some(eval) = self.directive(object, scope, path)?
769        {
770            return Ok(eval);
771        }
772        if let Some(kind) = object.get("type").and_then(Value::as_str) {
773            if kind.contains('/') {
774                return self.instance(kind, object, scope, path).map(Eval::Value);
775            }
776            if let Some(id) = bare_template(kind) {
777                return self.bare(id, object, scope, path).map(Eval::Value);
778            }
779        }
780        let mut out = Map::with_capacity(object.len());
781        for (field, value) in object {
782            let at = format!("{path}.{field}");
783            match self.eval(value, scope, Some(field), &at)? {
784                Eval::Value(value) => {
785                    out.insert(field.clone(), value);
786                }
787                Eval::Absent => {}
788                Eval::Splice(_) => return Err(error(&at, "`$each` goes in a list")),
789            }
790        }
791        Ok(Eval::Value(Value::Object(out)))
792    }
793
794    /// A node template named by `id`, bound to the reference's `with`, as a stack carrying the
795    /// reference's placement.
796    fn instance(
797        &mut self,
798        id: &str,
799        object: &Map<String, Value>,
800        scope: &Scope<'_>,
801        path: &str,
802    ) -> Result<Value, ComposeError> {
803        self.reference(id, object, scope, &format!("{path}.with"), path)
804    }
805
806    /// Binds a 1st-party template named by its bare type, whose other fields are its data.
807    fn bare(
808        &mut self,
809        id: &str,
810        object: &Map<String, Value>,
811        scope: &Scope<'_>,
812        path: &str,
813    ) -> Result<Value, ComposeError> {
814        let (mut reference, data): (Map<_, _>, Map<_, _>) = object
815            .iter()
816            .filter(|(field, _)| field.as_str() != "type")
817            .map(|(field, value)| (field.clone(), value.clone()))
818            .partition(|(field, _)| PLACEMENT.contains(&field.as_str()));
819        reference.insert("type".to_owned(), json!(id));
820        reference.insert("with".to_owned(), Value::Object(data));
821        self.reference(id, &reference, scope, path, path)
822    }
823
824    /// [`Self::instance`], its data's errors named from `data_path`.
825    fn reference(
826        &mut self,
827        id: &str,
828        object: &Map<String, Value>,
829        scope: &Scope<'_>,
830        data_path: &str,
831        path: &str,
832    ) -> Result<Value, ComposeError> {
833        if let Some(field) = object.keys().find(|field| {
834            !["type", "with", "version"].contains(&field.as_str())
835                && !PLACEMENT.contains(&field.as_str())
836        }) {
837            return Err(error(
838                &format!("{path}.{field}"),
839                "a template node takes `with`, `version` and placement fields",
840            ));
841        }
842        let template = *self.templates.get(id).ok_or_else(|| {
843            error(
844                &format!("{path}.type"),
845                format!("no template \"{id}\" was given"),
846            )
847        })?;
848        let header = header(template)?.expect("templates are indexed by their headers");
849        if header.kind != Kind::Node {
850            return Err(error(
851                &format!("{path}.type"),
852                format!("{id} is a video template, not a node"),
853            ));
854        }
855        if let Some(version) = object.get("version")
856            && version.as_u64() != Some(header.version)
857        {
858            return Err(error(
859                &format!("{path}.version"),
860                format!("{id} is version {}, not {version}", header.version),
861            ));
862        }
863        if self.stack.iter().any(|open| open == id) || self.stack.len() >= MAX_DEPTH {
864            return Err(error(
865                path,
866                format!(
867                    "{id} names itself through its templates, or they nest deeper than {MAX_DEPTH}"
868                ),
869            ));
870        }
871        let data = match object.get("with") {
872            Some(with) => match self.eval(with, scope, None, &format!("{path}.with"))? {
873                Eval::Value(value) => value,
874                _ => Value::Null,
875            },
876            None => Value::Null,
877        };
878        self.stack.push(id.to_owned());
879        let bound = self.bind_body(
880            template,
881            &header,
882            &data,
883            data_path,
884            &format!("{path}<{id}>"),
885        );
886        self.stack.pop();
887        let node = bound?;
888        let mut stack = Map::new();
889        stack.insert("type".to_owned(), json!("stack"));
890        stack.insert("children".to_owned(), json!([node]));
891        for field in PLACEMENT {
892            if let Some(value) = object.get(field)
893                && let Eval::Value(value) =
894                    self.eval(value, scope, Some(field), &format!("{path}.{field}"))?
895            {
896                stack.insert(field.to_owned(), value);
897            }
898        }
899        Ok(Value::Object(stack))
900    }
901
902    /// A template's body bound to `data`: a video template's spec, or a node template's node.
903    fn bind_body(
904        &mut self,
905        template: &Value,
906        header: &Header,
907        data: &Value,
908        data_path: &str,
909        path: &str,
910    ) -> Result<Value, ComposeError> {
911        let params = params(template.get("params"), &format!("{path}.params"))?;
912        let values = resolve(&params, data, data_path)?;
913        let scope = Scope {
914            values,
915            template: true,
916            ..Scope::default()
917        };
918        match header.kind {
919            Kind::Node => {
920                let node = template
921                    .get("node")
922                    .ok_or_else(|| error(path, "a node template has a `node`"))?;
923                match self.eval(node, &scope, None, &format!("{path}.node"))? {
924                    Eval::Value(value) => Ok(value),
925                    _ => Err(error(
926                        &format!("{path}.node"),
927                        "a node template draws one node",
928                    )),
929                }
930            }
931            Kind::Video => {
932                let mut body = template.as_object().cloned().unwrap_or_default();
933                body.remove("template");
934                body.remove("params");
935                match self.eval(&Value::Object(body), &scope, None, path)? {
936                    Eval::Value(value) => Ok(value),
937                    _ => Err(error(path, "a video template is one spec")),
938                }
939            }
940        }
941    }
942}
943
944/// `text` with each `{{name}}` replaced by its parameter's text, number or choice; `{{{{` is a
945/// literal `{{`.
946fn interpolate(text: &str, scope: &Scope<'_>, path: &str) -> Result<String, ComposeError> {
947    if !text.contains("{{") {
948        return Ok(text.to_owned());
949    }
950    let mut out = String::with_capacity(text.len());
951    let mut rest = text;
952    while let Some(start) = rest.find("{{") {
953        out.push_str(&rest[..start]);
954        let after = &rest[start + 2..];
955        if let Some(stripped) = after.strip_prefix("{{") {
956            out.push_str("{{");
957            rest = stripped;
958            continue;
959        }
960        let end = after
961            .find("}}")
962            .ok_or_else(|| error(path, "a `{{` has no `}}`"))?;
963        let name = after[..end].trim();
964        match scope.lookup(name) {
965            None => {}
966            Some(Value::String(value)) => out.push_str(value),
967            Some(Value::Number(number)) => out.push_str(&format_number(number)),
968            Some(Value::Bool(flag)) => out.push_str(if *flag { "true" } else { "false" }),
969            Some(_) => {
970                return Err(error(
971                    path,
972                    format!("{{{{{name}}}}} is not text, a number or a choice"),
973                ));
974            }
975        }
976        rest = &after[end + 2..];
977    }
978    out.push_str(rest);
979    Ok(out)
980}
981
982/// A number as decimal text: whole numbers without a fraction.
983fn format_number(number: &serde_json::Number) -> String {
984    match number.as_f64() {
985        Some(value) if value.fract() == 0.0 && value.abs() < 1e15 => format!("{value:.0}"),
986        _ => number.to_string(),
987    }
988}
989
990fn index(templates: &[Value]) -> Result<BTreeMap<String, &Value>, ComposeError> {
991    let mut found = BTreeMap::new();
992    for (position, template) in templates.iter().enumerate() {
993        let header = header(template)
994            .map_err(|problem| {
995                error(
996                    &format!("templates[{position}].{}", problem.path),
997                    problem.message,
998                )
999            })?
1000            .ok_or_else(|| {
1001                error(
1002                    &format!("templates[{position}]"),
1003                    "a template has a `template` header",
1004                )
1005            })?;
1006        found.insert(header.id, template);
1007    }
1008    for template in crate::library::TEMPLATES.iter() {
1009        let header = header(template)?.expect("a built-in template has a header");
1010        found.entry(header.id).or_insert(template);
1011    }
1012    Ok(found)
1013}
1014
1015/// Binds `document` to `data`: a template's parameters replaced and its template nodes
1016/// expanded, giving a plain spec (or, for a node template, a plain node). A document without a
1017/// header has only its template nodes expanded; directives and `{{name}}` exist only in template
1018/// bodies. Without a header, template nodes or a theme, `bind` returns `document` unchanged.
1019///
1020/// # Errors
1021/// Returns where in the template or data, and why, it does not bind.
1022pub fn bind(document: &Value, data: &Value, options: &BindOptions) -> Result<Value, ComposeError> {
1023    let mut binder = Binder {
1024        templates: index(&options.templates)?,
1025        stack: Vec::new(),
1026        made: 0,
1027    };
1028    let header = header(document)?;
1029    let mut bound = match &header {
1030        Some(header) => {
1031            binder.stack.push(header.id.clone());
1032            binder.bind_body(document, header, data, "data", "template")?
1033        }
1034        None => match binder.eval(document, &Scope::default(), None, "spec")? {
1035            Eval::Value(value) => value,
1036            _ => return Err(error("spec", "a spec is one object")),
1037        },
1038    };
1039    if header
1040        .as_ref()
1041        .is_none_or(|header| header.kind == Kind::Video)
1042        && let Some(theme) = &options.theme
1043        && let Some(object) = bound.as_object_mut()
1044    {
1045        object.insert("theme".to_owned(), theme.clone());
1046    }
1047    Ok(bound)
1048}
1049
1050/// Fields of a template node that place it, beside its template's data.
1051const PLACEMENT: [&str; 6] = ["id", "at", "duration", "inset", "enter", "exit"];
1052
1053/// Node types that name a 1st-party template without its `alpha2/` owner.
1054pub(crate) const BARE: [(&str, &str); 7] = [
1055    ("title", "alpha2/title"),
1056    ("title_card", "alpha2/title-card"),
1057    ("lower_third", "alpha2/lower-third"),
1058    ("end_card", "alpha2/end-card"),
1059    ("logo", "alpha2/logo"),
1060    ("reframe", "alpha2/reframe"),
1061    ("comparison_grid", "alpha2/comparison-grid"),
1062];
1063
1064fn bare_template(kind: &str) -> Option<&'static str> {
1065    BARE.iter()
1066        .find(|(name, _)| *name == kind)
1067        .map(|(_, id)| *id)
1068}
1069
1070/// Whether `$if` takes its `then`, for a true bool or any other value that is given and not empty.
1071fn is_set(value: Option<&Value>) -> bool {
1072    match value {
1073        None | Some(Value::Null) => false,
1074        Some(Value::Bool(value)) => *value,
1075        Some(Value::String(text)) => !text.is_empty(),
1076        Some(Value::Array(items)) => !items.is_empty(),
1077        Some(Value::Object(fields)) => !fields.is_empty(),
1078        Some(Value::Number(_)) => true,
1079    }
1080}
1081
1082/// The JSON Schema (2020-12) of a template's data, with each parameter's title, description,
1083/// default and checks a schema can say; file rules are in `x-alpha2-media`.
1084///
1085/// # Errors
1086/// Returns where the template's header or parameters do not parse.
1087///
1088/// # Panics
1089/// Never; an object schema is always an object.
1090pub fn data_schema(template: &Value) -> Result<Value, ComposeError> {
1091    let header =
1092        header(template)?.ok_or_else(|| error("template", "a template has a `template` header"))?;
1093    let params = params(template.get("params"), "template.params")?;
1094    let mut schema = object_schema(&params);
1095    let object = schema.as_object_mut().expect("an object schema");
1096    object.insert(
1097        "$schema".to_owned(),
1098        json!("https://json-schema.org/draft/2020-12/schema"),
1099    );
1100    if let Some(name) = header.id.strip_prefix("alpha2/") {
1101        object.insert(
1102            "$id".to_owned(),
1103            json!(format!(
1104                "https://alpha2.sh/templates/{name}/v{}/data.json",
1105                header.version
1106            )),
1107        );
1108    }
1109    object.insert("title".to_owned(), json!(header.title.unwrap_or(header.id)));
1110    if let Some(description) = header.description {
1111        object.insert("description".to_owned(), json!(description));
1112    }
1113    Ok(schema)
1114}
1115
1116/// Where a data schema's references to compose types point.
1117#[derive(Clone, Copy)]
1118enum Refs {
1119    /// The published compose schema, for a data schema of its own.
1120    Published,
1121    /// `#/$defs`, inside the compose schema.
1122    #[cfg_attr(not(feature = "schema"), allow(dead_code))]
1123    Local,
1124}
1125
1126impl Refs {
1127    fn to(self, name: &str) -> Value {
1128        match self {
1129            Self::Published => {
1130                json!({"$ref": format!("{}#/$defs/{name}", crate::spec::COMPOSE_SCHEMA_ID)})
1131            }
1132            Self::Local => json!({"$ref": format!("#/$defs/{name}")}),
1133        }
1134    }
1135}
1136
1137/// Compose schema variants for template nodes. Each 1st-party template gets typed variants for
1138/// its `alpha2/` id and bare name, and one variant takes any other `owner/name`.
1139#[cfg(feature = "schema")]
1140pub(crate) fn node_schemas() -> Vec<Value> {
1141    let placement = |properties: &mut Map<String, Value>| {
1142        properties.insert("id".to_owned(), json!({"type": "string", "description": "The node's name, for other nodes to refer to."}));
1143        properties.insert("at".to_owned(), json!({"type": "number", "description": "Seconds from the parent's start (an overlay's: the video's). Ignored in a sequence."}));
1144        properties.insert("duration".to_owned(), json!({"type": "number", "description": "Length in seconds. Default: the template's own, else what its parent gives it."}));
1145        let described = |name: &str, description: &str| {
1146            let mut schema = Refs::Local.to(name);
1147            schema["description"] = json!(description);
1148            schema
1149        };
1150        properties.insert("inset".to_owned(), described("Inset", "Pixels kept clear inside the parent's area: one number, or `[top, right, bottom, left]`."));
1151        properties.insert(
1152            "enter".to_owned(),
1153            described("Motion", "How it comes in at its start."),
1154        );
1155        properties.insert(
1156            "exit".to_owned(),
1157            described("Motion", "How it goes out, ending at its end."),
1158        );
1159    };
1160    let mut variants = Vec::new();
1161    for template in crate::library::TEMPLATES.iter() {
1162        let header = header(template)
1163            .ok()
1164            .flatten()
1165            .expect("a built-in template has a header");
1166        let params = params(template.get("params"), "template.params")
1167            .expect("a built-in template's parameters parse");
1168        let data = object_schema_with(&params, Refs::Local);
1169        let description = header.description.clone().unwrap_or_default();
1170        if let Some((name, _)) = BARE.iter().find(|(_, id)| *id == header.id) {
1171            let mut properties = data["properties"].as_object().cloned().unwrap_or_default();
1172            properties.insert("type".to_owned(), json!({"const": name}));
1173            placement(&mut properties);
1174            let mut required = data["required"].as_array().cloned().unwrap_or_default();
1175            required.insert(0, json!("type"));
1176            variants.push(json!({
1177                "type": "object",
1178                "description": description,
1179                "properties": properties,
1180                "required": required,
1181                "additionalProperties": false,
1182            }));
1183        }
1184        let mut properties = Map::new();
1185        properties.insert("type".to_owned(), json!({"const": header.id}));
1186        properties.insert(
1187            "version".to_owned(),
1188            json!({"const": header.version, "description": "The template's version."}),
1189        );
1190        let mut with = data.clone();
1191        with["description"] = json!("The template's data.");
1192        properties.insert("with".to_owned(), with);
1193        placement(&mut properties);
1194        let required = if data["required"]
1195            .as_array()
1196            .is_some_and(|list| !list.is_empty())
1197        {
1198            json!(["type", "with"])
1199        } else {
1200            json!(["type"])
1201        };
1202        variants.push(json!({
1203            "type": "object",
1204            "description": description,
1205            "properties": properties,
1206            "required": required,
1207            "additionalProperties": false,
1208        }));
1209    }
1210    let mut properties = Map::new();
1211    properties.insert(
1212        "type".to_owned(),
1213        json!({
1214            "type": "string",
1215            "pattern": "^[a-z0-9_-]+/[a-z0-9_-]+$",
1216            "not": {"pattern": "^alpha2/"},
1217            "description": "A template's `owner/name` id; the spec is compiled with it.",
1218        }),
1219    );
1220    properties.insert(
1221        "version".to_owned(),
1222        json!({"type": "integer", "minimum": 1, "description": "The template's version; when given, it must be the given template's."}),
1223    );
1224    properties.insert(
1225        "with".to_owned(),
1226        json!({"type": "object", "description": "The template's data."}),
1227    );
1228    placement(&mut properties);
1229    variants.push(json!({
1230        "type": "object",
1231        "description": "A node template by its id, bound to `with`.",
1232        "properties": properties,
1233        "required": ["type"],
1234        "additionalProperties": false,
1235    }));
1236    variants
1237}
1238
1239fn object_schema(params: &[Param]) -> Value {
1240    object_schema_with(params, Refs::Published)
1241}
1242
1243fn object_schema_with(params: &[Param], refs: Refs) -> Value {
1244    let properties = params
1245        .iter()
1246        .map(|param| (param.name.clone(), param_schema(param, refs)))
1247        .collect::<Map<_, _>>();
1248    let required = params
1249        .iter()
1250        .filter(|param| param.required && param.default.is_none())
1251        .map(|param| json!(param.name))
1252        .collect::<Vec<_>>();
1253    json!({
1254        "type": "object",
1255        "properties": properties,
1256        "required": required,
1257        "additionalProperties": false,
1258    })
1259}
1260
1261fn param_schema(param: &Param, refs: Refs) -> Value {
1262    let mut schema = match &param.kind {
1263        ParamKind::Text {
1264            min_chars,
1265            max_chars,
1266            ..
1267        } => json!({"type": "string", "minLength": min_chars, "maxLength": max_chars}),
1268        ParamKind::Media { accept, rules } => {
1269            let mut media = rules.clone();
1270            media.insert("accept".to_owned(), json!(accept));
1271            json!({"type": "string", "format": "uri-reference", "x-alpha2-media": media})
1272        }
1273        ParamKind::Audio { rules } => {
1274            json!({"type": "string", "format": "uri-reference", "x-alpha2-audio": rules})
1275        }
1276        ParamKind::Number { min, max } => json!({"type": "number", "minimum": min, "maximum": max}),
1277        ParamKind::Bool => json!({"type": "boolean"}),
1278        ParamKind::Enum(values) => json!({"enum": values}),
1279        ParamKind::Color => refs.to("SolidColor"),
1280        ParamKind::Font => json!({"type": "string", "description": "A font family the host has."}),
1281        ParamKind::Node => refs.to("Node"),
1282        ParamKind::List {
1283            min_items,
1284            max_items,
1285            item,
1286        } => json!({
1287            "type": "array",
1288            "items": object_schema_with(item, refs),
1289            "minItems": min_items,
1290            "maxItems": max_items,
1291        }),
1292    };
1293    let object = schema.as_object_mut().expect("an object schema");
1294    object.retain(|_, value| !value.is_null());
1295    if let Some(title) = &param.title {
1296        object.insert("title".to_owned(), json!(title));
1297    }
1298    if let Some(description) = &param.description {
1299        object.insert("description".to_owned(), json!(description));
1300    }
1301    if let Some(default) = &param.default {
1302        object.insert("default".to_owned(), default.clone());
1303    }
1304    schema
1305}
1306
1307/// Problems with a template, and with `data` for it when given: its header and parameters, the
1308/// parameters its body names, literal content a template leaves to its data or theme, and
1309/// whether it binds to a spec that parses. Without data it binds to sample data.
1310///
1311/// Paths are into the template (`template.params[0]`, `template.node.children[1]`) or the
1312/// data (`data.title`); a diagnostic has no place in the text.
1313#[must_use]
1314pub fn lint(template: &Value, data: Option<&Value>, templates: &[Value]) -> Vec<Diagnostic> {
1315    let mut issues = Vec::new();
1316    let fail = |issues: &mut Vec<Diagnostic>, code: &'static Code, problem: ComposeError| {
1317        issues.push(Diagnostic::new(
1318            code,
1319            path_of(&problem.path, "template"),
1320            problem.message,
1321        ));
1322    };
1323    let header = match header(template) {
1324        Ok(Some(header)) => header,
1325        Ok(None) => {
1326            fail(
1327                &mut issues,
1328                &TEMPLATE_HEADER,
1329                error("template", "a template has a `template` header"),
1330            );
1331            return issues;
1332        }
1333        Err(problem) => {
1334            fail(&mut issues, &TEMPLATE_HEADER, problem);
1335            return issues;
1336        }
1337    };
1338    let declared = match params(template.get("params"), "template.params") {
1339        Ok(params) => params,
1340        Err(problem) => {
1341            fail(&mut issues, &TEMPLATE_PARAMS, problem);
1342            return issues;
1343        }
1344    };
1345    let (body, root) = match header.kind {
1346        Kind::Node => (
1347            template.get("node").cloned().unwrap_or(Value::Null),
1348            "template.node",
1349        ),
1350        Kind::Video => {
1351            let mut body = template.as_object().cloned().unwrap_or_default();
1352            body.remove("template");
1353            body.remove("params");
1354            (Value::Object(body), "template")
1355        }
1356    };
1357    let mut used = BTreeSet::new();
1358    let mut scope = declared
1359        .iter()
1360        .map(|param| param.name.clone())
1361        .collect::<BTreeSet<_>>();
1362    names(&body, &mut scope, &mut used, root, &mut issues, &declared);
1363    for (index, param) in declared.iter().enumerate() {
1364        if !used.contains(&param.name) {
1365            issues.push(Diagnostic::new(
1366                &TEMPLATE_UNUSED_PARAM,
1367                path_of(&format!("template.params[{index}]"), "template"),
1368                format!("{} is declared but never used", param.name),
1369            ));
1370        }
1371    }
1372    content(&body, None, root, &mut issues);
1373    let sample = match data.cloned().map_or_else(|| least_data(&declared), Ok) {
1374        Ok(sample) => sample,
1375        Err(problem) => {
1376            fail(&mut issues, &TEMPLATE_BIND, problem);
1377            return issues;
1378        }
1379    };
1380    let options = BindOptions {
1381        theme: None,
1382        templates: templates.to_vec(),
1383    };
1384    match bind(template, &sample, &options) {
1385        Err(problem) => fail(&mut issues, &TEMPLATE_BIND, problem),
1386        Ok(bound) => {
1387            let parsed = match header.kind {
1388                Kind::Video => {
1389                    crate::parse_spec(&bound.to_string())
1390                        .map(|_| ())
1391                        .map_err(|problem| {
1392                            error(
1393                                &rerooted(&problem.path, "spec", "template"),
1394                                problem.message,
1395                            )
1396                        })
1397                }
1398                Kind::Node => crate::de::from_value::<crate::spec::Node>(bound)
1399                    .map(|_| ())
1400                    .map_err(|located| {
1401                        error(
1402                            &crate::de::join("template.node", &located.path),
1403                            located.message,
1404                        )
1405                    }),
1406            };
1407            if let Err(problem) = parsed {
1408                fail(&mut issues, &TEMPLATE_SPEC, problem);
1409            }
1410        }
1411    }
1412    issues
1413}
1414
1415fn rerooted(path: &str, from: &str, to: &str) -> String {
1416    path.strip_prefix(from)
1417        .filter(|rest| rest.is_empty() || rest.starts_with(['.', '[']))
1418        .map_or_else(|| path.to_owned(), |rest| format!("{to}{rest}"))
1419}
1420
1421/// Notes the parameters `value` names, flagging names no parameter or alias has and directives
1422/// on parameters of the wrong type.
1423fn names(
1424    value: &Value,
1425    scope: &mut BTreeSet<String>,
1426    used: &mut BTreeSet<String>,
1427    path: &str,
1428    issues: &mut Vec<Diagnostic>,
1429    declared: &[Param],
1430) {
1431    let mut note = |name: &str, path: &str, want: Option<&str>, issues: &mut Vec<Diagnostic>| {
1432        let root = name.split('.').next().unwrap_or(name);
1433        used.insert(root.to_owned());
1434        if !scope.contains(root) {
1435            issues.push(Diagnostic::new(
1436                &TEMPLATE_UNKNOWN_PARAM,
1437                path_of(path, "template"),
1438                format!("{name} is not a parameter"),
1439            ));
1440        } else if let Some(want) = want
1441            && let Some(param) = declared.iter().find(|param| param.name == root)
1442            && !name.contains('.')
1443            && param.kind.name() != want
1444        {
1445            issues.push(Diagnostic::new(
1446                &TEMPLATE_PARAM_TYPE,
1447                path_of(path, "template"),
1448                format!("{name} is a {} parameter, not a {want}", param.kind.name()),
1449            ));
1450        }
1451    };
1452    match value {
1453        Value::Object(object) => {
1454            for (directive, want) in [
1455                ("$param", None),
1456                ("$if", None),
1457                ("$switch", Some("enum")),
1458                ("$each", Some("list")),
1459            ] {
1460                if let Some(name) = object.get(directive).and_then(Value::as_str) {
1461                    note(name, path, want, issues);
1462                }
1463            }
1464            let alias = object
1465                .get("$each")
1466                .and(object.get("as"))
1467                .and_then(Value::as_str)
1468                .map(str::to_owned);
1469            let added = alias
1470                .as_ref()
1471                .is_some_and(|alias| scope.insert(alias.clone()));
1472            for (field, inner) in object {
1473                if field.starts_with('$') && field != "$theme" {
1474                    continue;
1475                }
1476                names(
1477                    inner,
1478                    scope,
1479                    used,
1480                    &format!("{path}.{field}"),
1481                    issues,
1482                    declared,
1483                );
1484            }
1485            if let Some(node) = object.get("node").filter(|_| alias.is_some()) {
1486                names(node, scope, used, &format!("{path}.node"), issues, declared);
1487            }
1488            if added && let Some(alias) = alias {
1489                scope.remove(&alias);
1490            }
1491        }
1492        Value::Array(items) => {
1493            for (index, item) in items.iter().enumerate() {
1494                names(
1495                    item,
1496                    scope,
1497                    used,
1498                    &format!("{path}[{index}]"),
1499                    issues,
1500                    declared,
1501                );
1502            }
1503        }
1504        Value::String(text) => {
1505            let mut rest = text.as_str();
1506            while let Some(start) = rest.find("{{") {
1507                let after = &rest[start + 2..];
1508                if let Some(stripped) = after.strip_prefix("{{") {
1509                    rest = stripped;
1510                    continue;
1511                }
1512                let Some(end) = after.find("}}") else { break };
1513                note(after[..end].trim(), path, None, issues);
1514                rest = &after[end + 2..];
1515            }
1516        }
1517        _ => {}
1518    }
1519}
1520
1521/// Flags literal files, colors and copy, which a template takes from its data and theme.
1522fn content(value: &Value, key: Option<&str>, path: &str, issues: &mut Vec<Diagnostic>) {
1523    let mut flag = |code: &'static Code, message: String| {
1524        issues.push(Diagnostic::new(code, path_of(path, "template"), message));
1525    };
1526    match value {
1527        Value::Object(object) => {
1528            if object.contains_key("$param") || object.contains_key("$theme") {
1529                return;
1530            }
1531            if let Ok(color) = serde_json::from_value::<alpha2_model::Rgba>(value.clone())
1532                && object.contains_key("red")
1533                && !structural(color)
1534            {
1535                flag(
1536                    &TEMPLATE_LITERAL_COLOR,
1537                    "a template takes colors from its theme or data".to_owned(),
1538                );
1539                return;
1540            }
1541            for (field, inner) in object {
1542                content(inner, Some(field), &format!("{path}.{field}"), issues);
1543            }
1544        }
1545        Value::Array(items) => {
1546            for (index, item) in items.iter().enumerate() {
1547                content(item, key, &format!("{path}[{index}]"), issues);
1548            }
1549        }
1550        Value::String(text) => {
1551            let key = key.unwrap_or_default();
1552            if FILE_KEYS.contains(&key) {
1553                flag(
1554                    &TEMPLATE_LITERAL_MEDIA,
1555                    format!("a template takes files from its data, not \"{text}\""),
1556                );
1557            } else if text.starts_with('#')
1558                && let Some(color) = alpha2_model::Rgba::from_hex(text)
1559                && !structural(color)
1560            {
1561                flag(
1562                    &TEMPLATE_LITERAL_COLOR,
1563                    format!("a template takes colors from its theme or data, not {text}"),
1564                );
1565            } else if TEXT_KEYS.contains(&key) && literal_copy(text) {
1566                flag(
1567                    &TEMPLATE_LITERAL_TEXT,
1568                    format!("a template takes its words from its data, not \"{text}\""),
1569                );
1570            }
1571        }
1572        _ => {}
1573    }
1574}
1575
1576/// Whether `color` is structural: transparent, or black or white at any opacity.
1577#[allow(clippy::float_cmp)]
1578fn structural(color: alpha2_model::Rgba) -> bool {
1579    color.alpha == 0.0
1580        || [color.red, color.green, color.blue]
1581            .iter()
1582            .all(|part| *part == 0.0)
1583        || [color.red, color.green, color.blue]
1584            .iter()
1585            .all(|part| *part == 1.0)
1586}
1587
1588/// Whether `text`, its `{{...}}` taken out, still holds a letter or digit.
1589fn literal_copy(text: &str) -> bool {
1590    let mut rest = text;
1591    let mut plain = String::new();
1592    while let Some(start) = rest.find("{{") {
1593        plain.push_str(&rest[..start]);
1594        match rest[start + 2..].find("}}") {
1595            Some(end) => rest = &rest[start + 2 + end + 2..],
1596            None => {
1597                rest = "";
1598            }
1599        }
1600    }
1601    plain.push_str(rest);
1602    plain.chars().any(char::is_alphanumeric)
1603}
1604
1605/// [`sample_data`] for `params`, or why the least data they take is more than a binding makes.
1606fn least_data(params: &[Param]) -> Result<Value, ComposeError> {
1607    sample_data(params, &mut { MAX_BOUND_VALUES }).ok_or_else(|| {
1608        error(
1609            "template.params",
1610            format!("the least data the parameters take makes more than {MAX_BOUND_VALUES} values"),
1611        )
1612    })
1613}
1614
1615/// Data that satisfies `params`, for checking a template without data of its own, made only
1616/// while it stays within [`MAX_BOUND_VALUES`] (`room` is what is left).
1617fn sample_data(params: &[Param], room: &mut usize) -> Option<Value> {
1618    let mut data = Map::new();
1619    for param in params {
1620        if param.default.is_some() || !param.required {
1621            continue;
1622        }
1623        *room = room.checked_sub(1)?;
1624        let value = match &param.kind {
1625            ParamKind::Text {
1626                min_chars,
1627                max_chars,
1628                ..
1629            } => {
1630                let least = min_chars.unwrap_or(1).max(1);
1631                let length = 4.clamp(least, max_chars.unwrap_or(u64::MAX).max(least));
1632                let length = usize::try_from(length).unwrap_or(4);
1633                *room = room.checked_sub(length / STRING_BYTES_PER_VALUE)?;
1634                json!("x".repeat(length))
1635            }
1636            ParamKind::Media { accept, .. } => {
1637                json!(if accept.iter().any(|kind| kind == "video") {
1638                    "sample.mp4"
1639                } else {
1640                    "sample.png"
1641                })
1642            }
1643            ParamKind::Audio { .. } => json!("sample.m4a"),
1644            ParamKind::Number { min, max } => json!(min.or(*max).unwrap_or(0.0)),
1645            ParamKind::Bool => json!(false),
1646            ParamKind::Enum(values) => json!(values[0]),
1647            ParamKind::Color => json!("#808080"),
1648            ParamKind::Font => json!("sans-serif"),
1649            ParamKind::Node => json!({"type": "color"}),
1650            ParamKind::List {
1651                min_items, item, ..
1652            } => {
1653                let count = usize::try_from(min_items.unwrap_or(1).max(1)).unwrap_or(1);
1654                let mut items = Vec::with_capacity(count.min(*room));
1655                for _ in 0..count {
1656                    *room = room.checked_sub(1)?;
1657                    items.push(sample_data(item, room)?);
1658                }
1659                Value::Array(items)
1660            }
1661        };
1662        data.insert(param.name.clone(), value);
1663    }
1664    Some(Value::Object(data))
1665}
1666
1667#[cfg(test)]
1668mod tests;