oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! Public configuration and entry points for the template engine.

mod programs;

use std::{cell::Cell, rc::Rc, sync::Arc};

use crate::{
    error::Result,
    eval::{Evaluator, Helper, Services},
    lexer::DirectiveTable,
    loader::Loader,
    render::Renderer,
    translate::Translator,
    value::{MAX_OWNED_DATA_DEPTH, Value, ValueMap, bounded_owned_layers},
};

use crate::render::components::{
    ComponentRegistration, ComponentServices, MethodRegistration, RegisteredComponent,
};

/// Per-render resource limits.
#[derive(Clone, Copy, Debug)]
pub struct Limits {
    /// Maximum nested view renders, including the entry view, and depth cap for built-in traversal.
    pub depth: usize,
    /// Maximum HTML bytes written, including intermediate captures.
    pub output: usize,
    /// Total loop iterations across the render.
    pub iterations: usize,
    /// Maximum items in an expanded collection.
    pub expansion: usize,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            depth: 64,
            output: 8 * 1024 * 1024,
            iterations: 100_000,
            expansion: 100_000,
        }
    }
}

/// Resource counters shared by the renders that make up a response.
#[derive(Clone, Debug)]
pub struct RenderBudget(Rc<BudgetCounters>);

#[derive(Debug)]
struct BudgetCounters {
    limits: Limits,
    output: Cell<usize>,
    iterations: Cell<usize>,
    expansion: Cell<usize>,
    depth: Cell<usize>,
}

impl RenderBudget {
    /// Start a response budget with the supplied limits.
    pub fn new(limits: Limits) -> Self {
        Self(Rc::new(BudgetCounters {
            limits,
            output: Cell::new(limits.output),
            iterations: Cell::new(limits.iterations),
            expansion: Cell::new(limits.expansion),
            depth: Cell::new(0),
        }))
    }

    /// Return the output bytes still available to the response.
    pub fn remaining_output(&self) -> usize {
        self.0.output.get()
    }

    /// Charge bytes produced or buffered outside the core renderer.
    pub fn charge_output(&self, bytes: usize) -> Result<()> {
        consume(&self.0.output, bytes, "render output limit exceeded")
    }

    /// Return the collection entries still available to the response.
    pub fn remaining_expansion(&self) -> usize {
        self.0.expansion.get()
    }

    /// Charge collection entries materialized outside the core renderer.
    pub fn charge_expansion(&self, entries: usize) -> Result<()> {
        consume(
            &self.0.expansion,
            entries,
            "collection expansion limit exceeded",
        )
    }

    pub(crate) fn limits(&self) -> Limits {
        self.0.limits
    }

    pub(crate) fn charge_iteration(&self) -> Result<()> {
        consume(&self.0.iterations, 1, "loop iteration limit exceeded")
    }

    pub(crate) fn enter_view(&self, span: Option<crate::span::Span>) -> Result<ViewDepth> {
        let depth = self.0.depth.get();
        if depth >= self.limits().depth.min(128) {
            return Err(crate::error::Error::new(
                crate::error::ErrorKind::Limit,
                "view render depth limit exceeded",
                span,
            ));
        }
        self.0.depth.set(depth + 1);
        Ok(ViewDepth(self.clone()))
    }

    fn leave_view(&self) {
        self.0.depth.set(self.0.depth.get() - 1);
    }
}

fn consume(counter: &Cell<usize>, amount: usize, message: &'static str) -> Result<()> {
    let remaining = counter
        .get()
        .checked_sub(amount)
        .ok_or_else(|| crate::error::Error::new(crate::error::ErrorKind::Limit, message, None))?;
    counter.set(remaining);
    Ok(())
}

pub(crate) struct ViewDepth(RenderBudget);

impl Drop for ViewDepth {
    fn drop(&mut self) {
        self.0.leave_view();
    }
}

/// Options shared by renders from one environment.
#[derive(Clone, Copy, Debug)]
pub struct Options {
    /// Whether escaped echoes encode existing HTML entities again.
    pub double_encode: bool,
    /// Resource limits.
    pub limits: Limits,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            double_encode: true,
            limits: Limits::default(),
        }
    }
}

/// Request state supplied explicitly by the caller.
#[derive(Clone, Debug)]
pub struct RequestContext<'a> {
    /// An optional response budget shared by render calls and their finalizers.
    pub budget: Option<RenderBudget>,
    /// Current application environment.
    pub environment: String,
    /// Locale used by translations without an explicit locale.
    pub locale: Option<String>,
    /// Session values, including the optional CSRF token at `_token`.
    pub session: ValueMap<'a>,
    /// Previously submitted form fields.
    pub old_input: ValueMap<'a>,
    /// Request context keys.
    pub context: ValueMap<'a>,
    /// Validation errors by bag and field, with a list of messages per field.
    pub errors: ValueMap<'a>,
    /// Current authenticated user, if any.
    pub user: Option<Value<'a>>,
    /// Explicit results of application ability checks.
    pub abilities: indexmap::IndexMap<String, bool>,
}

