cdoc 1.0.0

A markdown-based document parser and processor
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
407
408
409
410
use anyhow::{anyhow, Context as AnyhowContext};
use rhai::{Dynamic, Engine, Scope};
use std::collections::{BTreeMap, HashMap};
use std::io::{Cursor, Write};

use rhai::serde::to_dynamic;
use std::io;
use std::path::PathBuf;

use tera::{ArgFromValue, Context, Error, FunctionResult, Kwargs, State, Tera, TeraResult, Value};

mod definition;
mod precompiled;

use crate::renderers::RenderedParam;
pub use definition::*;

/// Builds a Tera filter backed by a rhai script. tera 2.0 filters receive the input value and
/// keyword arguments (rather than 1.x's `&serde_json::Value` + `&HashMap`), so we bridge through
/// serde_json to feed the script and to convert its result back into a Tera [`Value`].
fn create_rhai_filter(
    source: String,
) -> impl Fn(&Value, Kwargs, &State) -> TeraResult<Value> + Send + Sync + 'static {
    move |val: &Value, args: Kwargs, _state: &State| -> TeraResult<Value> {
        let eng = Engine::new();
        let mut scope = Scope::new();

        let val_json = serde_json::to_value(val).unwrap_or(serde_json::Value::Null);
        let args_json: serde_json::Value = args.deserialize().unwrap_or(serde_json::Value::Null);
        scope.push_dynamic(
            "val",
            to_dynamic(val_json).map_err(|e| Error::message(e.to_string()))?,
        );
        scope.push_dynamic(
            "args",
            to_dynamic(args_json).map_err(|e| Error::message(e.to_string()))?,
        );

        let res: Dynamic = eng
            .eval_with_scope(&mut scope, &source)
            .map_err(|e| Error::message(e.to_string()))?;
        let json = serde_json::to_value(res).map_err(|e| Error::message(e.to_string()))?;
        // Preserve plain strings verbatim; render anything else as its JSON representation.
        let out = match json {
            serde_json::Value::String(s) => s,
            other => other.to_string(),
        };
        Ok(Value::from(out))
    }
}

/// Builds a Tera function for a shortcode. It renders the shortcode's own template through the
/// captured [`TemplateManager`]. tera 2.0 delivers arguments as [`Kwargs`]; we recover the full
/// (arbitrary) argument set via `deserialize` and forward it into the render context.
fn get_shortcode_tera_fn(
    temp: TemplateManager,
    id: String,
    template_prefix: String,
    type_: TemplateType,
) -> impl Fn(Kwargs, &State) -> TeraResult<String> + Send + Sync + 'static {
    move |args: Kwargs, _state: &State| -> TeraResult<String> {
        let arg_map: BTreeMap<String, serde_json::Value> =
            args.deserialize().map_err(|e| Error::message(e.to_string()))?;

        let mut ctx = Context::new();
        for (k, v) in &arg_map {
            ctx.insert(k.clone(), v);
        }

        let mut buf = Cursor::new(Vec::new());
        match temp.render(&id, &template_prefix, type_.clone(), &ctx, &mut buf) {
            Ok(()) => Ok(String::from_utf8(buf.into_inner()).unwrap()),
            Err(e) => {
                let mut ebuf = Vec::new();
                err_format(e, &mut ebuf).map_err(|er| Error::message(er.to_string()))?;
                Ok(String::from_utf8(ebuf).unwrap())
            }
        }
    }
}

fn err_format(e: anyhow::Error, mut f: impl Write) -> io::Result<()> {
    write!(f, "Error {:?}", e)?;
    e.chain()
        .skip(1)
        .try_for_each(|cause| write!(f, " caused by: {}", cause))?;
    Ok(())
}

/// Provides a common Api for the three layout types and output formats.
#[derive(Clone)]
pub struct TemplateManager {
    path: PathBuf,
    pub tera: Tera,
    pub definitions: HashMap<String, TemplateDefinition>,
    filter_path: PathBuf,
}

impl TemplateManager {
    /// Create new template manager from template path. Reads the template files.
    pub fn from_path(
        template_path: PathBuf,
        filter_path: PathBuf,
        create_filters: bool,
    ) -> anyhow::Result<Self> {
        TemplateManager::new(
            load_template_definitions(template_path.clone())?,
            template_path,
            filter_path,
            create_filters,
        )
    }

