nucleusflow 0.0.1

A powerful Rust library for content processing, enabling static site generation, document conversion, and templating.
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! # Template Rendering Module
//!
//! Provides flexible template rendering capabilities with support for various template engines.
//! The module offers a pluggable architecture for template rendering with built-in support
//! for Handlebars templates.
//!
//! ## Features
//!
//! - Pluggable template engine architecture
//! - Built-in Handlebars support with helpers
//! - Template caching and validation
//! - Partial template support
//! - Custom helper registration

use crate::{ProcessingError, Result, TemplateRenderer};
use handlebars::{
    Context, Handlebars, Helper, Output, RenderContext, RenderError,
    RenderErrorReason,
};
use parking_lot::RwLock;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::convert::From;
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Represents a custom template helper with helper name and execution.
pub trait TemplateHelper: Send + Sync {
    /// Executes the helper with the given parameters and context.
    fn execute(
        &self,
        params: &[JsonValue],
        context: &JsonValue,
    ) -> Result<JsonValue>;

    /// Returns the name of the helper for registration.
    fn name(&self) -> &str;
}

/// Provides details for template validation errors.
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// Error details detailing the validation issue
    pub details: String,
    /// Line number where error occurred, if available
    pub line: Option<usize>,
    /// Column number where error occurred, if available
    pub column: Option<usize>,
    /// Template source snippet where error occurred
    pub source: Option<String>,
}

impl From<ValidationError> for ProcessingError {
    fn from(error: ValidationError) -> Self {
        ProcessingError::TemplateProcessing {
            details: error.details,
            template_name: String::new(),
            source: None,
        }
    }
}

/// Renderer for Handlebars templates with caching and custom helpers.
#[derive(Clone)]
pub struct HandlebarsRenderer {
    engine: Arc<RwLock<Handlebars<'static>>>, // Handlebars engine
    template_dir: PathBuf,                    // Directory for templates
    template_cache: Arc<RwLock<HashMap<String, String>>>, // Cache for loaded templates
    helpers: Arc<RwLock<HashMap<String, Box<dyn TemplateHelper>>>>, // Custom registered helpers
    strict_mode: bool, // Flag for strict mode
}

impl std::fmt::Debug for HandlebarsRenderer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HandlebarsRenderer")
            .field("template_dir", &self.template_dir)
            .field("strict_mode", &self.strict_mode)
            .finish()
    }
}

impl HandlebarsRenderer {
    /// Creates a new instance of `HandlebarsRenderer`.
    pub fn new(template_dir: &Path) -> Result<Self> {
        let mut handlebars = Handlebars::new();
        handlebars.set_dev_mode(cfg!(debug_assertions));
        handlebars.register_escape_fn(handlebars::html_escape);

        let mut renderer = Self {
            engine: Arc::new(RwLock::new(handlebars)),
            template_dir: template_dir.to_path_buf(),
            template_cache: Arc::new(RwLock::new(HashMap::new())),
            helpers: Arc::new(RwLock::new(HashMap::new())),
            strict_mode: false,
        };

        renderer =
            renderer.with_helper("uppercase", helpers::UppercaseHelper);
        renderer.load_templates()?;
        Ok(renderer)
    }

    /// Enables or disables strict mode, affecting how missing variables and undefined helpers are handled.
    pub fn with_strict_mode(mut self, strict: bool) -> Self {
        self.strict_mode = strict;
        self.engine.write().set_strict_mode(strict);
        self
    }

    /// Registers a custom helper with the renderer.
    pub fn with_helper<H>(self, name: &str, helper: H) -> Self
    where
        H: TemplateHelper + Clone + 'static,
    {
        _ = self
            .helpers
            .write()
            .insert(name.to_string(), Box::new(helper.clone()));
        self.register_helper(name, helper);
        self
    }

    /// Registers a partial template.
    pub fn with_partial(
        self,
        name: &str,
        template: &str,
    ) -> Result<Self> {
        self.engine
            .write()
            .register_partial(name, template)
            .map_err(|e| ProcessingError::TemplateProcessing {
                details: format!(
                    "Failed to register partial '{}': {}",
                    name, e
                ),
                template_name: name.to_string(),
                source: Some(Box::new(e)),
            })?;
        Ok(self)
    }

    /// Loads templates from the directory, caching and validating them.
    fn load_templates(&self) -> Result<()> {
        let mut engine = self.engine.write();
        let mut cache = self.template_cache.write();

        for entry in
            std::fs::read_dir(&self.template_dir).map_err(|e| {
                ProcessingError::TemplateProcessing {
                    details: format!(
                        "Failed to read template directory: {}",
                        e
                    ),
                    template_name: String::new(),
                    source: Some(Box::new(e)),
                }
            })?
        {
            let entry = entry.map_err(|e| {
                ProcessingError::TemplateProcessing {
                    details: format!(
                        "Failed to read directory entry: {}",
                        e
                    ),
                    template_name: String::new(),
                    source: Some(Box::new(e)),
                }
            })?;
            let path = entry.path();

            if path.is_file()
                && path.extension().and_then(|s| s.to_str())
                    == Some("hbs")
            {
                let template_name = path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .ok_or_else(|| {
                        ProcessingError::TemplateProcessing {
                            details: "Invalid template filename"
                                .to_string(),
                            template_name: path.display().to_string(),
                            source: None,
                        }
                    })?;

                let template_content = std::fs::read_to_string(&path)
                    .map_err(|e| {
                    ProcessingError::TemplateProcessing {
                        details: format!(
                            "Failed to read template file: {}",
                            e
                        ),
                        template_name: path.display().to_string(),
                        source: Some(Box::new(e)),
                    }
                })?;

                self.validate_template(&template_content).map_err(
                    |e| ProcessingError::TemplateProcessing {
                        details: format!(
                            "Template validation failed: {}",
                            e
                        ),
                        template_name: template_name.to_string(),
                        source: None,
                    },
                )?;

                engine
                    .register_template_string(
                        template_name,
                        &template_content,
                    )
                    .map_err(|e| {
                        ProcessingError::TemplateProcessing {
                            details: format!(
                                "Failed to register template: {}",
                                e
                            ),
                            template_name: template_name.to_string(),
                            source: Some(Box::new(e)),
                        }
                    })?;

                _ = cache.insert(
                    template_name.to_string(),
                    template_content,
                );
            }
        }
        Ok(())
    }