impl<'a> RequestContext<'a> {
    fn bound_owned_inputs(&self) -> std::borrow::Cow<'_, Self> {
        if self
            .session
            .values()
            .chain(self.old_input.values())
            .chain(self.context.values())
            .chain(self.errors.values())
            .chain(self.user.iter())
            .all(|value| value.owned_depth_within(MAX_OWNED_DATA_DEPTH))
        {
            return std::borrow::Cow::Borrowed(self);
        }
        let bounded = |map: &ValueMap<'a>| {
            map.iter()
                .map(|(key, value)| (key.clone(), value.clone_with_depth_bound()))
                .collect()
        };
        std::borrow::Cow::Owned(Self {
            budget: self.budget.clone(),
            environment: self.environment.clone(),
            locale: self.locale.clone(),
            session: bounded(&self.session),
            old_input: bounded(&self.old_input),
            context: bounded(&self.context),
            errors: bounded(&self.errors),
            user: self.user.as_ref().map(Value::clone_with_depth_bound),
            abilities: self.abilities.clone(),
        })
    }
}

impl Default for RequestContext<'_> {
    fn default() -> Self {
        Self {
            budget: None,
            environment: "production".into(),
            locale: None,
            session: Default::default(),
            old_input: Default::default(),
            context: Default::default(),
            errors: Default::default(),
            user: None,
            abilities: Default::default(),
        }
    }
}

/// An environment with its own view loader, registry and rendering options.
pub struct Environment<L> {
    pub(crate) loader: L,
    programs: programs::Programs,
    pub(crate) options: Options,
    pub(crate) plain_text: bool,
    pub(crate) debug_directives: bool,
    shared_layers: Option<usize>,
    pub(crate) directives: DirectiveTable,
    pub(crate) extensions: crate::extend::Extensions,
    pub(crate) aliases: indexmap::IndexMap<String, String>,
    pub(crate) helpers: Arc<indexmap::IndexMap<String, Helper>>,
    pub(crate) injections: indexmap::IndexMap<String, Helper>,
    pub(crate) components: indexmap::IndexMap<String, RegisteredComponent>,
    pub(crate) component_aliases: indexmap::IndexMap<String, String>,
    pub(crate) anonymous_component_namespaces: indexmap::IndexMap<String, String>,
    pub(crate) component_services: ComponentServices,
    methods: Arc<Vec<MethodRegistration>>,
    pub(crate) clock: Option<crate::eval::Clock>,
    translator: Option<Arc<dyn Translator + Send + Sync>>,
}

impl<L: Loader> Environment<L> {
    /// Starts configuring an environment for the supplied loader.
    pub fn builder(loader: L) -> EnvironmentBuilder<L> {
        EnvironmentBuilder(Self {
            loader,
            programs: Default::default(),
            options: Options::default(),
            plain_text: false,
            debug_directives: false,
            shared_layers: None,
            directives: DirectiveTable::new(),
            extensions: Default::default(),
            aliases: Default::default(),
            helpers: Arc::default(),
            injections: Default::default(),
            components: Default::default(),
            component_aliases: Default::default(),
            anonymous_component_namespaces: Default::default(),
            component_services: Default::default(),
            methods: Arc::default(),
            clock: None,
            translator: None,
        })
    }