    fn new(
        definitions: HashMap<String, TemplateDefinition>,
        dir: PathBuf,
        filter_path: PathBuf,
        create_filters: bool,
    ) -> anyhow::Result<Self> {
        let defs = get_templates_from_definitions(&definitions, dir.clone());
        // tera 2.0 splits construction from glob loading.
        let mut tera = Tera::new();

        // tera 2.0 validates function/filter references when templates are *compiled* (1.x
        // resolved them lazily at render time). Register the helpers that shipped templates
        // reference before loading, so compilation succeeds:
        //  - `render`: a placeholder; the build pipeline installs the real implementation, which
        //    is looked up by name at render time.
        //  - `json_encode`: a 1.x built-in filter that was removed in 2.0.
        tera.register_function(
            "render",
            |_args: Kwargs, _state: &State| -> TeraResult<Value> { Ok(Value::from("")) },
        );
        tera.register_filter(
            "json_encode",
            |val: &Value, _args: Kwargs, _state: &State| -> TeraResult<Value> {
                Ok(Value::from(serde_json::to_string(val).unwrap_or_default()))
            },
        );
        // `embed` is provided by the build pipeline (it inlines images as base64); register a
        // pass-through placeholder so templates that reference it still compile standalone.
        tera.register_filter(
            "embed",
            |val: &Value, _args: Kwargs, _state: &State| -> TeraResult<Value> { Ok(val.clone()) },
        );

        tera.load_from_glob(&format!("{}/sources/**.html", dir.to_str().unwrap()))?;
        let filters = get_filters_from_files(filter_path.clone())?;

        filters.into_iter().for_each(|(name, source)| {
            tera.register_filter(name, create_rhai_filter(source));
        });

        tera.add_raw_templates(defs)?;

        let temp = TemplateManager {
            path: dir,
            tera,
            definitions,
            filter_path,
        };

        Ok(if create_filters {
            temp.register_shortcode_fns()?
        } else {
            temp
        })
    }

    #[allow(unused)]
    fn combine(mut self, other: TemplateManager) -> anyhow::Result<TemplateManager> {
        // tera 2.0 renamed `extend` to `register_from` (and it no longer returns a Result).
        self.tera.register_from(&other.tera);
        self.definitions.extend(other.definitions);

        Ok(self)
    }

    fn register_shortcode_fns(mut self) -> anyhow::Result<Self> {
        self.clone()
            .definitions
            .into_iter()
            .try_for_each(|(tp_name, def)| {
                let (_, id) = tp_name.split_once('_').unwrap();
                let type_ = &def.type_;
                for template_prefix in def.templates.keys() {
                    let f = get_shortcode_tera_fn(
                        self.clone(),
                        id.to_string(),
                        template_prefix.clone(),
                        type_.clone(),
                    );
                    let name = format!("shortcode_{template_prefix}_{id}");
                    self.tera.register_function(name, f);
                }
                Ok::<(), anyhow::Error>(())
            })?;
        Ok(self)
    }

    /// Reload all files and definitions
    pub fn reload(&mut self) -> anyhow::Result<()> {
        let defs = load_template_definitions(self.path.clone())?;
        let tps = get_templates_from_definitions(&defs, self.path.clone());
        self.tera.full_reload()?;
        self.tera.add_raw_templates(tps)?;
        let filters = get_filters_from_files(self.filter_path.clone())?;

        filters.into_iter().for_each(|(name, source)| {
            self.tera.register_filter(name, create_rhai_filter(source));
        });

        self.definitions = defs;
        Ok(())
    }

    /// Register a Tera filter. The bounds mirror tera 2.0's [`Tera::register_filter`].
    pub fn register_filter<Func, Arg, Res>(&mut self, name: &str, filter: Func)
    where
        Func: tera::Filter<Arg, Res> + for<'a> tera::Filter<<Arg as ArgFromValue<'a>>::Output, Res>,
        Arg: for<'a> ArgFromValue<'a>,
        Res: FunctionResult,
    {
        self.tera.register_filter(name.to_string(), filter)
    }

    /// Fetch a [TemplateDefinition] by specifying its id and type.
    pub fn get_template(
        &self,
        id: &str,
        type_: TemplateType,
    ) -> anyhow::Result<TemplateDefinition> {
        let tp = self
            .definitions
            .get(&format!("{type_}_{id}"))
            .ok_or(anyhow!(
                "Template definition with id '{}' and type '{}' doesn't exist.",
                id,
                type_
            ))?;
        Ok(tp.clone())
    }