    /// Registers a helper function with the Handlebars engine.
    fn register_helper<H>(&self, name: &str, helper: H)
    where
        H: TemplateHelper + 'static,
    {
        let helper_fn = move |h: &Helper,
                              _: &Handlebars,
                              ctx: &Context,
                              _: &mut RenderContext,
                              out: &mut dyn Output|
              -> std::result::Result<
            (),
            RenderError,
        > {
            let params: Vec<JsonValue> =
                h.params().iter().map(|p| p.value().clone()).collect();

            let result =
                helper.execute(&params, ctx.data()).map_err(|e| {
                    RenderError::from(RenderErrorReason::Other(
                        e.to_string(),
                    ))
                })?;
            out.write(&result.to_string())?;
            Ok(())
        };

        self.engine
            .write()
            .register_helper(name, Box::new(helper_fn));
    }

    /// Validates the template syntax to catch errors early.
    fn validate_template(&self, template: &str) -> Result<()> {
        let engine = self.engine.read();
        _ = engine
            .render_template(template, &JsonValue::Null)
            .map_err(|e| ValidationError {
                details: e.to_string(),
                line: e.line_no,
                column: e.column_no,
                source: Some(template.to_string()),
            })?;

        let mut brackets = Vec::new();
        let mut in_tag = false;

        for (i, c) in template.chars().enumerate() {
            match c {
                '{' if in_tag => brackets.push(('{', i)),
                '}' if brackets.pop().is_none() => {
                    return Err(ValidationError {
                        details: "Unmatched closing brace".to_string(),
                        line: None,
                        column: Some(i),
                        source: Some(template.to_string()),
                    }
                    .into());
                }
                '{' => in_tag = true,
                _ => {}
            }
        }

        if !brackets.is_empty() {
            return Err(ValidationError {
                details: "Unmatched opening brace".to_string(),
                line: None,
                column: Some(brackets[0].1),
                source: Some(template.to_string()),
            }
            .into());
        }

        Ok(())
    }

    /// Validates template context variables in strict mode.
    fn validate_context(
        &self,
        template: &str,
        context: &JsonValue,
    ) -> Result<()> {
        let template_content = self
            .template_cache
            .read()
            .get(template)
            .ok_or_else(|| ProcessingError::TemplateProcessing {
                details: format!(
                    "Template '{}' not found in cache",
                    template
                ),
                template_name: template.to_string(),
                source: None,
            })?
            .clone();

        let mut required_vars = Vec::new();
        let mut current_var = String::new();
        let mut in_var = false;

        for c in template_content.chars() {
            match c {
                '{' => {
                    current_var.clear();
                    in_var = true;
                }
                '}' if in_var => {
                    required_vars.push(current_var.clone());
                    in_var = false;
                }
                c if in_var => current_var.push(c),
                _ => {}
            }
        }

        for var in required_vars {
            if context.get(&var).is_none() {
                return Err(ProcessingError::TemplateProcessing {
                    details: format!(
                        "Missing required variable '{}'",
                        var
                    ),
                    template_name: template.to_string(),
                    source: None,
                });
            }
        }

        Ok(())
    }
}

impl TemplateRenderer for HandlebarsRenderer {
    fn render(
        &self,
        template: &str,
        context: &JsonValue,
    ) -> Result<String> {
        if self.strict_mode {
            self.validate_context(template, context)?;
        }

        self.engine.read().render(template, context).map_err(|e| {
            ProcessingError::TemplateProcessing {
                details: format!("Template rendering failed: {}", e),
                template_name: template.to_string(),
                source: Some(Box::new(e)),
            }
        })
    }

    fn validate(
        &self,
        template: &str,
        context: &JsonValue,
    ) -> Result<()> {
        if !self.template_cache.read().contains_key(template) {
            return Err(ProcessingError::TemplateProcessing {
                details: format!("Template '{}' not found", template),
                template_name: template.to_string(),
                source: None,
            });
        }

        if self.strict_mode {
            self.validate_context(template, context)?;
        }

        Ok(())
    }
}

/// Built-in helpers for template processing.
pub mod helpers {
    use super::*;

    /// Helper to convert text to uppercase.
    #[derive(Debug, Clone, Copy)]
    pub struct UppercaseHelper;

    impl TemplateHelper for UppercaseHelper {
        fn execute(
            &self,
            params: &[JsonValue],
            _context: &JsonValue,
        ) -> Result<JsonValue> {
            let text = params
                .first()
                .and_then(|p| p.as_str())
                .ok_or_else(|| ProcessingError::TemplateProcessing {
                    details:
                        "Uppercase helper requires a string parameter"
                            .to_string(),
                    template_name: String::new(),
                    source: None,
                })?;
            Ok(JsonValue::String(text.to_uppercase()))
        }

        fn name(&self) -> &str {
            "uppercase"
        }
    }
}