oxblade 0.2.0

Laravel Blade templates for Rust: Blade's markup and directives with Rust expressions, rendering the same HTML as Laravel. 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
//! Bounded JSON serialization for core and adapter view data.

mod key;

use std::{collections::BTreeMap, fmt};

use serde::ser::{
    self, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
    SerializeTupleStruct, SerializeTupleVariant, Serializer,
};
use serde::{Serialize, ser::Error as _};
use serde_json::{Map, Value};

use crate::{
    error::{Error, ErrorKind},
    library::fault,
    value::MAX_OWNED_DATA_DEPTH,
};

/// Maximum container depth of a prepared view data tree.
pub const MAX_DEPTH: usize = MAX_OWNED_DATA_DEPTH;

fn depth_error() -> Error {
    Error::new(
        ErrorKind::Limit,
        "view JSON data depth limit exceeded",
        None,
    )
}

/// Serializes model data into a bounded JSON tree, optionally recording trusted HTML.
///
/// A model's own serialization code and destruction must be stack-safe. Use a
/// borrowed model when its destruction requires special handling by the caller.
pub fn serialize_model(
    model: &(impl Serialize + ?Sized),
    track_html: bool,
) -> crate::error::Result<Tree> {
    model
        .serialize(TreeSerializer {
            remaining: MAX_DEPTH,
            track_html,
        })
        .map_err(|error| error.0)
}

/// Serializes a plain override with one level reserved for the containing view object.
pub fn serialize_override(value: &(impl Serialize + ?Sized)) -> crate::error::Result<Value> {
    value
        .serialize(TreeSerializer {
            remaining: MAX_DEPTH - 1,
            track_html: false,
        })
        .map(|tree| tree.value)
        .map_err(|error| error.0)
}

#[derive(Debug)]
struct SerializeError(Error);

impl fmt::Display for SerializeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(formatter)
    }
}

impl std::error::Error for SerializeError {}

impl ser::Error for SerializeError {
    fn custom<T: fmt::Display>(message: T) -> Self {
        Self(fault(message.to_string()))
    }
}

impl From<serde_json::Error> for SerializeError {
    fn from(error: serde_json::Error) -> Self {
        Self(fault(error.to_string()))
    }
}

/// Trusted HTML strings indexed by escaped JSON pointer.
pub type Provenance = Vec<(String, String)>;

/// Escapes a single segment of a JSON pointer.
pub fn pointer_segment(key: &str) -> String {
    key.replace('~', "~0").replace('/', "~1")
}

type Result<T> = std::result::Result<T, SerializeError>;

/// JSON data and the trusted HTML produced by the same serialization.
pub struct Tree {
    /// JSON data passed to the view.
    pub value: Value,
    /// Trusted HTML paths and their exact serialized values.
    pub provenance: Provenance,
}

impl Tree {
    fn plain(value: Value) -> Self {
        Self {
            value,
            provenance: Vec::new(),
        }
    }

    fn child(self, segment: &str, provenance: &mut Provenance) -> Value {
        if !self.provenance.is_empty() {
            let segment = pointer_segment(segment);
            provenance.extend(
                self.provenance
                    .into_iter()
                    .map(|(path, html)| (format!("/{segment}{path}"), html)),
            );
        }
        self.value
    }

    fn variant(self, variant: &str) -> Self {
        let mut provenance = Vec::new();
        let value = self.child(variant, &mut provenance);
        Self {
            value: Value::Object(Map::from_iter([(variant.to_owned(), value)])),
            provenance,
        }
    }
}

#[derive(Clone, Copy)]
struct TreeSerializer {
    remaining: usize,
    track_html: bool,
}

impl TreeSerializer {
    fn descend(self, levels: usize) -> Result<Self> {
        let remaining = self
            .remaining
            .checked_sub(levels)
            .ok_or_else(|| SerializeError(depth_error()))?;
        Ok(Self { remaining, ..self })
    }

    fn sequence(self, len: Option<usize>, variant: Option<&'static str>) -> Result<Sequence> {
        Ok(Sequence {
            child: self.descend(1 + usize::from(variant.is_some()))?,
            items: Vec::with_capacity(len.unwrap_or(0)),
            provenance: Vec::new(),
            variant,
        })
    }

    fn object(self, variant: Option<&'static str>) -> Result<Object> {
        Ok(Object {
            child: self.descend(1 + usize::from(variant.is_some()))?,
            values: Map::new(),
            provenance: BTreeMap::new(),
            pending_key: None,
            variant,
        })
    }
}