    /// Render a template to a specified format
    ///
    /// # Arguments
    ///
    /// * `id` - The template identifier (the name of the definition file)
    /// * `template_prefix` - The template format key (which output format to use)
    /// * `type_` - The kind of template to render (builtin/layout/shortcode). Ensures that
    ///     different types can have templates with the same id.
    /// * `args` - Template arguments contained in a Tera context.
    /// * `buf` - Buffer to write the output to.
    pub fn render(
        &self,
        id: &str,
        template_prefix: &str,
        type_: TemplateType,
        args: &Context,
        buf: impl Write,
    ) -> anyhow::Result<()> {
        let tp = self.get_template(id, type_)?;
        let format_str = template_prefix;
        let format = tp.get_format(format_str).context(format!(
            "template with id '{id}' does not support format '{format_str}"
        ))?;
        // NOTE: tera 1.x allowed a per-template rhai `script` to mutate the render context by
        // round-tripping it through `Context::into_json`. tera 2.0's `Context` is neither
        // serializable nor iterable, so that bridge can't be reconstructed. No shipped template
        // uses the `script` field, so it is currently ignored (see CHANGELOG known limitations).
        match format {
            TemplateSource::Precompiled(tp, fm) => {
                tp.render(fm, args, buf)?;
            }
            TemplateSource::Derive(from) => {
                let format = tp.get_format(from).context(format!(
                    "template with id '{id}' does not support format '{format_str}"
                ))?;
                if let TemplateSource::Precompiled(tp, fm) = format {
                    tp.render(fm, args, buf)?;
                } else {
                    let type_ = &tp.type_;

                    let template_name = format!("{type_}_{id}.{format_str}");

                    self.tera.render_to(&template_name, args, buf)?;
                }
            }
            _ => {
                let type_ = &tp.type_;

                let template_name = format!("{type_}_{id}.{format_str}");

                self.tera.render_to(&template_name, args, buf)?;
            }
        }

        Ok(())
    }

    /// Performs argument validation for shortcodes.
    pub fn validate_args_for_template(
        &self,
        id: &str,
        args: &[RenderedParam],
    ) -> anyhow::Result<Vec<anyhow::Result<()>>> {
        let tp = self
            .get_template(id, TemplateType::Shortcode)
            .context(format!("Invalid shortcode identifier '{}'", id))?;
        tp.validate_args(args)
    }

    // pub fn shortcode_call_resolve_positionals(&self, call: Reference) -> anyhow::Result<Reference> {
    //     Ok(
    //         if let Reference::Command {
    //             function,
    //             parameters,
    //         } = call
    //         {
    //             let tp = self.get_template(&function, TemplateType::Shortcode)?;
    //             let params = tp.shortcode.unwrap().parameters;
    //
    //             let args = parameters
    //                 .into_iter()
    //                 .enumerate()
    //                 .map(|(i, a)| {
    //                     let k = a.key.unwrap_or_else(|| params.get(i).unwrap().name.clone());
    //                     Parameter {
    //                         key: Some(k),
    //                         value: a.value,
    //                         pos: a.pos,
    //                     }
    //                 })
    //                 .collect();
    //
    //             Reference::Command {
    //                 function,
    //                 parameters: args,
    //             }
    //         } else {
    //             call
    //         },
    //     )
    // }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;
    use std::path::PathBuf;
    use tera::Context;

    fn embedded_templates() -> TemplateManager {
        let base = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/config/templates");
        let filters = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/config/filters");
        TemplateManager::from_path(base, filters, false).expect("load embedded templates")
    }

    /// The canonical template set must load, and its definitions (builtins + shortcodes) must be
    /// registered — this is what every project relies on.
    #[test]
    fn loads_embedded_template_definitions() {
        let tm = embedded_templates();
        // A builtin and a shortcode that ship with the tool.
        assert!(tm.get_template("header", TemplateType::Builtin).is_ok());
        assert!(tm.get_template("message", TemplateType::Shortcode).is_ok());
    }

    /// Rendering a shortcode is a core authoring feature; this exercises the shortcode template
    /// path end to end (argument context → rendered HTML).
    #[test]
    fn renders_message_shortcode() {
        let tm = embedded_templates();

        let mut ctx = Context::new();
        ctx.insert("color", "info");
        ctx.insert("title", "Heads up");
        ctx.insert("body", "Body text here");

        let mut buf = Cursor::new(Vec::new());
        tm.render("message", "html", TemplateType::Shortcode, &ctx, &mut buf)
            .expect("render message shortcode");
        let out = String::from_utf8(buf.into_inner()).unwrap();

        assert!(
            out.contains(r#"class="message is-info""#),
            "missing color class:\n{out}"
        );
        assert!(out.contains("Heads up"), "missing title:\n{out}");
        assert!(out.contains("Body text here"), "missing body:\n{out}");
    }

    /// When the optional title is omitted, the template falls back to the capitalized color.
    #[test]
    fn message_shortcode_title_defaults_to_color() {
        let tm = embedded_templates();

        let mut ctx = Context::new();
        ctx.insert("color", "warning");
        ctx.insert("body", "No title here");

        let mut buf = Cursor::new(Vec::new());
        tm.render("message", "html", TemplateType::Shortcode, &ctx, &mut buf)
            .expect("render message shortcode");
        let out = String::from_utf8(buf.into_inner()).unwrap();

        assert!(out.contains("Warning"), "expected capitalized color fallback:\n{out}");
    }
}