    /// Renders a view with one layer of values and default request context.
    pub fn render<'a>(&self, name: &str, data: ValueMap<'a>) -> Result<String> {
        self.render_layers(name, [data], &RequestContext::default(), None)
    }

    /// Renders a view with the fields of a JSON object as its data.
    ///
    /// The data is borrowed, not converted. Anything other than an object is an error, since a view's data
    /// is a set of named values.
    ///
    /// ```
    /// use oxblade::{engine::Environment, loader::MemoryLoader};
    ///
    /// let env = Environment::builder(MemoryLoader::new().view("hello", "Hello, {{ name }}!")).build();
    /// let html = env.render_json("hello", &serde_json::json!({ "name": "<Ada>" })).unwrap();
    /// assert_eq!(html, "Hello, &lt;Ada&gt;!");
    /// ```
    pub fn render_json(&self, name: &str, data: &serde_json::Value) -> Result<String> {
        let Some(fields) = data.as_object() else {
            return Err(crate::error::Error::new(
                crate::error::ErrorKind::Render,
                "view data must be a JSON object",
                None,
            ));
        };
        let data = fields
            .iter()
            .map(|(key, value)| (key.clone(), Value::Json(value)))
            .collect();
        self.render(name, data)
    }

    /// Renders a view with layers in ascending priority and an optional fragment.
    ///
    /// An absent fragment returns the complete rendered view.
    pub fn render_layers<'a>(
        &self,
        name: &str,
        layers: impl IntoIterator<Item = ValueMap<'a>>,
        request: &RequestContext<'a>,
        fragment: Option<&str>,
    ) -> Result<String> {
        self.with_view_layers(name, layers, request, |renderer, layers| {
            renderer.render(name, layers, fragment)
        })
    }

    /// Renders once and concatenates the selected fragments in the supplied order.
    ///
    /// Pass `None` to concatenate all fragments in capture order. An unknown fragment
    /// contributes the complete view, as when selecting one fragment.
    pub fn render_fragments<'a>(
        &self,
        name: &str,
        data: ValueMap<'a>,
        fragments: Option<&[&str]>,
    ) -> Result<String> {
        self.render_fragment_layers(name, [data], &RequestContext::default(), fragments)
    }

    /// Selects multiple fragments when the condition is true, or renders the complete view.
    pub fn render_fragments_if<'a>(
        &self,
        condition: bool,
        name: &str,
        data: ValueMap<'a>,
        fragments: Option<&[&str]>,
    ) -> Result<String> {
        if condition {
            self.render_fragments(name, data, fragments)
        } else {
            self.render(name, data)
        }
    }

    /// Renders multiple fragments with caller-supplied layers and request facts.
    pub fn render_fragment_layers<'a>(
        &self,
        name: &str,
        layers: impl IntoIterator<Item = ValueMap<'a>>,
        request: &RequestContext<'a>,
        fragments: Option<&[&str]>,
    ) -> Result<String> {
        if fragments.is_some_and(<[&str]>::is_empty) {
            drop(bounded_owned_layers(layers));
            return Ok(String::new());
        }
        self.with_view_layers(name, layers, request, |renderer, layers| {
            renderer.render_fragments(name, layers, fragments)
        })
    }

    pub(crate) fn with_view_layers<'a, T>(
        &self,
        name: &str,
        layers: impl IntoIterator<Item = ValueMap<'a>>,
        request: &RequestContext<'a>,
        render: impl FnOnce(Renderer<'_, 'a, L>, &mut dyn Iterator<Item = ValueMap<'a>>) -> Result<T>,
    ) -> Result<T> {
        let mut layers = bounded_owned_layers(layers);
        let request = request.bound_owned_inputs();
        let renderer = Renderer::new(self, &request);
        if !self.methods.is_empty()
            && let Some(view) = crate::shape::view_models().find(|view| view.name == name)
        {
            let mut types = crate::shape::TypeRegistry::default();
            let shape = (view.describe)(&mut types);
            let mut layers: Vec<_> = layers.collect();
            for data in &mut layers {
                crate::render::components::annotate_methods(data, &shape, &types, &self.methods)?;
            }
            return render(renderer, &mut layers.into_iter());
        }
        render(renderer, &mut layers)
    }

    pub(crate) fn evaluator<'a>(
        &self,
        layers: impl IntoIterator<Item = ValueMap<'a>>,
        request: &RequestContext<'a>,
        budget: RenderBudget,
    ) -> Evaluator<'a> {
        let services = Services {
            helpers: Arc::clone(&self.helpers),
            methods: Arc::clone(&self.methods),
            errors: Some(request.errors.clone()),
            user: request.user.clone(),
            session: request.session.clone(),
            old_input: request.old_input.clone(),
            context: request.context.clone(),
            clock: self.clock.clone(),
            translator: self.translator.clone(),
            locale: request.locale.as_deref().map(Arc::from),
        };
        Evaluator::configured(
            layers.into_iter().collect(),
            services,
            budget,
            request.budget.is_some(),
        )
        .retain_shared_layers(self.shared_layers)
    }
}

/// Configures the loader's engine before rendering.
pub struct EnvironmentBuilder<L>(pub(crate) Environment<L>);

impl<L: Loader> EnvironmentBuilder<L> {
    /// Sets rendering options.
    pub fn options(mut self, options: Options) -> Self {
        self.0.options = options;
        self
    }

    /// Enables template diagnostics with `@dump` and `@dd`. Off by default.
    pub fn debug_directives(mut self, enabled: bool) -> Self {
        self.0.debug_directives = enabled;
        self
    }

    /// Keeps the first data layers, plus request facts, visible in isolated views.
    ///
    /// Declare the number of shared layers supplied before view-local data.
    pub fn shared_layers(mut self, count: usize) -> Self {
        self.0.shared_layers = Some(count);
        self
    }

    /// Displays escaped echoes as plain text, for a hand-written text body.
    pub fn plain_text(mut self, enabled: bool) -> Self {
        self.0.plain_text = enabled;
        self
    }

    /// Resolves authentication from zero arguments or a guard name.
    pub fn authentication(self, resolve: Helper) -> Self {
        self.helper("@auth", resolve)
    }

