alpha2-compose 0.10.0

Compiles alpha2 compose specs (sequences, stacks, grids, presets) into project documents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! The published JSON Schemas of the compose spec.
//!
//! They describe shape only: types, required fields, tags and unknown-field rejection. Ranges
//! and file facts are checked by [`crate::compile`].

use std::collections::BTreeSet;

use serde_json::{Map, Value, json};

pub use crate::spec::COMPOSE_SCHEMA_ID;

/// Where the core compose schema, the one without the engine-level nodes, is published.
pub const COMPOSE_CORE_SCHEMA_ID: &str = "https://alpha2.sh/schema/compose-core.v1.json";

/// Node types the core schema leaves out, since they take engine documents as they are.
const ADVANCED_NODES: [&str; 2] = ["raw", "layout"];

/// The compose spec as schemars writes it, every type inline.
fn generated() -> Value {
    let mut schema = schemars::generate::SchemaSettings::draft2020_12()
        .for_deserialize()
        .into_generator()
        .into_root_schema_for::<crate::VideoSpec>();
    schema.insert(
        "title".to_owned(),
        Value::String(format!(
            "alpha2 compose spec, version {}",
            crate::COMPOSE_VERSION
        )),
    );
    let mut value = schema.to_value();
    alpha2_model::finish_json_schema(&mut value);
    value["$defs"]["EffectUse"] = effect_use_schema();
    value["$defs"]["GeneratorUse"] = generator_use_schema();
    if let Some(nodes) = value["$defs"]["Node"]["oneOf"].as_array_mut() {
        nodes.extend(crate::template::node_schemas());
    }
    if let Some(defs) = value["$defs"].as_object_mut() {
        defs.extend(animation_defs());
    }
    value
}

/// An effect use as one variant per built-in effect, its parameters typed and ranged as the
/// catalog declares them, plus any effect by its full id.
fn effect_use_schema() -> Value {
    use_schema(
        alpha2_model::EffectKind::Effect,
        "alpha2.effect.",
        "A host's effect by its full id, with its parameters by name.",
        "One effect: a built-in by its short name, or any effect by its full id, with its parameters by name. A parameter is a constant, a ramp or keys; a named image input is a node.",
    )
}

fn generator_use_schema() -> Value {
    use_schema(
        alpha2_model::EffectKind::Generator,
        "alpha2.generator.",
        "A host's generator by its full id, with its parameters by name.",
        "One generator: a built-in by its short name, or any generator by its full id, with its parameters by name. A parameter is a constant, a ramp or keys.",
    )
}

fn use_schema(
    kind: alpha2_model::EffectKind,
    prefix: &str,
    host: &str,
    description: &str,
) -> Value {
    let mut variants = alpha2_model::builtin_effects()
        .iter()
        .filter(|spec| spec.kind == kind)
        .map(|spec| {
            let short = spec.id.strip_prefix(prefix).unwrap_or(&spec.id).to_owned();
            let mut properties = Map::new();
            properties.insert("effect".to_owned(), json!({"const": short}));
            properties.insert(
                "version".to_owned(),
                json!({"const": spec.version, "description": "The built-in's version."}),
            );
            for param in &spec.params {
                properties.insert(
                    param.name.clone(),
                    animated(&param_value_schema(param), base_name(param.param_type)),
                );
            }
            for input in &spec.inputs {
                properties.insert(
                    input.clone(),
                    json!({"$ref": "#/$defs/Node", "description": "A node drawn as this image."}),
                );
            }
            let mut required = vec![json!("effect")];
            required.extend(spec.inputs.iter().map(|input| json!(input)));
            json!({
                "type": "object",
                "title": spec.label,
                "properties": properties,
                "required": required,
                "additionalProperties": false,
            })
        })
        .collect::<Vec<_>>();
    variants.push(json!({
        "type": "object",
        "description": host,
        "properties": {
            "effect": {
                "type": "string",
                "pattern": "^[^.]+\\..+$",
                "description": "The full id, with its dots.",
            },
            "version": {
                "type": "integer",
                "minimum": 1,
                "description": "The version the id names. Default 1.",
            },
        },
        "required": ["effect"],
        "additionalProperties": true,
    }));
    json!({
        "description": description,
        "oneOf": variants,
    })
}

/// The base type a parameter's ramps and keys use.
const fn base_name(param_type: alpha2_model::EffectParamType) -> &'static str {
    use alpha2_model::EffectParamType as Type;
    match param_type {
        Type::Float => "number",
        Type::Vec2 => "vec2",
        Type::Vec4 => "vec4",
        Type::Color => "color",
        Type::Enum => "choice",
        Type::Bool => "bool",
    }
}

