typst-rails 0.1.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +191 -1
- data/README.md +347 -33
- data/lib/typst-rails.rb +7 -0
- data/lib/typst_rails/backends/base.rb +24 -1
- data/lib/typst_rails/backends/cli.rb +47 -12
- data/lib/typst_rails/backends/gem.rb +19 -2
- data/lib/typst_rails/data_serializer.rb +294 -0
- data/lib/typst_rails/diagnostics.rb +284 -0
- data/lib/typst_rails/erb_source.rb +36 -0
- data/lib/typst_rails/errors.rb +139 -0
- data/lib/typst_rails/framework_detection.rb +13 -4
- data/lib/typst_rails/handler.rb +51 -9
- data/lib/typst_rails/helpers.rb +26 -112
- data/lib/typst_rails/markdown_converter.rb +248 -0
- data/lib/typst_rails/rage_integration.rb +55 -8
- data/lib/typst_rails/rails_rendering.rb +58 -0
- data/lib/typst_rails/railtie.rb +7 -0
- data/lib/typst_rails/renderer.rb +223 -107
- data/lib/typst_rails/sinatra_integration.rb +11 -12
- data/lib/typst_rails/template_rendering.rb +252 -0
- data/lib/typst_rails/version.rb +1 -1
- data/lib/typst_rails/view_helpers.rb +28 -0
- data/lib/typst_rails.rb +140 -5
- metadata +12 -3
data/README.md
CHANGED
|
@@ -47,7 +47,6 @@ end
|
|
|
47
47
|
|
|
48
48
|
```typst
|
|
49
49
|
<%# app/views/reports/monthly.typ %>
|
|
50
|
-
<% data = { title: @title, author: @author } %>
|
|
51
50
|
#let data = json("typst_data.json")
|
|
52
51
|
|
|
53
52
|
= #data.title
|
|
@@ -57,9 +56,82 @@ Author: #data.author
|
|
|
57
56
|
Generated on <%= Time.now.strftime("%Y-%m-%d") %>
|
|
58
57
|
```
|
|
59
58
|
|
|
59
|
+
Data reaches the template two ways. ERB runs first, in the view context, so
|
|
60
|
+
instance variables and helpers work as in any view; note that `<%= %>` output
|
|
61
|
+
is not escaped. The controller's instance variables and locals are also
|
|
62
|
+
serialized to `typst_data.json`, which Typst reads with `json()`. That file is
|
|
63
|
+
written only when the template source mentions `typst_data.json`.
|
|
64
|
+
|
|
65
|
+
Only values with a faithful JSON form are written. Strings, numbers, booleans,
|
|
66
|
+
nil, Hashes, Arrays and Sets pass through, converted recursively; Symbols
|
|
67
|
+
become strings; Dates and Times (including `ActiveSupport::TimeWithZone`)
|
|
68
|
+
become ISO 8601 strings without fractional seconds; and BigDecimals become
|
|
69
|
+
decimal strings such as `"19.99"`, so no precision is lost (use
|
|
70
|
+
`decimal(data.total)` in Typst to do arithmetic with them). Hash keys must be
|
|
71
|
+
Strings, Symbols or numbers. Other objects are converted with `as_json` when
|
|
72
|
+
their class defines one, as ActiveRecord models and relations do, or with
|
|
73
|
+
`to_h`, as Structs and `Data` classes do. The generic `as_json` ActiveSupport
|
|
74
|
+
adds to every object does not count, since it writes the object's instance
|
|
75
|
+
variables. NaN, Infinity, and anything else, such as a Proc or a `Money`
|
|
76
|
+
object, are rejected.
|
|
77
|
+
|
|
78
|
+
A rejected local raises `TypstRails::SerializationError`, a
|
|
79
|
+
`TypstRails::Error`, naming where the value sits:
|
|
80
|
+
|
|
81
|
+
```text
|
|
82
|
+
locals.line_items[0].amount is a Money, which is not JSON-serializable. Convert it ...
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Controllers often hold instance variables the template never uses, so a
|
|
86
|
+
rejected instance variable is left out of `typst_data.json` instead, with one
|
|
87
|
+
warning per render in the Rails log listing each one and why. Instance
|
|
88
|
+
variables whose names begin with an underscore are skipped silently. To give
|
|
89
|
+
the template such a value, convert it and pass it as a local:
|
|
90
|
+
|
|
91
|
+
```ruby
|
|
92
|
+
render template: "invoices/show", locals: { total: @invoice.total.to_s }
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
The `TypstRails::Helpers` methods, such as `escape_typst` and
|
|
96
|
+
`markdown_to_typst`, are available in views:
|
|
97
|
+
|
|
98
|
+
```typst
|
|
99
|
+
= <%= escape_typst(@title) %>
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
In views, `url_encode` remains ActionView's own, which encodes spaces as `%20`.
|
|
103
|
+
|
|
104
|
+
`.typ` partials work like any other partial. Only the outermost `.typ`
|
|
105
|
+
template is compiled; a partial returns its Typst source, which is spliced
|
|
106
|
+
into the parent before the whole document compiles once:
|
|
107
|
+
|
|
108
|
+
```typst
|
|
109
|
+
<%# app/views/reports/monthly.pdf.typ %>
|
|
110
|
+
= Monthly Report
|
|
111
|
+
|
|
112
|
+
<%= render partial: "shared/footer" %> <%# app/views/shared/_footer.pdf.typ %>
|
|
113
|
+
```
|
|
114
|
+
|
|
60
115
|
### Rage Integration
|
|
61
116
|
|
|
62
|
-
Rage
|
|
117
|
+
Rage controllers have no template handlers, so when Rage is detected,
|
|
118
|
+
`RageController::API` gains a `render_typst` helper instead:
|
|
119
|
+
|
|
120
|
+
```ruby
|
|
121
|
+
class ReportsController < RageController::API
|
|
122
|
+
def monthly
|
|
123
|
+
@title = "Monthly Report"
|
|
124
|
+
render_typst "app/views/reports/monthly.typ", { author: "Durable Systems Inc." }
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
As with Sinatra, the template runs through ERB in the controller's scope,
|
|
130
|
+
with the locals hash as local variables, and the locals are also written to
|
|
131
|
+
`typst_data.json`. Pass `status:` to set the response status. If
|
|
132
|
+
`typst-rails` loads before Rage's controllers, add
|
|
133
|
+
`include TypstRails::RageIntegration::ControllerHelpers` to your base
|
|
134
|
+
controller.
|
|
63
135
|
|
|
64
136
|
### Sinatra Integration
|
|
65
137
|
|
|
@@ -77,55 +149,132 @@ get '/report.pdf' do
|
|
|
77
149
|
end
|
|
78
150
|
```
|
|
79
151
|
|
|
80
|
-
|
|
152
|
+
The template runs through ERB first, in the route's scope, so instance
|
|
153
|
+
variables, helpers such as `escape_typst`, and the locals hash are all
|
|
154
|
+
available. The locals are also written to `typst_data.json` for templates
|
|
155
|
+
that read it.
|
|
81
156
|
|
|
82
|
-
|
|
157
|
+
### Rendering outside a request
|
|
83
158
|
|
|
84
|
-
|
|
159
|
+
Background jobs, mailers, rake tasks, and scripts have no controller to
|
|
160
|
+
render with. `TypstRails.render` takes a template path and returns the PDF
|
|
161
|
+
as a binary string:
|
|
85
162
|
|
|
86
163
|
```ruby
|
|
87
|
-
|
|
88
|
-
|
|
164
|
+
pdf = TypstRails.render("reports/monthly",
|
|
165
|
+
locals: { month: "October" },
|
|
166
|
+
assigns: { title: "Monthly Report" })
|
|
167
|
+
File.binwrite("monthly.pdf", pdf)
|
|
89
168
|
```
|
|
90
169
|
|
|
91
|
-
|
|
170
|
+
The template runs through ERB first. `locals` become local variables,
|
|
171
|
+
`assigns` become instance variables, and the `TypstRails::Helpers` methods,
|
|
172
|
+
such as `escape_typst`, are available. Both hashes are also written to
|
|
173
|
+
`typst_data.json`, as in a controller render, with locals winning on a name
|
|
174
|
+
clash:
|
|
92
175
|
|
|
93
|
-
```
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
# => "# Title\n\nContent"
|
|
176
|
+
```typst
|
|
177
|
+
<%# app/views/reports/monthly.typ %>
|
|
178
|
+
#let data = json("typst_data.json")
|
|
97
179
|
|
|
98
|
-
|
|
99
|
-
html_to_typst("<h1>Title</h1>")
|
|
100
|
-
# => "= Title\n\n"
|
|
180
|
+
= <%= @title %>
|
|
101
181
|
|
|
102
|
-
|
|
103
|
-
sanitize_html('<script>alert("xss")</script><p>Safe</p>')
|
|
104
|
-
# => "<p>Safe</p>"
|
|
182
|
+
Figures for <%= escape_typst(month) %>, also readable as #data.month.
|
|
105
183
|
```
|
|
106
184
|
|
|
107
|
-
|
|
185
|
+
Relative paths resolve against `app/views` in a Rails app and against the
|
|
186
|
+
current directory elsewhere; pass `root:` to use another directory. The
|
|
187
|
+
`.typ` extension is optional, and `reports/monthly.pdf.typ` is found if
|
|
188
|
+
`reports/monthly.typ` does not exist. A relative path that leads outside the
|
|
189
|
+
root, such as `"../../config/master"`, raises `ArgumentError`. Absolute paths
|
|
190
|
+
are used as given, so do not pass user input as one.
|
|
191
|
+
|
|
192
|
+
These templates are not rendered by ActionView, so your app's helpers,
|
|
193
|
+
route helpers, and `render` for partials are not available.
|
|
194
|
+
|
|
195
|
+
#### Rendering through Rails
|
|
196
|
+
|
|
197
|
+
`TypstRails.render_with_rails` renders the template the way a controller
|
|
198
|
+
action does, so those helpers work. It takes a Rails template name, found
|
|
199
|
+
by Rails' own view lookup, and returns the PDF as a binary string:
|
|
200
|
+
|
|
201
|
+
```ruby
|
|
202
|
+
pdf = TypstRails.render_with_rails("reports/monthly",
|
|
203
|
+
locals: { month: "October" },
|
|
204
|
+
assigns: { title: "Monthly Report" })
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
It calls `ApplicationController.render(template:, formats: [:pdf], locals:,
|
|
208
|
+
assigns:)`. If your `ApplicationController` inherits from
|
|
209
|
+
`ActionController::API`, which cannot render views, it uses
|
|
210
|
+
`ActionController::Base` instead. Pass `controller:` to pick another one,
|
|
211
|
+
for example one that adds the helpers the template needs. Calling
|
|
212
|
+
`ApplicationController.render` yourself with the same arguments gives the
|
|
213
|
+
same result.
|
|
214
|
+
|
|
215
|
+
Which one to use:
|
|
216
|
+
|
|
217
|
+
- `TypstRails.render` works in any Ruby program, takes a file path, and
|
|
218
|
+
checks that relative paths stay inside the root. Templates get
|
|
219
|
+
`TypstRails::Helpers` and nothing else.
|
|
220
|
+
- `TypstRails.render_with_rails` needs ActionController. Use it when the
|
|
221
|
+
template calls your helpers, builds URLs, or renders partials. It raises
|
|
222
|
+
`TypstRails::Error` if ActionController is not loaded.
|
|
223
|
+
|
|
224
|
+
There is no request, so helpers that build full URLs, such as
|
|
225
|
+
`report_url`, need a host from `Rails.application.routes.default_url_options`.
|
|
226
|
+
|
|
227
|
+
Write partials as `.typ` files, such as `_footer.pdf.typ`; see the Rails
|
|
228
|
+
usage section above. An `.erb` partial also works, but Rails escapes `<%= %>`
|
|
229
|
+
output in `.erb` files as HTML, turning `&` into `&`, so use `<%== %>`
|
|
230
|
+
there, together with `escape_typst` for untrusted values.
|
|
231
|
+
|
|
232
|
+
In a job:
|
|
108
233
|
|
|
109
234
|
```ruby
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
235
|
+
class MonthlyReportJob < ApplicationJob
|
|
236
|
+
def perform(account)
|
|
237
|
+
pdf = TypstRails.render("reports/monthly", assigns: { account: account })
|
|
238
|
+
File.binwrite(Rails.root.join("tmp", "report-#{account.id}.pdf"), pdf)
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
```
|
|
113
242
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
243
|
+
Pass the PDF to `deliver_now` rather than `deliver_later` if you hand it to
|
|
244
|
+
a mailer: job arguments are serialized, and binary strings do not survive
|
|
245
|
+
that. Better still, render inside the mailer, as below.
|
|
246
|
+
|
|
247
|
+
In a mailer, assign the PDF to `attachments`:
|
|
248
|
+
|
|
249
|
+
```ruby
|
|
250
|
+
class InvoiceMailer < ApplicationMailer
|
|
251
|
+
def receipt(invoice)
|
|
252
|
+
attachments["invoice-#{invoice.number}.pdf"] =
|
|
253
|
+
TypstRails.render("invoices/show", locals: { invoice: invoice })
|
|
254
|
+
mail(to: invoice.customer.email, subject: "Your invoice")
|
|
255
|
+
end
|
|
256
|
+
end
|
|
117
257
|
```
|
|
118
258
|
|
|
119
|
-
|
|
259
|
+
To store the PDF with ActiveStorage, `TypstRails.render_and_attach` renders
|
|
260
|
+
the template and calls `attach` on what you pass it:
|
|
120
261
|
|
|
121
262
|
```ruby
|
|
122
|
-
|
|
263
|
+
class Report < ApplicationRecord
|
|
264
|
+
has_one_attached :pdf
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
TypstRails.render_and_attach(report.pdf, "reports/monthly",
|
|
268
|
+
filename: "monthly.pdf",
|
|
269
|
+
locals: { report: report })
|
|
123
270
|
```
|
|
124
271
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
272
|
+
It accepts any object with an `attach(io:, filename:, content_type:)`
|
|
273
|
+
method; ActiveStorage itself is not required. `content_type:` defaults to
|
|
274
|
+
`"application/pdf"`, and `assigns:` and `root:` work as in
|
|
275
|
+
`TypstRails.render`. Pass `via: :rails` to render with
|
|
276
|
+
`TypstRails.render_with_rails` instead; `controller:` then works as it does
|
|
277
|
+
there.
|
|
129
278
|
|
|
130
279
|
### Configuration
|
|
131
280
|
|
|
@@ -136,6 +285,85 @@ TypstRails.configure do |config|
|
|
|
136
285
|
end
|
|
137
286
|
```
|
|
138
287
|
|
|
288
|
+
`default_root_path` sets the Typst root, so templates can load files beneath
|
|
289
|
+
it with root-relative paths, such as `#image("/images/logo.png")`. Each render
|
|
290
|
+
creates a short-lived working directory inside the root, so it must be
|
|
291
|
+
writable. Without it, each render compiles in a private temporary directory
|
|
292
|
+
and cannot read your application's files.
|
|
293
|
+
|
|
294
|
+
#### Fonts
|
|
295
|
+
|
|
296
|
+
Typst finds fonts in three places: the fonts installed on the system, the
|
|
297
|
+
fonts embedded in Typst itself (Libertinus Serif, New Computer Modern and
|
|
298
|
+
DejaVu Sans Mono), and any extra directories you name.
|
|
299
|
+
|
|
300
|
+
```ruby
|
|
301
|
+
TypstRails.configure do |config|
|
|
302
|
+
config.font_paths = [Rails.root.join("app", "assets", "fonts")]
|
|
303
|
+
config.ignore_system_fonts = true
|
|
304
|
+
end
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
- `font_paths` lists directories that Typst searches, recursively, for font
|
|
308
|
+
files. It defaults to `[]`. A single path is accepted and wrapped in an
|
|
309
|
+
Array. Relative paths are expanded against the process working directory.
|
|
310
|
+
- `ignore_system_fonts` stops Typst from searching the system's fonts, so
|
|
311
|
+
only `font_paths` and Typst's embedded fonts are used. It defaults to
|
|
312
|
+
`false`.
|
|
313
|
+
|
|
314
|
+
Both settings apply to the `:cli` backend (as `--font-path` and
|
|
315
|
+
`--ignore-system-fonts`) and the `:gem` backend (as the `font_paths:` and
|
|
316
|
+
`ignore_system_fonts:` options of `Typst::Pdf.new`).
|
|
317
|
+
|
|
318
|
+
#### Fonts in production and Docker
|
|
319
|
+
|
|
320
|
+
A slim production image usually has few fonts installed, and often not the
|
|
321
|
+
ones a template was designed with. Typst does not fail when a font is
|
|
322
|
+
missing: it warns and falls back to another font, so the PDF renders but
|
|
323
|
+
looks different from the one you saw in development.
|
|
324
|
+
|
|
325
|
+
To get the same output everywhere, keep the font files with the
|
|
326
|
+
application and point `font_paths` at them:
|
|
327
|
+
|
|
328
|
+
1. Copy the `.ttf` or `.otf` files your templates use into the app, for
|
|
329
|
+
example `app/assets/fonts/`, and commit them. Check that each font's
|
|
330
|
+
license allows you to redistribute it.
|
|
331
|
+
2. Set `config.font_paths` to that directory.
|
|
332
|
+
3. Optionally set `config.ignore_system_fonts = true`. Typst then skips
|
|
333
|
+
scanning the system's font directories on each compile, and a document
|
|
334
|
+
can no longer pick up a font that happens to be installed on one machine
|
|
335
|
+
but not another. A font your templates name that is missing from
|
|
336
|
+
`font_paths` then falls back in development too, so you see the problem
|
|
337
|
+
before you deploy.
|
|
338
|
+
|
|
339
|
+
Nothing extra needs to be installed in the Docker image for this, since the
|
|
340
|
+
fonts ship inside the application directory.
|
|
341
|
+
|
|
342
|
+
#### Accessible and archival PDFs
|
|
343
|
+
|
|
344
|
+
Set `pdf_standard` to have Typst enforce a PDF standard. Use `:ua_1` for
|
|
345
|
+
PDF/UA-1, the accessibility standard:
|
|
346
|
+
|
|
347
|
+
```ruby
|
|
348
|
+
TypstRails.configure do |config|
|
|
349
|
+
config.pdf_standard = :ua_1
|
|
350
|
+
end
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
PDF/UA-1 requires a document title. Set it in each template, or the render
|
|
354
|
+
raises `TypstRails::Error`:
|
|
355
|
+
|
|
356
|
+
```typst
|
|
357
|
+
#set document(title: "Quarterly Report")
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
Pass an array to combine standards, such as `[:a_2b, :ua_1]` for a document
|
|
361
|
+
that is both archival and accessible. The accepted keys are `:pdf_1_4`,
|
|
362
|
+
`:pdf_1_5`, `:pdf_1_6`, `:pdf_1_7`, `:pdf_2_0`, `:a_1a`, `:a_1b`, `:a_2a`,
|
|
363
|
+
`:a_2b`, `:a_2u`, `:a_3a`, `:a_3b`, `:a_3u`, `:a_4`, `:a_4e`, `:a_4f` and
|
|
364
|
+
`:ua_1`, matching the values listed by `typst compile --help`. The default,
|
|
365
|
+
`nil`, produces a plain PDF. Both the CLI and gem backends honor this setting.
|
|
366
|
+
|
|
139
367
|
### Compilation Backends
|
|
140
368
|
|
|
141
369
|
`TypstRails` compiles documents through a pluggable backend. Two backends ship
|
|
@@ -172,7 +400,10 @@ class MyRemoteBackend < TypstRails::Backends::Base
|
|
|
172
400
|
end
|
|
173
401
|
|
|
174
402
|
def compile(typ_path, root_dir)
|
|
175
|
-
# ... return PDF bytes
|
|
403
|
+
# ... return PDF bytes. If Typst rejects the source, raise
|
|
404
|
+
# TypstRails::CompileError with Typst's diagnostic output as the message;
|
|
405
|
+
# raise TypstRails::Error for other failures. To report warnings from a
|
|
406
|
+
# successful compile, yield Typst's diagnostic output to the block.
|
|
176
407
|
end
|
|
177
408
|
end
|
|
178
409
|
|
|
@@ -180,6 +411,89 @@ TypstRails::Backends::Registry.register(:my_remote, MyRemoteBackend.new)
|
|
|
180
411
|
TypstRails.configure { |config| config.backend = :my_remote }
|
|
181
412
|
```
|
|
182
413
|
|
|
414
|
+
### Errors
|
|
415
|
+
|
|
416
|
+
When Typst rejects a template, rendering raises `TypstRails::CompileError`, a
|
|
417
|
+
subclass of `TypstRails::Error`, so existing `rescue TypstRails::Error` code
|
|
418
|
+
keeps working. The message names the template and the location of the first
|
|
419
|
+
error, followed by Typst's own report:
|
|
420
|
+
|
|
421
|
+
```
|
|
422
|
+
Typst compilation failed in app/views/reports/show.pdf.typ:4:9: unknown variable: foo
|
|
423
|
+
(Line numbers count lines of the compiled Typst source, after any ERB evaluation.)
|
|
424
|
+
|
|
425
|
+
error: unknown variable: foo
|
|
426
|
+
┌─ app/views/reports/show.pdf.typ:4:9
|
|
427
|
+
│
|
|
428
|
+
4 │ #let x = foo(1)
|
|
429
|
+
│ ^^^
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
Each render compiles a copy of the template in a temporary directory. Paths
|
|
433
|
+
into that directory are replaced in the message: the template becomes its
|
|
434
|
+
name (the view path in Rails, the path you passed to the Sinatra and Rage
|
|
435
|
+
helpers, or `(inline source)` for a `Renderer` built from a string), other
|
|
436
|
+
files under the Typst root become root-relative paths such as `/lib.typ`, and
|
|
437
|
+
files next to the template, such as `typst_data.json`, are shown by name.
|
|
438
|
+
To name a template yourself, pass `template:` to `TypstRails::Renderer.new`:
|
|
439
|
+
|
|
440
|
+
```ruby
|
|
441
|
+
TypstRails::Renderer.new(File.read(path), template: path).render(nil, data)
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
The error also carries the details as attributes:
|
|
445
|
+
|
|
446
|
+
```ruby
|
|
447
|
+
rescue TypstRails::CompileError => e
|
|
448
|
+
e.template # => "app/views/reports/show.pdf.typ", or nil
|
|
449
|
+
e.line # => 4, line of the first error
|
|
450
|
+
e.column # => 9, column of the first error
|
|
451
|
+
e.source_line # => "#let x = foo(1)", when the error is in the template
|
|
452
|
+
e.diagnostics # => every error and warning, with severity, message,
|
|
453
|
+
# path, line, column and hints
|
|
454
|
+
e.errors # => just the errors
|
|
455
|
+
e.warnings # => just the warnings
|
|
456
|
+
e.typst_message # => Typst's output, with paths rewritten
|
|
457
|
+
e.command # => the command line the CLI backend ran, for debugging
|
|
458
|
+
end
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
Line numbers refer to the source Typst compiled. For `.typ` views and the
|
|
462
|
+
Sinatra and Rage helpers, that is the template after ERB evaluation, so an
|
|
463
|
+
ERB tag that expands to several lines, or a `<% %>` line that is trimmed
|
|
464
|
+
away, shifts them relative to the file on disk; `source_line` shows the line
|
|
465
|
+
Typst actually saw. Columns are counted from 0, as Typst prints them.
|
|
466
|
+
|
|
467
|
+
Parsing is best-effort. If Typst's output is not in a format TypstRails
|
|
468
|
+
recognizes, you still get a `CompileError` with the raw output in the message
|
|
469
|
+
and in `typst_message`, and `diagnostics` is empty.
|
|
470
|
+
|
|
471
|
+
### Warnings
|
|
472
|
+
|
|
473
|
+
Typst can report warnings, such as an unknown font family, on a compile that
|
|
474
|
+
succeeds. With the CLI backend, TypstRails passes them to `config.on_warning`,
|
|
475
|
+
which is called with an array of diagnostics and the template's name (or
|
|
476
|
+
nil). By default the warnings are logged with `Rails.logger.warn`, or with
|
|
477
|
+
`Kernel#warn` outside Rails:
|
|
478
|
+
|
|
479
|
+
```ruby
|
|
480
|
+
TypstRails.configure do |config|
|
|
481
|
+
# Fail tests on any Typst warning:
|
|
482
|
+
config.on_warning = ->(warnings, template) do
|
|
483
|
+
raise "Typst warnings in #{template}: #{warnings.map(&:to_s).join(", ")}"
|
|
484
|
+
end
|
|
485
|
+
|
|
486
|
+
# Or ignore them:
|
|
487
|
+
# config.on_warning = nil
|
|
488
|
+
end
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
An error raised by the handler propagates from the render.
|
|
492
|
+
|
|
493
|
+
The `typst` gem returns only the PDF on a successful compile, so with the
|
|
494
|
+
`:gem` backend `on_warning` is never called. Warnings that accompany a failed
|
|
495
|
+
compile are included in `CompileError#warnings` with either backend.
|
|
496
|
+
|
|
183
497
|
## Testing
|
|
184
498
|
|
|
185
499
|
The gem includes comprehensive testing at multiple levels:
|
|
@@ -237,7 +551,7 @@ a real release rather than loaded from the working tree:
|
|
|
237
551
|
bundle exec rake e2e:docker
|
|
238
552
|
```
|
|
239
553
|
|
|
240
|
-
See [e2e-docker/README.md](e2e-docker/README.md) for detailed documentation.
|
|
554
|
+
See [e2e-tests/docker/README.md](e2e-tests/docker/README.md) for detailed documentation.
|
|
241
555
|
|
|
242
556
|
### Code Coverage
|
|
243
557
|
|
data/lib/typst-rails.rb
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Bundler.require loads a gem by its name, "typst-rails", but the library's
|
|
4
|
+
# entry point is typst_rails.rb. This file bridges the two, so a plain
|
|
5
|
+
# `gem "typst-rails"` line in a Gemfile loads the Railtie and registers the
|
|
6
|
+
# .typ template handler.
|
|
7
|
+
require "typst_rails"
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "typst_rails/errors"
|
|
4
|
+
|
|
3
5
|
module TypstRails
|
|
4
6
|
module Backends
|
|
5
7
|
# Abstract interface for a Typst compilation backend.
|
|
@@ -20,11 +22,32 @@ module TypstRails
|
|
|
20
22
|
#
|
|
21
23
|
# @param typ_path [String] path to the .typ source file to compile
|
|
22
24
|
# @param root_dir [String] root directory for resolving relative imports
|
|
25
|
+
# @yieldparam diagnostics [String] Typst's diagnostic output from a
|
|
26
|
+
# successful compile, such as warnings. Backends that can see it
|
|
27
|
+
# should yield it when a block is given; the Renderer parses it and
|
|
28
|
+
# passes the warnings to {TypstRails::Configuration#on_warning}.
|
|
29
|
+
# Yielding is optional.
|
|
23
30
|
# @return [String] binary PDF data
|
|
24
|
-
# @raise [TypstRails::
|
|
31
|
+
# @raise [TypstRails::CompileError] if Typst rejects the source; pass
|
|
32
|
+
# Typst's diagnostic output as the message so it can be parsed
|
|
33
|
+
# @raise [TypstRails::Error] if compilation fails for another reason
|
|
25
34
|
def compile(typ_path, root_dir)
|
|
26
35
|
raise NotImplementedError, "#{self.class} must implement #compile"
|
|
27
36
|
end
|
|
37
|
+
|
|
38
|
+
private
|
|
39
|
+
|
|
40
|
+
# Options from {TypstRails::Configuration#compile_options}, or an empty
|
|
41
|
+
# Hash when nothing is configured. TypstRails.configuration is checked
|
|
42
|
+
# with respond_to? first because the top-level module is not loaded when
|
|
43
|
+
# "typst_rails/renderer" is required on its own.
|
|
44
|
+
#
|
|
45
|
+
# @return [Hash{Symbol => Object}]
|
|
46
|
+
def configured_compile_options
|
|
47
|
+
return {} unless TypstRails.respond_to?(:configuration)
|
|
48
|
+
|
|
49
|
+
TypstRails.configuration&.compile_options || {}
|
|
50
|
+
end
|
|
28
51
|
end
|
|
29
52
|
end
|
|
30
53
|
end
|
|
@@ -23,17 +23,27 @@ module TypstRails
|
|
|
23
23
|
@executable_path = executable_path
|
|
24
24
|
end
|
|
25
25
|
|
|
26
|
+
# A path containing a directory separator is checked directly; a bare
|
|
27
|
+
# name is looked up on PATH, as the compile command would be. No shell
|
|
28
|
+
# is involved, so the path is never interpreted.
|
|
29
|
+
#
|
|
26
30
|
# @return [Boolean] whether the configured Typst executable can be found
|
|
27
31
|
def available?
|
|
28
|
-
|
|
32
|
+
path = executable_path
|
|
33
|
+
return executable_file?(path) if directory_path?(path)
|
|
29
34
|
|
|
30
|
-
|
|
35
|
+
executable_on_path?(path)
|
|
31
36
|
end
|
|
32
37
|
|
|
38
|
+
# Passes {TypstRails::Configuration#compile_options} to Typst as
|
|
39
|
+
# command-line flags. Typst's stderr is parsed into the raised
|
|
40
|
+
# {TypstRails::CompileError} on failure, and yielded to the block, if
|
|
41
|
+
# given, on success, since a successful compile can still print warnings.
|
|
42
|
+
#
|
|
33
43
|
# @see Base#compile
|
|
34
44
|
def compile(typ_path, root_dir)
|
|
35
45
|
output_pdf_path = File.join(root_dir, "#{File.basename(typ_path, ".typ")}_output.pdf")
|
|
36
|
-
cmd = [executable_path, "compile", "--root", root_dir, typ_path, output_pdf_path]
|
|
46
|
+
cmd = [executable_path, "compile", "--root", root_dir, *compile_option_args, typ_path, output_pdf_path]
|
|
37
47
|
|
|
38
48
|
begin
|
|
39
49
|
_stdout_str, stderr_str, status = Open3.capture3(*cmd)
|
|
@@ -43,8 +53,11 @@ module TypstRails
|
|
|
43
53
|
raise Error, "Failed to execute Typst compiler: #{e.message}"
|
|
44
54
|
end
|
|
45
55
|
|
|
46
|
-
|
|
47
|
-
|
|
56
|
+
raise CompileError.new(stderr_str, command: cmd) unless status.success?
|
|
57
|
+
|
|
58
|
+
pdf_data = read_compiled_pdf(output_pdf_path)
|
|
59
|
+
yield stderr_str if block_given? && !stderr_str.strip.empty?
|
|
60
|
+
pdf_data
|
|
48
61
|
ensure
|
|
49
62
|
safe_unlink(output_pdf_path)
|
|
50
63
|
end
|
|
@@ -64,6 +77,35 @@ module TypstRails
|
|
|
64
77
|
TypstRails.configuration&.typst_executable_path
|
|
65
78
|
end
|
|
66
79
|
|
|
80
|
+
# Flags for the configured compile options. Each font directory gets its
|
|
81
|
+
# own --font-path flag rather than one PATH_SEPARATOR-joined value, so a
|
|
82
|
+
# directory whose name contains the separator still reaches Typst
|
|
83
|
+
# intact. Typst takes several PDF standards as one comma-separated value.
|
|
84
|
+
def compile_option_args
|
|
85
|
+
options = configured_compile_options
|
|
86
|
+
flags = Array(options[:font_paths]).flat_map { |path| ["--font-path", path] }
|
|
87
|
+
flags << "--ignore-system-fonts" if options[:ignore_system_fonts]
|
|
88
|
+
standards = Array(options[:pdf_standards])
|
|
89
|
+
flags.push("--pdf-standard", standards.join(",")) unless standards.empty?
|
|
90
|
+
flags
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def directory_path?(path)
|
|
94
|
+
[File::SEPARATOR, File::ALT_SEPARATOR].compact.any? { |separator| path.include?(separator) }
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def executable_on_path?(name)
|
|
98
|
+
extensions = [""] + ENV.fetch("PATHEXT", "").split(File::PATH_SEPARATOR)
|
|
99
|
+
|
|
100
|
+
ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).any? do |dir|
|
|
101
|
+
extensions.any? { |ext| executable_file?(File.join(dir, "#{name}#{ext}")) }
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def executable_file?(path)
|
|
106
|
+
File.file?(path) && File.executable?(path)
|
|
107
|
+
end
|
|
108
|
+
|
|
67
109
|
def read_compiled_pdf(output_pdf_path)
|
|
68
110
|
raise Error, "Typst compilation succeeded but output file was not created" unless File.exist?(output_pdf_path)
|
|
69
111
|
|
|
@@ -73,13 +115,6 @@ module TypstRails
|
|
|
73
115
|
pdf_data
|
|
74
116
|
end
|
|
75
117
|
|
|
76
|
-
def raise_compilation_failure(cmd, stderr_str)
|
|
77
|
-
error_message = "Typst compilation failed.\n"
|
|
78
|
-
error_message += "Command: #{cmd.join(" ")}\n"
|
|
79
|
-
error_message += "Stderr: #{stderr_str}" unless stderr_str.empty?
|
|
80
|
-
raise Error, error_message
|
|
81
|
-
end
|
|
82
|
-
|
|
83
118
|
def safe_unlink(path)
|
|
84
119
|
File.unlink(path) if path && File.exist?(path)
|
|
85
120
|
rescue StandardError => e
|
|
@@ -32,11 +32,28 @@ module TypstRails
|
|
|
32
32
|
end
|
|
33
33
|
end
|
|
34
34
|
|
|
35
|
+
# Passes {TypstRails::Configuration#compile_options} to `Typst::Pdf.new`.
|
|
36
|
+
# The `typst` gem raises with Typst's diagnostics as the message, so
|
|
37
|
+
# failures become a {TypstRails::CompileError} with parsed
|
|
38
|
+
# diagnostics. On success it returns only the PDF, so warnings are not
|
|
39
|
+
# available and nothing is yielded.
|
|
40
|
+
#
|
|
35
41
|
# @see Base#compile
|
|
36
42
|
def compile(typ_path, root_dir)
|
|
37
|
-
::Typst::Pdf.new(file: typ_path, root: root_dir).compiled.document
|
|
43
|
+
::Typst::Pdf.new(file: typ_path, root: root_dir, **gem_options).compiled.document
|
|
38
44
|
rescue StandardError => e
|
|
39
|
-
raise
|
|
45
|
+
raise CompileError, e.message
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
private
|
|
49
|
+
|
|
50
|
+
# Options for Typst::Pdf.new, under the keys the `typst` gem expects.
|
|
51
|
+
# PDF standards are left out when none are configured, so a plain
|
|
52
|
+
# compile does not pass an empty list.
|
|
53
|
+
def gem_options
|
|
54
|
+
options = configured_compile_options.slice(:font_paths, :ignore_system_fonts, :pdf_standards)
|
|
55
|
+
options.delete(:pdf_standards) if Array(options[:pdf_standards]).empty?
|
|
56
|
+
options
|
|
40
57
|
end
|
|
41
58
|
end
|
|
42
59
|
end
|