# `Typsty`
[🔗](https://github.com/akoutmos/typsty/blob/0.1.0/lib/typsty.ex#L1)

Render [Typst](https://typst.app) documents to PDF, PNG and SVG, with Elixir data passed
to the template as Typst values, in its `assigns` dictionary.

## Document modules

A document module does `use Typsty` and either defines `render/1` with the `~TYPST` sigil:

```elixir
defmodule MyApp.Invoice do
  use Typsty

  def render(assigns) do
    ~TYPST"""
    #set page(paper: "us-letter")

    = Invoice #assigns.number

    #table(
      columns: (1fr, auto),
      [*Item*], [*Price*],
      ..assigns.items.map(item => (item.name, [\$#item.price])).flatten(),
    )
    """
  end
end
```

or leaves `render/1` out and puts the template in a `.typ` file next to the module, with
the same base name (`invoice.ex` and `invoice.typ`), like LiveView's colocated templates.

Render it with the generated functions:

```elixir
assigns = %{number: 1042, items: [%{name: "Widget", price: 25}]}

{:ok, pdf} = MyApp.Invoice.to_pdf(assigns)
{:ok, [page_1 | _]} = MyApp.Invoice.to_png(assigns, ppi: 300)
{:ok, pages} = MyApp.Invoice.to_svg(assigns)
```

`to_pdf/2`, `to_png/2` and `to_svg/2` return `{:error, Typsty.RenderError.t()}` when the
document fails to render, and their bang variants (`to_pdf!/2` and so on) raise it. They
take the options described in [Options](#module-options).

Templates are checked when the module compiles: a syntax error in a `~TYPST` sigil or a
`.typ` template fails the build with a `Typsty.SyntaxError` that points at the line in
your file. Run `mix format` with `Typsty.Formatter` to format them with
[typstyle](https://github.com/typstyle-rs/typstyle).

## Assigns

The template reads the assigns from a dictionary named `assigns`, like a LiveView's
`@number` is `assigns.number`: `assigns.number` and `assigns.items` above. That keeps what
comes from Elixir apart from what the template defines, and never shadows anything in
Typst. Typst gets the data itself, not code generated from it, so nothing needs escaping,
and the template can loop over lists, read fields and do arithmetic:

| Elixir                                    | Typst                                  |
| ----------------------------------------- | -------------------------------------- |
| `nil`, `true`, `false`                    | `none`, `true`, `false`                |
| integers and floats                       | `int` (64-bit) and `float`             |
| strings                                   | `str`                                  |
| atoms                                     | `str` (`:paid` becomes `"paid"`)       |
| lists and tuples                          | `array`                                |
| maps                                      | `dictionary`, with string keys         |
| `Date`, `Time`, `NaiveDateTime`, `DateTime` | `datetime` (`DateTime` keeps its wall time) |
| `Decimal`                                 | `decimal`                              |
| `MapSet`, `Range`, `Date.Range`           | `array`                                |
| other structs                             | see `Typsty.Encoder`                   |

The assigns are a map with atom or string keys, and the keys of maps inside the data can be
atoms, strings or integers. A template reads keys that aren't identifiers with `at`
(`assigns.at("invoice number")`), and assigns that may be missing with a default:

```typst
#let subtitle = assigns.at("subtitle", default: none)
```

A few things to know about the conversion:

- Dictionaries are sorted by key, since Elixir maps have no order. The keys are strings, so
  integer keys sort as text (`"10"` before `"2"`).
- Keyword lists are lists of tuples, so they become arrays of `(key, value)` pairs; pass
  maps for dictionaries. Charlists are lists of integers too.
- A `Date.Range` becomes an array of the dates it steps through, so a template shows a
  range of days with `.first()` and `.last()`.
- A `MapSet` becomes a sorted array: dates, times and decimals in order of their values,
  anything else in Erlang's term order.
- Typst's datetimes have no fractions of a second or time zones: times are truncated to
  the second, and a `DateTime` keeps its wall time (convert it to the time zone the
  document should show first).
- Typst's decimals have 28 significant digits, at most 28 of them after the decimal point.
- Links can only go to http, https, mailto and tel URLs, or relative ones: a link to
  another kind of URL, such as a `javascript:` URL that came from a user, is left out of
  PDFs and SVGs, with a warning.
- `datetime.today()` is the date in UTC: pass the date in the user's time zone as an
  assign instead.

A template that uses a few assigns a lot can give them short names, by destructuring
them at its top. The names are then the template's own, so pick ones that don't hide
anything it uses from Typst, such as `title` or `page`:

```typst
#let (customer, items) = assigns

= Invoice for #customer.name
```

`assigns` is bound at the top of the template, like a `let` binding, so it's only visible
in the template itself. Pass the files it imports, such as components (see
`Typsty.Component`), the values they
need as arguments, which keeps them independent of where their data comes from:

```typst
#import "components/tables.typ": line-items
#line-items(assigns.items)
```

(Imported files other than components can also read the assigns from
`sys.inputs.assigns`.)

`render/1` gets the assigns before the template does, so it can compute values for it:

```elixir
def render(assigns) do
  assigns = Map.put(assigns, :total, Enum.sum_by(assigns.items, & &1.price))

  ~TYPST"""
  Total: #assigns.total
  """
end
```

## Components

Reusable parts of documents, such as tables, letterheads, headers and footers, are
components: Typst functions in modules that `use Typsty.Component`, which documents list
and import:

```elixir
defmodule MyApp.Invoice do
  use Typsty, components: [MyApp.Documents.Letterhead, MyApp.Documents.Tables]

  def render(assigns) do
    ~TYPST"""
    #import "components/letterhead.typ": letterhead
    #import "components/tables.typ": line-items
    #show: letterhead.with(title: [Invoice #assigns.number])

    #line-items(assigns.items)
    """
  end
end
```

See `Typsty.Component`.

## Files

Files the document reads, such as images, data files and other `.typ` files, are passed
with the `:files` option, as binaries. They're never written to disk:

```elixir
MyApp.Invoice.to_pdf(assigns, files: %{"logo.png" => logo_png, "styles.typ" => styles})
```

```typst
#import "styles.typ": heading-style
#image("logo.png", width: 4cm)
```

Paths are relative to the project root (`"logo.png"` and `"/logo.png"` are the same file),
`main.typ` is the template itself, and `components/` is reserved for components: `:files`
can't have files there, and it isn't read from `:root`. To also read files from a
directory, set `:root`; files given with `:files` take precedence.
Without `:root`, the document can only read the files it's given. Files read from `:root`
may be at most 512 MiB.

Typst keeps every file path it sees for the life of the VM, and has room for 65,535 of
them. Use stable names, like `logo.png` or `photos/1.jpg`, rather than a unique name per
render: a template that builds paths from data (`image("photos/" + assigns.id)`) uses a new
one for every id. Typsty stops a render that reads more than 10,000 different files,
refuses new names in `:files` once 50,000 different ones have been given over the life of
the VM, and stops renders that need a new path once Typst's table is nearly full, which
inside the VM lasts until it restarts. A `Typsty.Pool` replaces a worker whose table is
nearly full.
Typst keeps label names and bibliography keys for the life of the VM too, so make labels
from fixed names, not from data such as ids.

Documents rendered inside the VM can't read PDF files (as images, for example), or SVG
images that contain other SVG images: decoding them can crash the VM. Render them in a
`Typsty.Pool`, which can.

## Options

Rendering takes these options. All of them, except `:files` and `:components`, can also be
set in your application config, as defaults for every render:

```elixir
# config/runtime.exs
config :typsty, font_paths: [Application.app_dir(:my_app, "priv/fonts")], system_fonts: false
```

* `:files` (a map of paths to binaries, or a list of `{path, binary}` tuples) - The files the document reads, such as images, data files and other `.typ` files, as
  binaries, by their path in the project (see [Files](Typsty.html#module-files)). Paths
  in `components/` are reserved for components. Use fixed paths, not ones made from ids:
  the VM accepts at most 50,000 different ones over its life. This option can't be set
  in the config.

* `:components` (list of `t:module/0`) - Components the document imports (see `Typsty.Component`), besides the ones its module
  lists with `use Typsty, components: [...]`. This option can't be set in the config. The default value is `[]`.

* `:root` (`t:Path.t/0` or `nil`) - A directory to read the files that aren't in `:files` from, except `components/`,
  which only has the render's components. Documents can't read outside it, even
  through symbolic links, unless a link is swapped in while a document reads it, so
  don't set it to a directory that others can write to. The default value is `nil`.

* `:font_paths` (list of `t:Path.t/0`) - Directories to load fonts from, searched recursively. Relative paths are relative to
  the current directory when the document renders, which in a release isn't your app's
  directory: use `Application.app_dir/2`, in `config/runtime.exs`. The default value is `[]`.

* `:system_fonts` (`t:boolean/0`) - Whether to use the fonts installed on the system. Turn it off for documents that render
  the same on every machine. The default value is `true`.

* `:embedded_fonts` (`t:boolean/0`) - Whether to use the fonts that come with Typst (Libertinus Serif, New Computer Modern,
  New Computer Modern Math and DejaVu Sans Mono). The default value is `true`.

* `:package_paths` (list of `t:Path.t/0`) - Directories with Typst packages, laid out as `namespace/name/version`, like Typst's
  package cache. A template can import a package from them with
  `#import "@preview/cetz:0.4.2"`. Packages are never downloaded while rendering: fetch
  them ahead of time with `mix typsty.packages.get`. The default value is `[]`.

* `:ppi` (positive number (at most 10000)) - For PNG, the resolution in pixels per inch. The default value is `144`.

* `:pdf_standards` (list of `t:String.t/0`) - For PDF, the standards to conform to: any of `"1.4"`, `"1.5"`, `"1.6"`, `"1.7"`, `"2.0"`, `"a-1b"`, `"a-1a"`, `"a-2b"`, `"a-2u"`, `"a-2a"`, `"a-3b"`, `"a-3u"`, `"a-3a"`, `"a-4"`, `"a-4f"`, `"a-4e"`, `"ua-1"`,
  such as `["a-2b"]` for PDF/A-2b or `["ua-1"]` for PDF/UA-1. PDF/A needs the document's
  date, which is the time of the render unless the template sets it with
  `#set document(date: ...)`. The default value is `[]`.

* `:timeout` (`t:timeout/0`) - How long to wait for the render, in milliseconds (at most `4_294_967_295`), or
  `:infinity`, including the time spent waiting for a free slot (see
  `:max_concurrent_renders`). A render that times out returns an error and is cancelled:
  it stops the next time Typst lays out content, loads a file or a font, or exports a PNG
  or SVG page, which for most documents is within milliseconds. A template doing pure
  computation (a long loop of arithmetic) keeps running until it gets to one of those.
  In a `Typsty.Pool`, a render that times out is stopped right away. The default value is `60000`.

* `:pool` (`t:GenServer.name/0`, `t:pid/0` or `nil`) - The name or pid of a `Typsty.Pool` to render in, instead of rendering inside the VM. The default value is `nil`.

These can only be set in the application config:

* `:max_concurrent_renders` (`t:pos_integer/0`) - How many renders may run inside the VM at once, counting renders that timed out and are
  still being cancelled. A render waits for a free slot, within its timeout. This keeps
  renders that keep timing out from piling up in the background. Defaults to the number
  of dirty CPU schedulers (normally the number of CPU cores). See
  `Typsty.running_renders/0`. Renders in a `Typsty.Pool` are limited by its size instead.

* `:log_warnings` (`t:boolean/0`) - Whether to log Typst's warnings with `Logger.warning/1`. The default value is `true`.

* `:packages` (list of `t:String.t/0`) - The packages `mix typsty.packages.get` fetches when it's run without arguments. The default value is `[]`.

Invalid options, in a call or in the config, raise `ArgumentError`, with a message that
says which option is wrong.

Renders run on threads of their own, outside the BEAM's schedulers, and the process that
asked for the render waits for a message, so a render never holds up a scheduler.

Fonts are scanned once for each combination of `:font_paths`, `:system_fonts` and
`:embedded_fonts` and then cached, so only the first render with given font settings
pays for scanning them. Call `font_families/1` when your application starts to scan them
ahead of time. (A `Typsty.Pool` worker scans its own when it starts.)

## Errors

The functions that render return `{:error, %Typsty.RenderError{}}` when the document can't
be rendered, with a `:reason` that tells Typst's errors apart from timeouts and the like
(see `Typsty.RenderError`). They raise `ArgumentError` for invalid arguments: invalid
options, assigns that aren't a map, or data that can't be passed to Typst (see
[Assigns](#module-assigns)).

## What a template can do

Renders run with large stacks, away from the schedulers, and Typsty protects the VM from
the data a document is rendered with:

- **Assigns** are converted to Typst values, with limits on how deeply they nest and on
  the size of numbers and dates. They're data, never code: a template can't do anything
  with them that it couldn't do with values it wrote itself.
- **Files** (in `:files`, or under `:root`) are checked before Typst decodes them, for the
  files known to crash or hang its decoders: images that claim to be enormous, compressed
  SVGs, XML entities and PNG color profiles that expand without bound, SVGs with content
  far outside their canvas or with turbulence filters that take minutes to draw, deeply
  nested XML, CBOR that declares billions of items, bibliographies whose references cycle
  or nest deeply, PDFs. Typst decodes many formats with many libraries, though, and the
  checks can't promise that every hostile file is caught. **Render documents that read
  files from people you don't trust, such as uploads, in a `Typsty.Pool` with a
  `:memory_limit`.** Only the files a document reads are checked: data a template turns
  into bytes itself (`image(bytes(assigns.svg))`) isn't, so pass such data as a file. An
  SVG can read other files in the project too, by linking them, so don't give documents a
  `:root` that holds other people's files.

A template, though, is code. A template that loops forever is stopped at its timeout only
when it next calls into Typst, and what it does with its data decides how much work it
does: `"x" * assigns.n`, `range(assigns.n)` and `table(columns: assigns.n)` take as much
memory as the number says, and an allocation that fails ends the VM. A value of the wrong
type changes what an operation does, too: `#(item.qty * item.price)` repeats a string
when a user sends one as the quantity.

Rendering inside the VM is the right choice for well validated data: data your
application built, or that came from users through an Ecto changeset that cast its types
and checked its sizes. **Favor a `Typsty.Pool` with a `:memory_limit` for input from
untrusted users that isn't well validated**, such as request parameters passed to a
template as they are, and for templates you don't control: there, such a render only
ends its worker.

## Warnings

Typst's warnings (an unknown font family, for example) are logged with `Logger.warning/1`
and included in the `:stop` telemetry event (see `Typsty.Telemetry`). To stop logging them:

```elixir
config :typsty, log_warnings: false
```

# `assigns`

```elixir
@type assigns() :: map()
```

Assigns for a template: a map with atom or string keys.

# `font_option`

```elixir
@type font_option() ::
  {:font_paths, [Path.t()]}
  | {:system_fonts, boolean()}
  | {:embedded_fonts, boolean()}
```

An option for `font_families/1`: the font options for rendering.

# `format_option`

```elixir
@type format_option() ::
  {:line_length, pos_integer()}
  | {:indent, pos_integer()}
  | {:wrap_text, boolean()}
```

An option for `format/2`.

# `option`

```elixir
@type option() ::
  {:files, %{optional(String.t()) =&gt; binary()} | [{String.t(), binary()}]}
  | {:components, [module()]}
  | {:root, Path.t() | nil}
  | {:font_paths, [Path.t()]}
  | {:system_fonts, boolean()}
  | {:embedded_fonts, boolean()}
  | {:package_paths, [Path.t()]}
  | {:ppi, number()}
  | {:pdf_standards, [String.t()]}
  | {:timeout, timeout()}
  | {:pool, GenServer.name() | pid() | nil}
```

An option for rendering. See [Options](#module-options).

# `template`

```elixir
@type template() :: String.t() | Typsty.Template.t()
```

A template: Typst source, or a template from the `~TYPST` sigil or `render/1`.

# `render`

```elixir
@callback render(assigns :: map()) :: Typsty.Template.t()
```

Returns the template for the given assigns, as a `Typsty.Template` struct. Define it with
the `~TYPST` sigil, or leave it out and put the template in a `.typ` file next to the
module.

# `__using__`
*macro* 

Makes the module a document module. See the module documentation.

## Options

- `:template` - the template file, relative to the module's file. Defaults to the
  module's file name with the `.typ` extension, for the module its file is named after
  (`MyApp.Invoice` in `invoice.ex`, rather than a module nested in it). A module that
  defines `render/1` can't have a template.
- `:components` - the components the template imports (see `Typsty.Component`), as a
  list of modules. They're served at `components/<name>.typ`, with their files at
  `components/<name>/` and the components they list. They're checked when the document
  renders, so a module that isn't a component raises `ArgumentError` then, rather than
  when the document compiles.

## Overriding the generated functions

`to_pdf/2`, `to_png/2` and `to_svg/2` are overridable, to give a module's renders default
options, for example. Override them without default arguments, and call `super/2`; the
versions with one argument and the bang variants call them, so they get the defaults too:

```elixir
def to_pdf(assigns, opts) do
  super(assigns, Keyword.put_new(opts, :files, %{"logo.png" => MyApp.Assets.logo()}))
end
```

# `font_families`

```elixir
@spec font_families([font_option()]) :: [String.t()]
```

Returns the names of the font families available to documents with the given font options
(`:font_paths`, `:system_fonts` and `:embedded_fonts`, with the same defaults as for
rendering).

The fonts are scanned once for each combination of options and cached, so calling this
when your application starts makes the first render faster.

# `format`

```elixir
@spec format(String.t(), [format_option()]) ::
  {:ok, String.t()} | {:error, [Typsty.Diagnostic.t()]}
```

Formats Typst source with [typstyle](https://github.com/typstyle-rs/typstyle). Returns
`{:error, diagnostics}` if the source has syntax errors, since it can't be formatted then.

## Options

* `:line_length` (`t:pos_integer/0`) - The maximum line length. The default value is `98`.

* `:indent` (`t:pos_integer/0`) - The number of spaces to indent by. The default value is `2`.

* `:wrap_text` (`t:boolean/0`) - Whether to wrap long lines of text in markup. The default value is `false`.

# `running_renders`

```elixir
@spec running_renders() :: non_neg_integer()
```

Returns the number of renders running inside the VM, including renders that timed out
and are still being cancelled. Useful in health checks and metrics: it's at most
`:max_concurrent_renders`. Renders in a `Typsty.Pool` aren't counted.

# `sigil_TYPST`
*macro* 

The `~TYPST` sigil for writing Typst templates inline.

Like `~H`, it requires a variable named `assigns` in scope, which the template reads as
its `assigns` dictionary, and it returns a `Typsty.Template` struct. The template's syntax is checked when
it's compiled.

`mix format` formats the template with `Typsty.Formatter`. Use the `noformat` modifier to
leave a template as it is: `~TYPST"""..."""noformat`.

# `to_pdf`

```elixir
@spec to_pdf(template(), assigns(), [option()]) ::
  {:ok, binary()} | {:error, Typsty.RenderError.t()}
```

Renders a template as a PDF.

The template is a `Typsty.Template` (from the `~TYPST` sigil or a module's `render/1`), or
a string of Typst source. The template reads the assigns from its `assigns` dictionary; for
a `Typsty.Template`, they're merged into the assigns it already has.

```elixir
{:ok, pdf} = Typsty.to_pdf("= Hello #assigns.name", %{name: "World"})
```

See [Options](#module-options) for the options.

# `to_pdf!`

```elixir
@spec to_pdf!(template(), assigns(), [option()]) :: binary()
```

Like `to_pdf/3`, but raises `Typsty.RenderError` if rendering fails.

# `to_png`

```elixir
@spec to_png(template(), assigns(), [option()]) ::
  {:ok, [binary()]} | {:error, Typsty.RenderError.t()}
```

Renders each page of a template as a PNG. Takes the same arguments as `to_pdf/3`, and the
`:ppi` option sets the resolution.

# `to_png!`

```elixir
@spec to_png!(template(), assigns(), [option()]) :: [binary()]
```

Like `to_png/3`, but raises `Typsty.RenderError` if rendering fails.

# `to_svg`

```elixir
@spec to_svg(template(), assigns(), [option()]) ::
  {:ok, [binary()]} | {:error, Typsty.RenderError.t()}
```

Renders each page of a template as an SVG. Takes the same arguments as `to_pdf/3`.

# `to_svg!`

```elixir
@spec to_svg!(template(), assigns(), [option()]) :: [binary()]
```

Like `to_svg/3`, but raises `Typsty.RenderError` if rendering fails.

# `typst_version`

```elixir
@spec typst_version() :: String.t()
```

Returns the version of the Typst compiler that Typsty uses, such as `"0.15.1"`.

# `validate`

```elixir
@spec validate(String.t()) :: :ok | {:error, [Typsty.Diagnostic.t()]}
```

Checks the syntax of Typst source. Returns `{:error, diagnostics}` with the syntax errors
if it's invalid.

The `~TYPST` sigil and `.typ` templates are checked when they're compiled; this is for
templates that come from elsewhere, such as a database.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