/// What one value of a built-in's parameter is written as.
fn param_value_schema(param: &alpha2_model::EffectParamSpec) -> Value {
    use alpha2_model::EffectParamType as Type;
    let number = || {
        let mut number = json!({"type": "number"});
        if let Some(min) = param.min {
            number["minimum"] = json!(min);
        }
        if let Some(max) = param.max {
            number["maximum"] = json!(max);
        }
        number
    };
    let mut schema = match param.param_type {
        Type::Float => number(),
        Type::Vec2 => json!({"type": "array", "items": number(), "minItems": 2, "maxItems": 2}),
        Type::Vec4 => json!({"type": "array", "items": number(), "minItems": 4, "maxItems": 4}),
        Type::Color => json!({"$ref": "#/$defs/Rgba"}),
        Type::Enum => json!({"enum": param.enum_values}),
        Type::Bool => json!({"type": "boolean"}),
    };
    if let Some(object) = schema.as_object_mut() {
        object.insert("title".to_owned(), json!(param.label));
    }
    schema
}

/// A constant `value`, or a ramp or keys of its base type, by reference.
fn animated(value: &Value, base: &str) -> Value {
    json!({"anyOf": [
        value,
        {"$ref": format!("#/$defs/EffectRamp_{base}")},
        {"$ref": format!("#/$defs/EffectKeys_{base}")},
    ]})
}

/// The ramp and keys of each parameter base type, shared by every effect.
fn animation_defs() -> Vec<(String, Value)> {
    let described = |schema: &Value, description: &str| {
        let mut schema = schema.clone();
        schema["description"] = json!(description);
        schema
    };
    let ease = json!({"$ref": "#/$defs/EasingChoice"});
    let extrapolation = json!({"$ref": "#/$defs/Extrapolation"});
    let bases = [
        ("number", json!({"type": "number"})),
        (
            "vec2",
            json!({"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}),
        ),
        (
            "vec4",
            json!({"type": "array", "items": {"type": "number"}, "minItems": 4, "maxItems": 4}),
        ),
        ("color", json!({"$ref": "#/$defs/Rgba"})),
        ("choice", json!({"type": "string"})),
        ("bool", json!({"type": "boolean"})),
    ];
    bases
        .into_iter()
        .flat_map(|(base, value)| {
            [
                (
                    format!("EffectRamp_{base}"),
                    json!({
                        "type": "object",
                        "description": "A change from `from` to `to` over the node's time.",
                        "properties": {
                            "from": described(&value, "The value at the start."),
                            "to": described(&value, "The value at the end."),
                            "ease": described(&ease, "The timing curve. Default linear."),
                            "at": {
                                "type": "number",
                                "minimum": 0,
                                "description": "When it starts, in seconds from the node's start. Default 0.",
                            },
                            "duration": {
                                "type": "number",
                                "minimum": 0,
                                "description": "How long it lasts, in seconds. Default: to the node's end.",
                            },
                        },
                        "required": ["from", "to"],
                        "additionalProperties": false,
                    }),
                ),
                (
                    format!("EffectKeys_{base}"),
                    json!({
                        "type": "object",
                        "description": "Values at seconds from the node's start.",
                        "properties": {
                            "keys": {
                                "type": "array",
                                "minItems": 1,
                                "description": "The keys, in increasing time; at least one.",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "t": {
                                            "type": "number",
                                            "minimum": 0,
                                            "description": "Seconds from the node's start.",
                                        },
                                        "v": described(&value, "The value."),
                                        "ease": described(&ease, "The timing curve to the next key. Default linear."),
                                    },
                                    "required": ["t", "v"],
                                    "additionalProperties": false,
                                },
                            },
                            "before": described(&extrapolation, "What the value does before the first key. Default `hold`."),
                            "after": described(&extrapolation, "What the value does after the last key. Default `hold`."),
                        },
                        "required": ["keys"],
                        "additionalProperties": false,
                    }),
                ),
            ]
        })
        .collect()
}

