Skip to main content

typst_laravel/
lib.rs

1//! Typst for Laravel Rust: PDFs and images rendered in-process, without Chrome.
2//!
3//! Templates are [Typst](https://typst.app) files in `resources/pdf`. Each one reads the data it
4//! is rendered with from `data.cbor`:
5//!
6//! ```typst
7//! #let invoice = cbor("data.cbor")
8//!
9//! Invoice #invoice.number
10//! ```
11//!
12//! Register [`TypstServiceProvider`], then inject [`Typst`] and return what it renders:
13//!
14//! ```no_run
15//! use laravel::container::Inject;
16//! use typst_laravel::{Pdf, Typst};
17//!
18//! async fn show(typst: Inject<Typst>) -> laravel::Result<Pdf> {
19//!     typst.pdf("invoice", &serde_json::json!({ "number": "INV-7" })).await
20//! }
21//! ```
22
23#![warn(missing_docs)]
24
25mod factur_x;
26mod templates;
27mod world;
28
29use std::fmt;
30use std::path::PathBuf;
31use std::sync::{Arc, Mutex, PoisonError};
32
33use ciborium::Value as Cbor;
34use laravel::container::Registrar;
35use laravel::foundation::ServiceProvider;
36use laravel::http::{IntoResponse, Response, header};
37use serde::Serialize;
38use serde_json::Value as Json;
39
40use crate::factur_x::Invoice;
41use crate::world::{Engine, Format};
42
43/// Registers [`Typst`] for the templates in `resources/pdf`, and the `typst:template` command.
44#[derive(Debug)]
45pub struct TypstServiceProvider;
46
47impl ServiceProvider for TypstServiceProvider {
48    fn register(&self, app: &mut Registrar) {
49        app.singleton(async |app| Ok(Typst::new(app.config().app.resource_path("pdf"))));
50        app.discover(env!("CARGO_CRATE_NAME"));
51    }
52}
53
54/// Renders Typst templates.
55pub struct Typst(Mode);
56
57enum Mode {
58    Live(Arc<Engine>),
59    Fake(Mutex<Vec<(String, Json)>>),
60}
61
62impl Typst {
63    /// Creates a renderer for the templates and fonts in `root`.
64    pub fn new(root: impl Into<PathBuf>) -> Self {
65        Self(Mode::Live(Arc::new(Engine::new(root.into()))))
66    }
67
68    /// Creates a renderer for tests, which records what it is asked to render and returns no bytes.
69    #[must_use]
70    pub fn fake() -> Self {
71        Self(Mode::Fake(Mutex::default()))
72    }
73
74    /// Renders `template` to a PDF, with `data` as its `data.cbor`.
75    ///
76    /// Dots in the name are directories, so `invoices.show` is `invoices/show.typ`.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error when `data` can't be serialized, or when the template fails to compile. A
81    /// compile error lists each failure as `file:line:column: message`.
82    pub async fn pdf(&self, template: &str, data: &impl Serialize) -> laravel::Result<Pdf> {
83        self.render(template, data, Format::Pdf).await.map(Pdf)
84    }
85
86    /// Renders `template` to a PDF/A-3b: the archival standard, which may carry attachments such
87    /// as the XML of an electronic invoice.
88    ///
89    /// # Errors
90    ///
91    /// Returns an error as [`pdf`](Self::pdf) does, or when the document breaks the standard.
92    pub async fn archival(&self, template: &str, data: &impl Serialize) -> laravel::Result<Pdf> {
93        self.render(template, data, Format::Archival).await.map(Pdf)
94    }
95
96    /// Renders `template` to a Factur-X (`ZUGFeRD`) invoice: a PDF/A-3b that carries `xml`, the same
97    /// invoice as EN 16931 XML, and names its profile in the metadata.
98    ///
99    /// The template needs no change. The profile is read from the XML.
100    ///
101    /// # Errors
102    ///
103    /// Returns an error as [`archival`](Self::archival) does, or when `xml` names no Factur-X 1.0 profile.
104    pub async fn factur_x(&self, template: &str, data: &impl Serialize, xml: &str) -> laravel::Result<Pdf> {
105        self.render(template, data, Format::Invoice(Invoice::new(xml)?))
106            .await
107            .map(Pdf)
108    }
109
110    /// Renders the first page of `template` to a PNG, at two pixels per point.
111    ///
112    /// # Errors
113    ///
114    /// Returns an error as [`pdf`](Self::pdf) does.
115    pub async fn png(&self, template: &str, data: &impl Serialize) -> laravel::Result<Png> {
116        self.render(template, data, Format::Png).await.map(Png)
117    }
118
119    /// Asserts that a [`fake`](Self::fake) rendered `template` with data that `matches`.
120    ///
121    /// # Panics
122    ///
123    /// Panics when it didn't, or when the renderer is not a fake.
124    pub fn assert_rendered(&self, template: &str, matches: impl Fn(&Json) -> bool) {
125        let Mode::Fake(rendered) = &self.0 else {
126            panic!("Typst is not faked");
127        };
128        let rendered = rendered.lock().unwrap_or_else(PoisonError::into_inner);
129
130        assert!(
131            rendered.iter().any(|(name, data)| name == template && matches(data)),
132            "`{template}` was not rendered with matching data, only {rendered:?}",
133        );
134    }
135
136    async fn render(&self, template: &str, data: &impl Serialize, format: Format) -> laravel::Result<Vec<u8>> {
137        let data = serde_json::to_value(data)?;
138        let engine = match &self.0 {
139            Mode::Live(engine) => Arc::clone(engine),
140            Mode::Fake(rendered) => {
141                rendered
142                    .lock()
143                    .unwrap_or_else(PoisonError::into_inner)
144                    .push((template.to_owned(), data));
145                return Ok(Vec::new());
146            }
147        };
148        let main = format!("{}.typ", template.replace('.', "/"));
149        let now = laravel::now();
150        let mut encoded = Vec::new();
151        ciborium::into_writer(&cbor(data), &mut encoded)?;
152
153        laravel::task::spawn_blocking(move || engine.render(&main, encoded, &now, &format)).await?
154    }
155}
156
157impl fmt::Debug for Typst {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.debug_struct("Typst").finish_non_exhaustive()
160    }
161}
162
163/// Laravel turns on `serde_json`'s `arbitrary_precision`, under which only `serde_json` itself reads
164/// a JSON number as a number: Typst's `json()`, and CBOR written straight from the data, see a map.
165fn cbor(json: Json) -> Cbor {
166    match json {
167        Json::Null => Cbor::Null,
168        Json::Bool(flag) => Cbor::Bool(flag),
169        Json::Number(number) => number
170            .as_i64()
171            .map(Cbor::from)
172            .or_else(|| number.as_f64().map(Cbor::from))
173            .unwrap_or_else(|| Cbor::Text(number.to_string())),
174        Json::String(text) => Cbor::Text(text),
175        Json::Array(items) => Cbor::Array(items.into_iter().map(cbor).collect()),
176        Json::Object(fields) => Cbor::Map(
177            fields
178                .into_iter()
179                .map(|(key, value)| (Cbor::Text(key), cbor(value)))
180                .collect(),
181        ),
182    }
183}
184
185/// A rendered PDF and its bytes. Returned from a handler, it opens in the browser.
186#[derive(Clone, Debug)]
187pub struct Pdf(pub Vec<u8>);
188
189impl IntoResponse for Pdf {
190    fn into_response(self) -> Response {
191        ([(header::CONTENT_TYPE, "application/pdf")], self.0).into_response()
192    }
193}
194
195/// A rendered PNG and its bytes, which a handler may return as they are.
196#[derive(Clone, Debug)]
197pub struct Png(pub Vec<u8>);
198
199impl IntoResponse for Png {
200    fn into_response(self) -> Response {
201        ([(header::CONTENT_TYPE, "image/png")], self.0).into_response()
202    }
203}