pub(crate) fn depth_within(value: &Value, remaining: usize) -> bool {
    match value {
        Value::Array(values) => {
            remaining > 0
                && values
                    .iter()
                    .all(|value| depth_within(value, remaining - 1))
        }
        Value::Object(fields) => {
            remaining > 0
                && fields
                    .values()
                    .all(|value| depth_within(value, remaining - 1))
        }
        _ => true,
    }
}

macro_rules! serialize_scalars {
    ($($method:ident($ty:ty)),* $(,)?) => {$(
        fn $method(self, value: $ty) -> Result<Tree> {
            Ok(Tree::plain(serde_json::value::Serializer.$method(value)?))
        }
    )*};
}

impl Serializer for TreeSerializer {
    type Ok = Tree;
    type Error = SerializeError;
    type SerializeSeq = Sequence;
    type SerializeTuple = Sequence;
    type SerializeTupleStruct = Sequence;
    type SerializeTupleVariant = Sequence;
    type SerializeMap = Object;
    type SerializeStruct = Struct;
    type SerializeStructVariant = Object;

    serialize_scalars! {
        serialize_bool(bool), serialize_i8(i8), serialize_i16(i16), serialize_i32(i32),
        serialize_i64(i64), serialize_i128(i128), serialize_u8(u8), serialize_u16(u16),
        serialize_u32(u32), serialize_u64(u64), serialize_u128(u128), serialize_f32(f32),
        serialize_f64(f64), serialize_char(char), serialize_str(&str),
    }

    fn serialize_bytes(self, bytes: &[u8]) -> Result<Tree> {
        self.descend(1)?;
        Ok(Tree::plain(
            serde_json::value::Serializer.serialize_bytes(bytes)?,
        ))
    }

    fn serialize_none(self) -> Result<Tree> {
        self.serialize_unit()
    }

    fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<Tree> {
        value.serialize(self.descend(1)?)
    }

    fn serialize_unit(self) -> Result<Tree> {
        Ok(Tree::plain(Value::Null))
    }

    fn serialize_unit_struct(self, _: &'static str) -> Result<Tree> {
        self.serialize_unit()
    }

    fn serialize_unit_variant(
        self,
        _: &'static str,
        _: u32,
        variant: &'static str,
    ) -> Result<Tree> {
        self.serialize_str(variant)
    }

    fn serialize_newtype_struct<T: Serialize + ?Sized>(
        self,
        name: &'static str,
        value: &T,
    ) -> Result<Tree> {
        let mut tree = value.serialize(self.descend(1)?)?;
        if self.track_html && name == crate::Html::SERDE_NAME {
            let html = tree
                .value
                .as_str()
                .ok_or_else(|| SerializeError::custom("trusted HTML must serialize to a string"))?;
            tree.provenance.push((String::new(), html.to_owned()));
        }
        Ok(tree)
    }

    fn serialize_newtype_variant<T: Serialize + ?Sized>(
        self,
        _: &'static str,
        _: u32,
        variant: &'static str,
        value: &T,
    ) -> Result<Tree> {
        Ok(value.serialize(self.descend(1)?)?.variant(variant))
    }

    fn serialize_seq(self, len: Option<usize>) -> Result<Sequence> {
        self.sequence(len, None)
    }

    fn serialize_tuple(self, len: usize) -> Result<Sequence> {
        self.serialize_seq(Some(len))
    }

    fn serialize_tuple_struct(self, _: &'static str, len: usize) -> Result<Sequence> {
        self.serialize_tuple(len)
    }

    fn serialize_tuple_variant(
        self,
        _: &'static str,
        _: u32,
        variant: &'static str,
        len: usize,
    ) -> Result<Sequence> {
        self.sequence(Some(len), Some(variant))
    }

    fn serialize_map(self, _: Option<usize>) -> Result<Object> {
        self.object(None)
    }

    fn serialize_struct(self, name: &'static str, len: usize) -> Result<Struct> {
        // serde_json represents raw fragments and arbitrary-precision numbers through named structs.
        if matches!(
            name,
            "$serde_json::private::RawValue" | "$serde_json::private::Number"
        ) {
            return Ok(Struct::Json {
                json: serde_json::value::Serializer.serialize_struct(name, len)?,
                context: self,
                written: false,
            });
        }
        self.object(None).map(Struct::Object)
    }

    fn serialize_struct_variant(
        self,
        _: &'static str,
        _: u32,
        variant: &'static str,
        _: usize,
    ) -> Result<Object> {
        self.object(Some(variant))
    }
}