/// The JSON Schema (draft 2020-12) of the current compose spec. Types it shares with the project
/// document are `$ref`s into the project schema rather than copies.
///
/// # Panics
/// Never; a generated root schema has definitions.
#[must_use]
pub fn compose_json_schema() -> Value {
    let mut schema = generated();
    let project = alpha2_model::project_json_schema();
    let project_defs = project["$defs"].as_object().cloned().unwrap_or_default();
    let defs = schema["$defs"]
        .as_object_mut()
        .expect("the schema has definitions");
    let shared = defs
        .iter()
        .filter(|(name, def)| project_defs.get(*name) == Some(*def))
        .map(|(name, _)| name.clone())
        .collect::<BTreeSet<_>>();
    defs.retain(|name, _| !shared.contains(name));
    rewrite_refs(&mut schema, &shared);
    insert_front(&mut schema, "$id", COMPOSE_SCHEMA_ID);
    schema
}

/// The compose spec without its engine-level nodes (`raw`, `layout`), self-contained: the
/// schema an agent writes specs against.
#[must_use]
pub fn compose_core_json_schema() -> Value {
    let mut schema = generated();
    if let Some(node) = schema["$defs"]["Node"]["oneOf"].as_array_mut() {
        node.retain(|variant| {
            let tag = variant["properties"]["type"]["const"]
                .as_str()
                .unwrap_or_default();
            !ADVANCED_NODES.contains(&tag)
        });
    }
    prune(&mut schema);
    insert_front(&mut schema, "$id", COMPOSE_CORE_SCHEMA_ID);
    if let Some(object) = schema.as_object_mut() {
        object.insert(
            "title".to_owned(),
            Value::String(format!(
                "alpha2 compose spec, core, version {}",
                crate::COMPOSE_VERSION
            )),
        );
    }
    schema
}

/// The self-contained compose spec schema without prose, as the diagnostics walker embeds it.
/// Definitions shared with the project schema are marked `x-topic: project`.
#[must_use]
pub fn compose_shape_json() -> Value {
    let mut schema = generated();
    prune(&mut schema);
    let project = alpha2_model::project_json_schema();
    let project_defs = project["$defs"].as_object().cloned().unwrap_or_default();
    if let Some(defs) = schema["$defs"].as_object_mut() {
        for (name, def) in defs.iter_mut() {
            if project_defs.get(name) == Some(def)
                && let Some(object) = def.as_object_mut()
            {
                object.insert("x-topic".to_owned(), Value::String("project".to_owned()));
            }
        }
    }
    alpha2_model::strip_json_schema_prose(&mut schema);
    insert_front(&mut schema, "$id", COMPOSE_SCHEMA_ID);
    schema
}

fn insert_front(schema: &mut Value, key: &str, value: &str) {
    if let Some(object) = schema.as_object_mut() {
        let rest = std::mem::take(object);
        object.insert(key.to_owned(), Value::String(value.to_owned()));
        object.extend(rest);
    }
}

/// Points every local `$ref` to a shared type at the project schema.
fn rewrite_refs(value: &mut Value, shared: &BTreeSet<String>) {
    match value {
        Value::Object(object) => {
            if let Some(Value::String(reference)) = object.get_mut("$ref")
                && let Some(name) = reference.strip_prefix("#/$defs/")
                && shared.contains(name)
            {
                *reference = format!("{}#/$defs/{name}", alpha2_model::PROJECT_SCHEMA_ID);
            }
            object
                .values_mut()
                .for_each(|value| rewrite_refs(value, shared));
        }
        Value::Array(items) => items
            .iter_mut()
            .for_each(|value| rewrite_refs(value, shared)),
        _ => {}
    }
}

/// Drops the definitions nothing reachable from the root names.
fn prune(schema: &mut Value) {
    let defs = schema["$defs"].as_object().cloned().unwrap_or_default();
    let mut reached = BTreeSet::new();
    let mut pending = Vec::new();
    let mut root = schema.clone();
    if let Some(object) = root.as_object_mut() {
        object.remove("$defs");
    }
    refs(&root, &mut pending);
    while let Some(name) = pending.pop() {
        if reached.insert(name.clone())
            && let Some(def) = defs.get(&name)
        {
            refs(def, &mut pending);
        }
    }
    let kept = defs
        .into_iter()
        .filter(|(name, _)| reached.contains(name))
        .collect::<Map<_, _>>();
    schema["$defs"] = Value::Object(kept);
}

fn refs(value: &Value, found: &mut Vec<String>) {
    match value {
        Value::Object(object) => {
            if let Some(name) = object
                .get("$ref")
                .and_then(Value::as_str)
                .and_then(|reference| reference.strip_prefix("#/$defs/"))
            {
                found.push(name.to_owned());
            }
            object.values().for_each(|value| refs(value, found));
        }
        Value::Array(items) => items.iter().for_each(|value| refs(value, found)),
        _ => {}
    }
}