    /// Resolves an ability name and any subject arguments for the authorization directives.
    pub fn authorization(self, resolve: Helper) -> Self {
        self.helper("@can", resolve)
    }

    /// Registers a custom function.
    pub fn helper(mut self, name: impl Into<String>, helper: Helper) -> Self {
        Arc::make_mut(&mut self.0.helpers).insert(name.into(), helper);
        self
    }

    /// Registers a factory for the type named in an `@inject` declaration.
    pub fn service(mut self, ty: impl Into<String>, factory: Helper) -> Self {
        self.0.injections.insert(ty.into(), factory);
        self
    }

    /// Registers one class component by its declared name.
    pub fn component(self, component: ComponentRegistration) -> Self {
        self.components([component])
    }

    /// Registers class components by their declared tag names.
    pub fn components(
        mut self,
        components: impl IntoIterator<Item = ComponentRegistration>,
    ) -> Self {
        self.0.components.extend(
            components
                .into_iter()
                .map(|component| (component.name.into(), RegisteredComponent::new(component))),
        );
        self
    }

    /// Registers class components under a shared tag namespace.
    pub fn component_namespace(
        mut self,
        namespace: &str,
        components: impl IntoIterator<Item = ComponentRegistration>,
    ) -> Self {
        self.0
            .components
            .extend(components.into_iter().map(|component| {
                (
                    format!("{namespace}::{}", component.name),
                    RegisteredComponent::new(component),
                )
            }));
        self
    }

    /// Resolves a component alias to a registered class name or an exact view name.
    pub fn alias_component(
        mut self,
        view_or_class: impl Into<String>,
        alias: impl Into<String>,
    ) -> Self {
        self.0
            .component_aliases
            .insert(alias.into(), view_or_class.into());
        self
    }

    /// Searches an application view directory for tags with a given namespace.
    pub fn anonymous_component_namespace(
        mut self,
        directory: impl Into<String>,
        namespace: impl Into<String>,
    ) -> Self {
        self.0
            .anonymous_component_namespaces
            .insert(namespace.into(), directory.into());
        self
    }

    /// Leaves x-tags as text while still compiling their Blade directives and echoes.
    pub fn without_component_tags(mut self) -> Self {
        self.0.directives.disable_component_tags();
        self
    }

    /// Makes an already-built, cloneable service available to class components.
    pub fn component_service<T: Clone + Send + Sync + 'static>(mut self, service: T) -> Self {
        self.0.component_services.insert(service);
        self
    }

    /// Registers method adapters for typed template values.
    pub fn methods(mut self, methods: impl IntoIterator<Item = MethodRegistration>) -> Self {
        let registered = Arc::make_mut(&mut self.0.methods);
        for method in methods {
            registered.retain(|entry| (entry.type_name)() != (method.type_name)());
            registered.push(method);
        }
        self
    }

    /// Registers an include directive with the specified alias.
    pub fn alias_include(mut self, view: impl Into<String>, alias: &str) -> Self {
        self.clear_inline(alias);
        self.0.directives.register_exact_directive(alias, true);
        self.0.aliases.insert(alias.to_owned(), view.into());
        self
    }

    /// Registers a custom directive backed by a helper of the same name.
    pub fn directive_helper(mut self, name: &str, consumes_newline: bool) -> Self {
        self.clear_inline(name);
        self.0.directives.register_directive(name, consumes_newline);
        self
    }

    /// Registers a custom block condition backed by a boolean helper.
    pub fn condition_helper(mut self, name: &str) -> Self {
        self.0.extensions.conditions.shift_remove(name);
        self.0.extensions.legacy_conditions.insert(name.to_owned());
        self.0.directives.register_condition(name);
        self
    }

    /// Shares a translator across renders. A request can select its own locale.
    ///
    /// An explicitly registered helper with a translation name keeps precedence.
    pub fn translator(mut self, translator: impl Translator + Send + Sync + 'static) -> Self {
        self.0.translator = Some(Arc::new(translator));
        self
    }

    /// Uses an application-supplied clock for date helpers.
    pub fn clock(mut self, clock: crate::eval::Clock) -> Self {
        self.0.clock = Some(clock);
        self
    }

    /// Builds the environment.
    pub fn build(mut self) -> Environment<L> {
        self.install_condition_check();
        self.0
    }
}

impl EnvironmentBuilder<crate::loader::FilesystemLoader> {
    /// Registers a filesystem directory of anonymous components.
    ///
    /// An empty namespace adds an unprefixed search path.
    pub fn anonymous_component_path(
        mut self,
        path: impl Into<std::path::PathBuf>,
        namespace: &str,
    ) -> Self {
        self.0.loader = if namespace.is_empty() {
            self.0.loader.anonymous_path(path)
        } else {
            self.0.loader.namespace(namespace, path)
        };
        self
    }
}