struct Sequence {
    child: TreeSerializer,
    items: Vec<Value>,
    provenance: Provenance,
    variant: Option<&'static str>,
}

impl SerializeSeq for Sequence {
    type Ok = Tree;
    type Error = SerializeError;

    fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
        let tree = value.serialize(self.child)?;
        let value = if tree.provenance.is_empty() {
            tree.value
        } else {
            tree.child(&self.items.len().to_string(), &mut self.provenance)
        };
        self.items.push(value);
        Ok(())
    }

    fn end(self) -> Result<Tree> {
        let tree = Tree {
            value: Value::Array(self.items),
            provenance: self.provenance,
        };
        Ok(match self.variant {
            Some(variant) => tree.variant(variant),
            None => tree,
        })
    }
}

macro_rules! serialize_tuple {
    ($trait:ident, $method:ident) => {
        impl $trait for Sequence {
            type Ok = Tree;
            type Error = SerializeError;

            fn $method<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
                SerializeSeq::serialize_element(self, value)
            }

            fn end(self) -> Result<Tree> {
                SerializeSeq::end(self)
            }
        }
    };
}

serialize_tuple!(SerializeTuple, serialize_element);
serialize_tuple!(SerializeTupleStruct, serialize_field);
serialize_tuple!(SerializeTupleVariant, serialize_field);

struct Object {
    child: TreeSerializer,
    values: Map<String, Value>,
    provenance: BTreeMap<String, Provenance>,
    pending_key: Option<String>,
    variant: Option<&'static str>,
}

impl Object {
    fn insert<T: Serialize + ?Sized>(&mut self, key: String, value: &T) -> Result<()> {
        let mut provenance = Vec::new();
        let value = value.serialize(self.child)?.child(&key, &mut provenance);
        if provenance.is_empty() {
            self.provenance.remove(&key);
        } else {
            self.provenance.insert(key.clone(), provenance);
        }
        self.values.insert(key, value);
        Ok(())
    }

    fn finish(self) -> Tree {
        let tree = Tree {
            value: Value::Object(self.values),
            provenance: self.provenance.into_values().flatten().collect(),
        };
        match self.variant {
            Some(variant) => tree.variant(variant),
            None => tree,
        }
    }
}

impl SerializeMap for Object {
    type Ok = Tree;
    type Error = SerializeError;

    fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<()> {
        self.pending_key = Some(key.serialize(key::KeySerializer(self.child))?);
        Ok(())
    }

    fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
        let key = self
            .pending_key
            .take()
            .ok_or_else(|| SerializeError::custom("map value has no key"))?;
        self.insert(key, value)
    }

    fn end(self) -> Result<Tree> {
        Ok(self.finish())
    }
}

enum Struct {
    Object(Object),
    Json {
        json: <serde_json::value::Serializer as Serializer>::SerializeStruct,
        context: TreeSerializer,
        written: bool,
    },
}

impl SerializeStruct for Struct {
    type Ok = Tree;
    type Error = SerializeError;

    fn serialize_field<T: Serialize + ?Sized>(
        &mut self,
        key: &'static str,
        value: &T,
    ) -> Result<()> {
        match self {
            Self::Object(object) => object.insert(key.to_owned(), value),
            Self::Json {
                json,
                context,
                written,
            } => {
                let field = value.serialize(context.descend(1)?)?;
                json.serialize_field(key, &field.value)?;
                *written = true;
                Ok(())
            }
        }
    }

    fn end(self) -> Result<Tree> {
        match self {
            Self::Object(object) => Ok(object.finish()),
            Self::Json {
                json,
                context,
                written,
            } => {
                if !written {
                    return Err(SerializeError::custom("missing JSON payload"));
                }
                // serde_json parses RawValue with its own recursion limit. Account
                // for this already parsed fragment's depth within the surrounding tree.
                let value = SerializeStruct::end(json)?;
                if !depth_within(&value, context.remaining) {
                    return Err(SerializeError(depth_error()));
                }
                Ok(Tree::plain(value))
            }
        }
    }
}

impl SerializeStructVariant for Object {
    type Ok = Tree;
    type Error = SerializeError;

    fn serialize_field<T: Serialize + ?Sized>(
        &mut self,
        key: &'static str,
        value: &T,
    ) -> Result<()> {
        self.insert(key.to_owned(), value)
    }

    fn end(self) -> Result<Tree> {
        Ok(self.finish())
    }
}