typst-rails 0.1.0 → 0.2.1
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 +103 -1
- data/README.md +44 -52
- data/lib/typst_rails/backends/cli.rb +23 -2
- data/lib/typst_rails/erb_source.rb +36 -0
- data/lib/typst_rails/framework_detection.rb +13 -4
- 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/railtie.rb +7 -0
- data/lib/typst_rails/renderer.rb +54 -24
- data/lib/typst_rails/sinatra_integration.rb +7 -2
- data/lib/typst_rails/version.rb +1 -1
- data/lib/typst_rails/view_helpers.rb +28 -0
- data/lib/typst_rails.rb +9 -5
- metadata +9 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: fc059a87f8ebdb16113e053ae6bdad1c32638cc1137e77424430504ab08d9635
|
|
4
|
+
data.tar.gz: b39bda7395a15634391fd0b1d8a8923377387580f21797b367383ab01cc01a53
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 6e792083bd8593a5eea48147de44270444b9d83ade7de8074c4c177633681af8629dea85a56880b30a58384a8af8646a02e03a0bb2b282ba5deb356b9ee5a415
|
|
7
|
+
data.tar.gz: ee5c42c4d491ce960b774829e9201ace7b3716f2cabc3f902affb734c54fd2a142bf9834c608ffa67f033d947415607f238173d9814bf2af125843e844777511
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.2.1] - 2026-11-14
|
|
11
|
+
|
|
10
12
|
### Added
|
|
11
13
|
- Swappable Typst compilation backends: a `:cli` backend (shells out to the
|
|
12
14
|
Typst executable, the original behavior) and a `:gem` backend (uses the
|
|
@@ -14,7 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
14
16
|
automatically via `TypstRails::Backends::Registry` or set explicitly with
|
|
15
17
|
`TypstRails.configure { |c| c.backend = :gem }`. Custom backends can be
|
|
16
18
|
registered for other compilation strategies.
|
|
17
|
-
- Docker-based end-to-end tests (`e2e-docker/`, `rake e2e:docker`) covering
|
|
19
|
+
- Docker-based end-to-end tests (`e2e-tests/docker/`, `rake e2e:docker`) covering
|
|
18
20
|
the backend auto-detection matrix (CLI-only, gem-only, both, neither) and a
|
|
19
21
|
fresh `gem build` + `gem install` smoke test, independent of the local dev
|
|
20
22
|
environment.
|
|
@@ -29,7 +31,97 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
29
31
|
- Enhanced gemspec description with clearer value proposition
|
|
30
32
|
- Updated author email to commercial@durableprogramming.com
|
|
31
33
|
|
|
34
|
+
### Removed
|
|
35
|
+
- **Breaking:** the `sanitize_html` helper, along with the
|
|
36
|
+
`DEFAULT_ALLOWED_TAGS` and `DEFAULT_ALLOWED_ATTRIBUTES` constants. Nothing in
|
|
37
|
+
the gem called it: `html_to_typst` never sanitized its input, so this was an
|
|
38
|
+
opt-in helper that duplicated, less thoroughly, what dedicated sanitizers
|
|
39
|
+
already do. Callers who need it should use ActionView's `sanitize` helper,
|
|
40
|
+
the Rails::HTML sanitizers, Loofah, or the `sanitize` gem. Note that HTML
|
|
41
|
+
sanitization was never sufficient here in any case: it strips dangerous HTML,
|
|
42
|
+
but the surviving text still reaches a Typst document where `#`, `$`, `[`,
|
|
43
|
+
and `@` are syntactically meaningful. See SECURITY.md.
|
|
44
|
+
|
|
32
45
|
### Fixed
|
|
46
|
+
- Rage integration now works. It previously called an empty `Rage.configure`
|
|
47
|
+
block and registered nothing. Rage has no template handlers, so
|
|
48
|
+
`RageController::API` now gains `render_typst(template, locals, status:)`,
|
|
49
|
+
which runs the template through ERB and responds with the PDF.
|
|
50
|
+
- The Sinatra `typst` helper now runs templates through ERB, with the route's
|
|
51
|
+
instance variables, the `TypstRails::Helpers` methods, and the locals hash
|
|
52
|
+
in scope. It previously passed the file to Typst unprocessed, so data could
|
|
53
|
+
reach the template only through `typst_data.json`.
|
|
54
|
+
- `TypstRails::Helpers` is now available in Rails views. It was mixed only
|
|
55
|
+
into `Renderer`, but `.typ` templates evaluate their ERB in the view
|
|
56
|
+
context, so `escape_typst` raised `NoMethodError` there. Views keep
|
|
57
|
+
ActionView's `url_encode`.
|
|
58
|
+
- `typst_data.json` is written only when the template source mentions it.
|
|
59
|
+
Every controller instance variable, including whole ActiveRecord models,
|
|
60
|
+
was previously serialized to disk on each render, whether or not the
|
|
61
|
+
template read it.
|
|
62
|
+
- `default_root_path` now sets the Typst root. It was validated but never
|
|
63
|
+
read, so templates could not load files from the application. It also
|
|
64
|
+
accepts a `Pathname`; the README's `Rails.root.join(...)` example raised
|
|
65
|
+
`ArgumentError`.
|
|
66
|
+
- `markdown_to_typst` (and so `html_to_typst` and `include_markdown`) let
|
|
67
|
+
link and image URLs close the Typst string they were written into. A `"`
|
|
68
|
+
in a URL broke compilation, and a crafted URL could add Typst code to the
|
|
69
|
+
document. URLs are now written as escaped string literals, and link titles
|
|
70
|
+
(`[x](url "title")`) are dropped instead of being pasted into the URL.
|
|
71
|
+
- `markdown_to_typst` passed ordinary text through as Typst syntax, so
|
|
72
|
+
`#hashtag` ran as code, `$5 or $10` became math, `me@example.com` became a
|
|
73
|
+
reference, and an unmatched `**` or `_` opened emphasis. Text is now escaped
|
|
74
|
+
with `escape_typst`, and only the Markdown the converter recognizes becomes
|
|
75
|
+
Typst markup. This changes output for text that was previously passed
|
|
76
|
+
through raw: Typst markup given to `markdown_to_typst` is now escaped
|
|
77
|
+
rather than kept.
|
|
78
|
+
- `markdown_to_typst` now honors Markdown backslash escapes (`\*`, `\#`,
|
|
79
|
+
`\[`, and a trailing `# Changelog
|
|
80
|
+
|
|
81
|
+
All notable changes to this project will be documented in this file.
|
|
82
|
+
|
|
83
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
84
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
85
|
+
|
|
86
|
+
as a hard line break) and converts autolinks
|
|
87
|
+
(`<https://...>`).
|
|
88
|
+
- `markdown_to_typst` converts `*` and `+` bullets to `-`. Typst has no `*`
|
|
89
|
+
bullet (the line became bold text), and its `+` makes a numbered item.
|
|
90
|
+
Ordered items written `1)` become `1.`.
|
|
91
|
+
- Text right after a converted link or image, such as `(note)` or `.field`,
|
|
92
|
+
is no longer read by Typst as part of the `#link`/`#image` call.
|
|
93
|
+
- `Backends::Cli#available?` searches PATH in Ruby instead of running
|
|
94
|
+
`which` through a shell, so the configured executable path is never
|
|
95
|
+
interpreted by a shell. It also now requires the file to be executable.
|
|
96
|
+
- `escape_typst` now also escapes backticks, `~`, comment openers (`//`,
|
|
97
|
+
`/*`), dash shorthands (`--`, `---`, `-?`) and line-start markers (`=`, `-`,
|
|
98
|
+
`+`, `/`, `1.`). Text such as `a // b` previously lost everything after the
|
|
99
|
+
`//`, and a line beginning `- ` became a list item.
|
|
100
|
+
- `markdown_to_typst` no longer rewrites the contents of inline code or fenced
|
|
101
|
+
code blocks, and no longer treats `*` or `_` with whitespace on the inner
|
|
102
|
+
side as emphasis (`2 * 3 * 4` was converted to `2 _ 3 _ 4`).
|
|
103
|
+
- Concurrent renders no longer share `typst_data.json`. Each render now
|
|
104
|
+
compiles in its own temporary directory, so threads cannot read or delete
|
|
105
|
+
one another's data.
|
|
106
|
+
- `Renderer` now forwards keyword arguments when delegating helper calls to the
|
|
107
|
+
view context. On Ruby 3, helpers taking keyword arguments raised
|
|
108
|
+
`ArgumentError` when called through the renderer.
|
|
109
|
+
- `markdown_to_typst` mangled combined bold+italic: `***text***` came out as
|
|
110
|
+
`*_text*_` with mismatched markers, because the bold pass matched only two
|
|
111
|
+
of the three asterisks and stranded the third inside the text. `***text***`
|
|
112
|
+
and `___text___` are now recognized as a single token and convert to
|
|
113
|
+
`*_text_*`.
|
|
114
|
+
- `markdown_to_typst` rewrote `\x01` and `\x02` in the caller's own text to
|
|
115
|
+
`*`. Those bytes were used as internal placeholders while converting
|
|
116
|
+
emphasis, so any already present in the input were indistinguishable from
|
|
117
|
+
markers the conversion had written. Placeholders moved to the Unicode
|
|
118
|
+
private use area, and any that do appear in the source are now held aside
|
|
119
|
+
and restored verbatim.
|
|
120
|
+
- `FrameworkDetection.rails?`, `.rage?`, and `.sinatra?` returned `nil` rather
|
|
121
|
+
than `false` when the framework was absent, because `defined?` yields a
|
|
122
|
+
String or nil and the expressions were not coerced. They now return real
|
|
123
|
+
booleans, so callers comparing against `false` or serializing the result
|
|
124
|
+
behave as expected.
|
|
33
125
|
- `Backends::Cli#available?` raised `NoMethodError` when the gem was loaded
|
|
34
126
|
via a bare `require "typst_rails/renderer"`, because `executable_path` read
|
|
35
127
|
`TypstRails.configuration` without checking that the top-level module was
|
|
@@ -39,6 +131,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
39
131
|
- `TypstRails.configuration.typst_executable_path` is now actually used by
|
|
40
132
|
the CLI backend when compiling (previously ignored, so the setting had no
|
|
41
133
|
effect).
|
|
134
|
+
- Three E2E templates failed to compile because they fed Typst syntax it
|
|
135
|
+
could not parse. `02_html_conversion` piped `html_to_markdown` output --
|
|
136
|
+
raw Markdown, where `#` starts a heading -- directly into the document,
|
|
137
|
+
which Typst reads as code; it is now shown verbatim in a `#raw()` block.
|
|
138
|
+
`03_markdown_conversion` referenced a remote image, which Typst refuses to
|
|
139
|
+
fetch; the image case is now asserted as generated markup instead, since the
|
|
140
|
+
renderer compiles from a temp dir whose `--root` cannot reach repo files.
|
|
141
|
+
`05_complex_template` passed plain text containing `#` and `*` through
|
|
142
|
+
`html_to_typst`, which does not escape Typst metacharacters; the fixtures
|
|
143
|
+
are now the HTML that helper expects.
|
|
42
144
|
|
|
43
145
|
## [0.1.0] - 2024-01-XX (Initial Release)
|
|
44
146
|
|
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,41 @@ 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
|
+
The `TypstRails::Helpers` methods, such as `escape_typst` and
|
|
66
|
+
`markdown_to_typst`, are available in views:
|
|
67
|
+
|
|
68
|
+
```typst
|
|
69
|
+
= <%= escape_typst(@title) %>
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
In views, `url_encode` remains ActionView's own, which encodes spaces as `%20`.
|
|
73
|
+
|
|
60
74
|
### Rage Integration
|
|
61
75
|
|
|
62
|
-
Rage
|
|
76
|
+
Rage controllers have no template handlers, so when Rage is detected,
|
|
77
|
+
`RageController::API` gains a `render_typst` helper instead:
|
|
78
|
+
|
|
79
|
+
```ruby
|
|
80
|
+
class ReportsController < RageController::API
|
|
81
|
+
def monthly
|
|
82
|
+
@title = "Monthly Report"
|
|
83
|
+
render_typst "app/views/reports/monthly.typ", { author: "Durable Systems Inc." }
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
As with Sinatra, the template runs through ERB in the controller's scope,
|
|
89
|
+
with the locals hash as local variables, and the locals are also written to
|
|
90
|
+
`typst_data.json`. Pass `status:` to set the response status. If
|
|
91
|
+
`typst-rails` loads before Rage's controllers, add
|
|
92
|
+
`include TypstRails::RageIntegration::ControllerHelpers` to your base
|
|
93
|
+
controller.
|
|
63
94
|
|
|
64
95
|
### Sinatra Integration
|
|
65
96
|
|
|
@@ -77,55 +108,10 @@ get '/report.pdf' do
|
|
|
77
108
|
end
|
|
78
109
|
```
|
|
79
110
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
The
|
|
83
|
-
|
|
84
|
-
#### Text Escaping
|
|
85
|
-
|
|
86
|
-
```ruby
|
|
87
|
-
escape_typst("Price: $100") # => "Price: \\$100"
|
|
88
|
-
escape_typst("Hello #world") # => "Hello \\#world"
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
#### HTML to Markdown/Typst Conversion
|
|
92
|
-
|
|
93
|
-
```ruby
|
|
94
|
-
# Convert HTML to Markdown
|
|
95
|
-
html_to_markdown("<h1>Title</h1><p>Content</p>")
|
|
96
|
-
# => "# Title\n\nContent"
|
|
97
|
-
|
|
98
|
-
# Convert HTML directly to Typst
|
|
99
|
-
html_to_typst("<h1>Title</h1>")
|
|
100
|
-
# => "= Title\n\n"
|
|
101
|
-
|
|
102
|
-
# Sanitize HTML before conversion
|
|
103
|
-
sanitize_html('<script>alert("xss")</script><p>Safe</p>')
|
|
104
|
-
# => "<p>Safe</p>"
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
#### Markdown Conversion
|
|
108
|
-
|
|
109
|
-
```ruby
|
|
110
|
-
# Convert Markdown to Typst syntax
|
|
111
|
-
markdown_to_typst("# Title\n## Subtitle")
|
|
112
|
-
# => "= Title\n== Subtitle"
|
|
113
|
-
|
|
114
|
-
# Include external Markdown files
|
|
115
|
-
include_markdown("./content.md")
|
|
116
|
-
# Reads and converts the file to Typst syntax
|
|
117
|
-
```
|
|
118
|
-
|
|
119
|
-
#### URL Encoding
|
|
120
|
-
|
|
121
|
-
```ruby
|
|
122
|
-
url_encode("hello world") # => "hello+world"
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
These helpers are available in:
|
|
126
|
-
- ERB templates (Rails) - use directly: `<%= escape_typst(@text) %>`
|
|
127
|
-
- Plain Ruby code - include `TypstRails::Helpers` module
|
|
128
|
-
- The renderer includes these helpers automatically
|
|
111
|
+
The template runs through ERB first, in the route's scope, so instance
|
|
112
|
+
variables, helpers such as `escape_typst`, and the locals hash are all
|
|
113
|
+
available. The locals are also written to `typst_data.json` for templates
|
|
114
|
+
that read it.
|
|
129
115
|
|
|
130
116
|
### Configuration
|
|
131
117
|
|
|
@@ -136,6 +122,12 @@ TypstRails.configure do |config|
|
|
|
136
122
|
end
|
|
137
123
|
```
|
|
138
124
|
|
|
125
|
+
`default_root_path` sets the Typst root, so templates can load files beneath
|
|
126
|
+
it with root-relative paths, such as `#image("/images/logo.png")`. Each render
|
|
127
|
+
creates a short-lived working directory inside the root, so it must be
|
|
128
|
+
writable. Without it, each render compiles in a private temporary directory
|
|
129
|
+
and cannot read your application's files.
|
|
130
|
+
|
|
139
131
|
### Compilation Backends
|
|
140
132
|
|
|
141
133
|
`TypstRails` compiles documents through a pluggable backend. Two backends ship
|
|
@@ -237,7 +229,7 @@ a real release rather than loaded from the working tree:
|
|
|
237
229
|
bundle exec rake e2e:docker
|
|
238
230
|
```
|
|
239
231
|
|
|
240
|
-
See [e2e-docker/README.md](e2e-docker/README.md) for detailed documentation.
|
|
232
|
+
See [e2e-tests/docker/README.md](e2e-tests/docker/README.md) for detailed documentation.
|
|
241
233
|
|
|
242
234
|
### Code Coverage
|
|
243
235
|
|
|
@@ -23,11 +23,16 @@ 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
|
|
|
33
38
|
# @see Base#compile
|
|
@@ -64,6 +69,22 @@ module TypstRails
|
|
|
64
69
|
TypstRails.configuration&.typst_executable_path
|
|
65
70
|
end
|
|
66
71
|
|
|
72
|
+
def directory_path?(path)
|
|
73
|
+
[File::SEPARATOR, File::ALT_SEPARATOR].compact.any? { |separator| path.include?(separator) }
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def executable_on_path?(name)
|
|
77
|
+
extensions = [""] + ENV.fetch("PATHEXT", "").split(File::PATH_SEPARATOR)
|
|
78
|
+
|
|
79
|
+
ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).any? do |dir|
|
|
80
|
+
extensions.any? { |ext| executable_file?(File.join(dir, "#{name}#{ext}")) }
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def executable_file?(path)
|
|
85
|
+
File.file?(path) && File.executable?(path)
|
|
86
|
+
end
|
|
87
|
+
|
|
67
88
|
def read_compiled_pdf(output_pdf_path)
|
|
68
89
|
raise Error, "Typst compilation succeeded but output file was not created" unless File.exist?(output_pdf_path)
|
|
69
90
|
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "erb"
|
|
4
|
+
|
|
5
|
+
module TypstRails
|
|
6
|
+
# Runs a Typst template through ERB in a given scope, for frameworks
|
|
7
|
+
# without an ActionView-style template handler (Sinatra, Rage).
|
|
8
|
+
#
|
|
9
|
+
# As in Rails `.typ` views, output from `<%= %>` is not escaped; use
|
|
10
|
+
# {Helpers#escape_typst} for untrusted values.
|
|
11
|
+
#
|
|
12
|
+
# @api private
|
|
13
|
+
module ErbSource
|
|
14
|
+
# Local names ERB can bind; other keys still reach typst_data.json.
|
|
15
|
+
LOCAL_NAME = /\A[a-z_][a-zA-Z0-9_]*\z/.freeze
|
|
16
|
+
|
|
17
|
+
# Defined at module level so the binding it returns closes over no
|
|
18
|
+
# locals of #render, which a same-named template local could clobber.
|
|
19
|
+
BLANK_BINDING = proc { binding }
|
|
20
|
+
private_constant :BLANK_BINDING
|
|
21
|
+
|
|
22
|
+
# @param source [String] template source
|
|
23
|
+
# @param scope [Object] self for the template: its instance variables
|
|
24
|
+
# and methods are visible to ERB
|
|
25
|
+
# @param locals [Hash] exposed to ERB as local variables
|
|
26
|
+
# @return [String] the evaluated Typst source
|
|
27
|
+
def self.render(source, scope, locals = {})
|
|
28
|
+
context = scope.instance_exec(&BLANK_BINDING)
|
|
29
|
+
locals.each do |name, value|
|
|
30
|
+
name = name.to_s
|
|
31
|
+
context.local_variable_set(name, value) if LOCAL_NAME.match?(name)
|
|
32
|
+
end
|
|
33
|
+
::ERB.new(source, trim_mode: "-").result(context)
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
@@ -1,18 +1,27 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module TypstRails
|
|
4
|
-
# Detects which web framework (if any) is currently loaded
|
|
4
|
+
# Detects which web framework (if any) is currently loaded.
|
|
5
|
+
#
|
|
6
|
+
# Each predicate returns a real +true+ or +false+. `defined?` yields a
|
|
7
|
+
# String or nil rather than a boolean, so the results are coerced: callers
|
|
8
|
+
# that compare against +false+ or serialize the value would otherwise see
|
|
9
|
+
# nil when the framework is absent.
|
|
5
10
|
module FrameworkDetection
|
|
11
|
+
# @return [Boolean] whether Rails is loaded and booted far enough to have
|
|
12
|
+
# an application object
|
|
6
13
|
def self.rails?
|
|
7
|
-
defined?(::Rails) && ::Rails.respond_to?(:application)
|
|
14
|
+
!!(defined?(::Rails) && ::Rails.respond_to?(:application))
|
|
8
15
|
end
|
|
9
16
|
|
|
17
|
+
# @return [Boolean] whether Rage is loaded
|
|
10
18
|
def self.rage?
|
|
11
|
-
defined?(::Rage::Application)
|
|
19
|
+
!defined?(::Rage::Application).nil?
|
|
12
20
|
end
|
|
13
21
|
|
|
22
|
+
# @return [Boolean] whether Sinatra is loaded
|
|
14
23
|
def self.sinatra?
|
|
15
|
-
defined?(::Sinatra::Base)
|
|
24
|
+
!defined?(::Sinatra::Base).nil?
|
|
16
25
|
end
|
|
17
26
|
|
|
18
27
|
def self.detected_framework
|
data/lib/typst_rails/helpers.rb
CHANGED
|
@@ -12,7 +12,6 @@ module TypstRails
|
|
|
12
12
|
# - Converting HTML to Markdown and Typst
|
|
13
13
|
# - Converting Markdown to Typst syntax
|
|
14
14
|
# - Including external Markdown files
|
|
15
|
-
# - Sanitizing HTML for security
|
|
16
15
|
# - URL encoding
|
|
17
16
|
#
|
|
18
17
|
# These helpers are included in the Renderer and available in Rails ERB templates
|
|
@@ -41,6 +40,14 @@ module TypstRails
|
|
|
41
40
|
# - `<`, `>` (labels and references)
|
|
42
41
|
# - `{`, `}` (code blocks)
|
|
43
42
|
# - `@` (references)
|
|
43
|
+
# - `` ` `` (raw text)
|
|
44
|
+
# - `~` (non-breaking space)
|
|
45
|
+
# - `/` when it starts a comment (`//`, `/*`)
|
|
46
|
+
# - `-` when it starts a shorthand (`--`, `---`, `-?`)
|
|
47
|
+
#
|
|
48
|
+
# Characters that only mean something at the start of a line are escaped
|
|
49
|
+
# there: `=` (heading), `-` (list), `+` (numbered list), `/` (term list)
|
|
50
|
+
# and the `.` of `1.` (numbered list).
|
|
44
51
|
#
|
|
45
52
|
# @param text [String, nil] The text to escape
|
|
46
53
|
# @return [String] The escaped text, or empty string if text is nil
|
|
@@ -65,7 +72,11 @@ module TypstRails
|
|
|
65
72
|
|
|
66
73
|
# Escape special Typst characters
|
|
67
74
|
# See: https://typst.app/docs/reference/syntax/
|
|
68
|
-
text.gsub(/([#\$*_\[\]\\<>{}
|
|
75
|
+
text.gsub(/([#\$*_\[\]\\<>{}@`~])/, '\\\\\1')
|
|
76
|
+
.gsub(%r{/(?=[/*])}, "\\\\/")
|
|
77
|
+
.gsub(/-(?=[-?])/, "\\\\-")
|
|
78
|
+
.gsub(%r{^([ \t]*)([=+/-])}, '\\1\\\\\\2')
|
|
79
|
+
.gsub(/^([ \t]*\d+)\.(?=[ \t]|$)/, '\\1\\.')
|
|
69
80
|
end
|
|
70
81
|
|
|
71
82
|
# MARK: - HTML Conversion
|
|
@@ -142,9 +153,14 @@ module TypstRails
|
|
|
142
153
|
# - Headings (`#` → `=`)
|
|
143
154
|
# - Bold (`**text**` → `*text*`)
|
|
144
155
|
# - Italic (`*text*` → `_text_`)
|
|
156
|
+
# - Bold+italic (`***text***` → `*_text_*`)
|
|
145
157
|
# - Links (`[text](url)` → `#link("url")[text]`)
|
|
146
158
|
# - Images (`` → `#image("url")`)
|
|
147
159
|
#
|
|
160
|
+
# Inline code and fenced code blocks pass through untouched. Everything
|
|
161
|
+
# else is escaped, so text such as "#tag", "$5" or "me@example.com" reads
|
|
162
|
+
# as written rather than as Typst code, math or a reference.
|
|
163
|
+
#
|
|
148
164
|
# @param markdown [String, nil] The Markdown text to convert
|
|
149
165
|
# @return [String] Typst-compatible markup, or empty string if markdown is nil
|
|
150
166
|
# @raise [ArgumentError] if markdown is not a String or nil
|
|
@@ -161,6 +177,10 @@ module TypstRails
|
|
|
161
177
|
# markdown_to_typst("**bold** and *italic*")
|
|
162
178
|
# # => "*bold* and _italic_"
|
|
163
179
|
#
|
|
180
|
+
# @example Converting combined bold and italic
|
|
181
|
+
# markdown_to_typst("***important***")
|
|
182
|
+
# # => "*_important_*"
|
|
183
|
+
#
|
|
164
184
|
# @example Converting links
|
|
165
185
|
# markdown_to_typst("[Typst](https://typst.app)")
|
|
166
186
|
# # => "#link(\"https://typst.app\")[Typst]"
|
|
@@ -170,43 +190,7 @@ module TypstRails
|
|
|
170
190
|
return "" if markdown.nil?
|
|
171
191
|
raise ArgumentError, "markdown must be a String" unless markdown.is_a?(String)
|
|
172
192
|
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
# Convert Markdown headers to Typst headers
|
|
176
|
-
# # Title -> = Title
|
|
177
|
-
# ## Subtitle -> == Subtitle
|
|
178
|
-
# etc.
|
|
179
|
-
result.gsub!(/^(#{Regexp.quote("#")}{1,6})\s+(.+)$/) do
|
|
180
|
-
"#{"=" * Regexp.last_match(1).length} #{Regexp.last_match(2)}"
|
|
181
|
-
end
|
|
182
|
-
|
|
183
|
-
# Convert Markdown bold to Typst bold, using placeholder bytes (\x01 text \x02)
|
|
184
|
-
# so the italic pass below doesn't re-convert the resulting *text* markers.
|
|
185
|
-
# **text** or __text__ -> *text*
|
|
186
|
-
result.gsub!(/(\*\*|__)(.+?)\1/, "\x01\\2\x02")
|
|
187
|
-
|
|
188
|
-
# Convert Markdown italic to Typst italic (underscore style)
|
|
189
|
-
# *text* or _text_ -> _text_
|
|
190
|
-
result.gsub!(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/, '_\1_')
|
|
191
|
-
result.gsub!(/(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/, '_\1_')
|
|
192
|
-
|
|
193
|
-
# Replace bold placeholders with Typst bold markers
|
|
194
|
-
result.gsub!("\x01", "*")
|
|
195
|
-
result.gsub!("\x02", "*")
|
|
196
|
-
|
|
197
|
-
# Convert Markdown code to Typst code
|
|
198
|
-
# `code` -> `code` (same in Typst)
|
|
199
|
-
|
|
200
|
-
# Convert Markdown images (must run before links, since 
|
|
201
|
-
# would otherwise be matched by the link pattern below)
|
|
202
|
-
#  -> #image("url")
|
|
203
|
-
result.gsub!(/!\[([^\]]*)\]\(([^)]+)\)/, '#image("\2")')
|
|
204
|
-
|
|
205
|
-
# Convert Markdown links
|
|
206
|
-
# [text](url) -> #link("url")[text]
|
|
207
|
-
result.gsub!(/\[([^\]]+)\]\(([^)]+)\)/, '#link("\2")[\1]')
|
|
208
|
-
|
|
209
|
-
result
|
|
193
|
+
MarkdownConverter.new(markdown).convert
|
|
210
194
|
end
|
|
211
195
|
|
|
212
196
|
# Reads and includes Markdown content, converting it to Typst syntax.
|
|
@@ -247,79 +231,6 @@ module TypstRails
|
|
|
247
231
|
end
|
|
248
232
|
end
|
|
249
233
|
|
|
250
|
-
# MARK: - HTML Sanitization
|
|
251
|
-
|
|
252
|
-
DEFAULT_ALLOWED_TAGS = %w[
|
|
253
|
-
h1 h2 h3 h4 h5 h6 p br strong em u s del ins
|
|
254
|
-
ul ol li blockquote pre code a img table thead
|
|
255
|
-
tbody tr th td
|
|
256
|
-
].freeze
|
|
257
|
-
|
|
258
|
-
DEFAULT_ALLOWED_ATTRIBUTES = %w[href src alt title].freeze
|
|
259
|
-
|
|
260
|
-
# Sanitizes HTML before conversion to prevent XSS attacks.
|
|
261
|
-
#
|
|
262
|
-
# This method removes potentially dangerous tags and attributes from HTML
|
|
263
|
-
# before conversion to Typst. It provides basic XSS protection by:
|
|
264
|
-
# - Removing `<script>` and `<style>` tags
|
|
265
|
-
# - Removing event handler attributes (onclick, onload, etc.)
|
|
266
|
-
# - Optionally filtering to allowed tags and attributes
|
|
267
|
-
#
|
|
268
|
-
# @param html [String, nil] The HTML to sanitize
|
|
269
|
-
# @param allowed_tags [Array<String>, nil] List of allowed HTML tags (uses defaults if nil)
|
|
270
|
-
# @param allowed_attributes [Array<String>, nil] List of allowed attributes (uses defaults if nil)
|
|
271
|
-
# @return [String] Sanitized HTML, or empty string if html is nil
|
|
272
|
-
# @raise [ArgumentError] if html is not a String or nil
|
|
273
|
-
#
|
|
274
|
-
# @example Basic sanitization
|
|
275
|
-
# sanitize_html("<script>alert('xss')</script><p>Safe content</p>")
|
|
276
|
-
# # => "<p>Safe content</p>"
|
|
277
|
-
#
|
|
278
|
-
# @example Removing event handlers
|
|
279
|
-
# sanitize_html('<div onclick="evil()">Click</div>')
|
|
280
|
-
# # => "<div>Click</div>"
|
|
281
|
-
#
|
|
282
|
-
# @example Custom allowed tags
|
|
283
|
-
# sanitize_html("<p>Text</p><img src='x'>", allowed_tags: %w[p])
|
|
284
|
-
# # => "<p>Text</p>"
|
|
285
|
-
#
|
|
286
|
-
# @note This is basic sanitization. For production use with untrusted HTML,
|
|
287
|
-
# consider using a dedicated sanitization library like Loofah or Sanitize
|
|
288
|
-
def sanitize_html(html, allowed_tags: nil, allowed_attributes: nil)
|
|
289
|
-
return "" if html.nil?
|
|
290
|
-
raise ArgumentError, "html must be a String" unless html.is_a?(String)
|
|
291
|
-
|
|
292
|
-
allowed_tags ||= DEFAULT_ALLOWED_TAGS
|
|
293
|
-
allowed_attributes ||= DEFAULT_ALLOWED_ATTRIBUTES
|
|
294
|
-
|
|
295
|
-
fragment = Nokogiri::HTML5.fragment(html)
|
|
296
|
-
strip_disallowed_nodes(fragment, allowed_tags, allowed_attributes)
|
|
297
|
-
fragment.to_html
|
|
298
|
-
end
|
|
299
|
-
|
|
300
|
-
private
|
|
301
|
-
|
|
302
|
-
# Recursively removes tags not in +allowed_tags+ (keeping their text content)
|
|
303
|
-
# and strips attributes not in +allowed_attributes+ from the tags that remain.
|
|
304
|
-
def strip_disallowed_nodes(node, allowed_tags, allowed_attributes)
|
|
305
|
-
node.children.each do |child|
|
|
306
|
-
next strip_disallowed_nodes(child, allowed_tags, allowed_attributes) unless child.element?
|
|
307
|
-
|
|
308
|
-
unless allowed_tags.include?(child.name.downcase)
|
|
309
|
-
child.replace(child.children)
|
|
310
|
-
next strip_disallowed_nodes(node, allowed_tags, allowed_attributes)
|
|
311
|
-
end
|
|
312
|
-
|
|
313
|
-
child.attribute_nodes.each do |attr|
|
|
314
|
-
attr.remove unless allowed_attributes.include?(attr.name.downcase)
|
|
315
|
-
end
|
|
316
|
-
|
|
317
|
-
strip_disallowed_nodes(child, allowed_tags, allowed_attributes)
|
|
318
|
-
end
|
|
319
|
-
end
|
|
320
|
-
|
|
321
|
-
public
|
|
322
|
-
|
|
323
234
|
# MARK: - URL Encoding
|
|
324
235
|
|
|
325
236
|
# URL-encodes text for safe use in links.
|
|
@@ -352,3 +263,6 @@ module TypstRails
|
|
|
352
263
|
end
|
|
353
264
|
end
|
|
354
265
|
end
|
|
266
|
+
|
|
267
|
+
# Loaded after Helpers is defined, since the converter includes it.
|
|
268
|
+
require "typst_rails/markdown_converter"
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module TypstRails
|
|
4
|
+
# Converts one Markdown document to Typst markup. Backs
|
|
5
|
+
# {Helpers#markdown_to_typst}; each conversion uses a new instance, so the
|
|
6
|
+
# state it keeps between passes never outlives the call.
|
|
7
|
+
#
|
|
8
|
+
# Markup the conversion writes (headings, list markers, links, images,
|
|
9
|
+
# code) is stashed behind placeholders as it is made. The text left over is
|
|
10
|
+
# escaped with {Helpers#escape_typst}, so it reads as written, and the
|
|
11
|
+
# stashed markup is then put back.
|
|
12
|
+
#
|
|
13
|
+
# @api private
|
|
14
|
+
class MarkdownConverter
|
|
15
|
+
include Helpers
|
|
16
|
+
|
|
17
|
+
# MARK: - Placeholders
|
|
18
|
+
#
|
|
19
|
+
# The conversion rewrites emphasis in several regex passes. Each pass
|
|
20
|
+
# must not re-match markers written by an earlier one, so markers are
|
|
21
|
+
# staged as these private sentinel bytes and swapped for real Typst syntax
|
|
22
|
+
# at the very end.
|
|
23
|
+
#
|
|
24
|
+
# They are drawn from the Unicode private use area rather than plain
|
|
25
|
+
# control bytes so they cannot collide with anything a text pipeline is
|
|
26
|
+
# likely to emit. Any that do appear in the source are held aside by
|
|
27
|
+
# {#protect_placeholder_bytes} and put back verbatim afterwards.
|
|
28
|
+
BOLD_OPEN = "\u{E000}"
|
|
29
|
+
BOLD_CLOSE = "\u{E001}"
|
|
30
|
+
ITALIC_OPEN = "\u{E002}"
|
|
31
|
+
ITALIC_CLOSE = "\u{E003}"
|
|
32
|
+
|
|
33
|
+
# Sentinel standing in for a placeholder byte that was already present in
|
|
34
|
+
# the caller's input.
|
|
35
|
+
LITERAL_PLACEHOLDER = "\u{E004}"
|
|
36
|
+
|
|
37
|
+
# Delimit the index of a stashed token: Typst markup the conversion has
|
|
38
|
+
# already written, such as a heading marker, a link or a code span,
|
|
39
|
+
# held aside so the escaping pass leaves it intact.
|
|
40
|
+
STASH_OPEN = "\u{E005}"
|
|
41
|
+
STASH_CLOSE = "\u{E006}"
|
|
42
|
+
|
|
43
|
+
# Follows a stashed embedded expression (#link, #image). Typst would read
|
|
44
|
+
# a "(" or a "." and a name straight after one as part of the expression,
|
|
45
|
+
# so there it becomes a ";" to end the expression, and elsewhere it is
|
|
46
|
+
# dropped.
|
|
47
|
+
EXPRESSION_END = "\u{E007}"
|
|
48
|
+
|
|
49
|
+
# All sentinels this class reserves, in a single character class.
|
|
50
|
+
PLACEHOLDER_PATTERN = /[\u{E000}-\u{E007}]/.freeze
|
|
51
|
+
|
|
52
|
+
STASH_PATTERN = /\u{E005}(\d+)\u{E006}/.freeze
|
|
53
|
+
|
|
54
|
+
# Fenced code blocks (``` or ~~~) and single-line inline code spans.
|
|
55
|
+
# Fences come first so their backticks are not read as inline spans.
|
|
56
|
+
CODE_PATTERN = /^(`{3,}|~{3,})[^\n]*\n.*?^\1[ \t]*$|(`+)[^`\n][^\n]*?\2(?!`)/m.freeze
|
|
57
|
+
|
|
58
|
+
# A Markdown backslash escape: a backslash before ASCII punctuation, or at
|
|
59
|
+
# the end of a line, where it is a hard line break.
|
|
60
|
+
BACKSLASH_ESCAPE_PATTERN = %r{\\([!-/:-@\[-`\{-~])|\\(?=\r?\n)}.freeze
|
|
61
|
+
|
|
62
|
+
HEADING_PATTERN = /^(\#{1,6})[ \t]+(.+)$/.freeze
|
|
63
|
+
|
|
64
|
+
# Bullets (-, +, *) and ordered items (1. or 1)) followed by whitespace.
|
|
65
|
+
LIST_MARKER_PATTERN = /^([ \t]*)([-+*]|\d+[.)])(?=[ \t])/.freeze
|
|
66
|
+
|
|
67
|
+
# A link destination with an optional quoted title, which Typst has no
|
|
68
|
+
# place for and is dropped.
|
|
69
|
+
LINK_TARGET = /\(\s*(\S+?)(?:\s+"[^"]*")?\s*\)/.freeze
|
|
70
|
+
IMAGE_PATTERN = /!\[[^\]]*\]#{LINK_TARGET}/.freeze
|
|
71
|
+
LINK_PATTERN = /\[([^\]]+)\]#{LINK_TARGET}/.freeze
|
|
72
|
+
AUTOLINK_PATTERN = /<((?:https?|mailto):[^\s<>]+)>/.freeze
|
|
73
|
+
|
|
74
|
+
# One piece of stashed markup, and the source text it came from, which is
|
|
75
|
+
# what a link destination needs when the piece turns up inside one.
|
|
76
|
+
StashedToken = Struct.new(:markup, :literal)
|
|
77
|
+
|
|
78
|
+
private_constant :BOLD_OPEN, :BOLD_CLOSE, :ITALIC_OPEN, :ITALIC_CLOSE, :LITERAL_PLACEHOLDER,
|
|
79
|
+
:STASH_OPEN, :STASH_CLOSE, :EXPRESSION_END, :PLACEHOLDER_PATTERN, :STASH_PATTERN,
|
|
80
|
+
:CODE_PATTERN, :BACKSLASH_ESCAPE_PATTERN, :HEADING_PATTERN, :LIST_MARKER_PATTERN,
|
|
81
|
+
:LINK_TARGET, :IMAGE_PATTERN, :LINK_PATTERN, :AUTOLINK_PATTERN, :StashedToken
|
|
82
|
+
|
|
83
|
+
# @param markdown [String] the Markdown source
|
|
84
|
+
def initialize(markdown)
|
|
85
|
+
super()
|
|
86
|
+
@markdown = markdown
|
|
87
|
+
@tokens = []
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# @return [String] Typst-compatible markup
|
|
91
|
+
def convert
|
|
92
|
+
# The passes below use placeholder bytes to mark text they have already
|
|
93
|
+
# handled. Any such bytes already in the source would be
|
|
94
|
+
# indistinguishable from our own, so they are held aside and restored at
|
|
95
|
+
# the end.
|
|
96
|
+
result = protect_placeholder_bytes(@markdown.dup)
|
|
97
|
+
|
|
98
|
+
result = stash_literal_markdown(result)
|
|
99
|
+
result = stash_line_markers(result)
|
|
100
|
+
result = stash_links(result)
|
|
101
|
+
result = convert_inline_markdown(result)
|
|
102
|
+
|
|
103
|
+
restore_placeholder_bytes(restore_stash(result))
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
private
|
|
107
|
+
|
|
108
|
+
# MARK: - Markdown conversion passes
|
|
109
|
+
|
|
110
|
+
# Holds aside the parts of the source whose contents are literal: code,
|
|
111
|
+
# which is the same in Typst as in Markdown, and backslash escapes, which
|
|
112
|
+
# stand for their character.
|
|
113
|
+
def stash_literal_markdown(text)
|
|
114
|
+
text = text.gsub(CODE_PATTERN) { |code| stash(code, code) }
|
|
115
|
+
|
|
116
|
+
text.gsub(BACKSLASH_ESCAPE_PATTERN) do
|
|
117
|
+
char = Regexp.last_match(1)
|
|
118
|
+
next stash("\\", "") unless char
|
|
119
|
+
|
|
120
|
+
stash("\\#{char}", char)
|
|
121
|
+
end
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
# Converts the markers that only mean something at the start of a line:
|
|
125
|
+
# headings, and list items. Markdown bullets all become Typst's "-", since
|
|
126
|
+
# "+" would make a numbered item.
|
|
127
|
+
def stash_line_markers(text)
|
|
128
|
+
text = text.gsub(HEADING_PATTERN) do
|
|
129
|
+
heading = "#{"=" * Regexp.last_match(1).length} "
|
|
130
|
+
"#{stash(heading, heading)}#{Regexp.last_match(2)}"
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
text.gsub(LIST_MARKER_PATTERN) do
|
|
134
|
+
indent = Regexp.last_match(1)
|
|
135
|
+
marker = Regexp.last_match(2)
|
|
136
|
+
bullet = marker.match?(/\A\d/) ? "#{marker.to_i}." : "-"
|
|
137
|
+
"#{indent}#{stash(bullet, marker)}"
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# Converts images and links, writing their destinations as Typst string
|
|
142
|
+
# literals. Images go first, since  also matches the link
|
|
143
|
+
# pattern, and so an image can sit inside a link's text.
|
|
144
|
+
def stash_links(text)
|
|
145
|
+
text = text.gsub(AUTOLINK_PATTERN) do
|
|
146
|
+
stash_expression("#link(#{typst_string(Regexp.last_match(1))})")
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
text = text.gsub(IMAGE_PATTERN) do
|
|
150
|
+
stash_expression("#image(#{typst_string(Regexp.last_match(1))})")
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
text.gsub(LINK_PATTERN) do
|
|
154
|
+
body = convert_inline_markdown(Regexp.last_match(1))
|
|
155
|
+
stash_expression("#link(#{typst_string(Regexp.last_match(2))})[#{body}]")
|
|
156
|
+
end
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# Converts emphasis and escapes everything else, so whatever is left of
|
|
160
|
+
# the Markdown reads as literal text in Typst.
|
|
161
|
+
def convert_inline_markdown(text)
|
|
162
|
+
# Convert combined bold+italic first: ***text*** and ___text___ are a
|
|
163
|
+
# single Markdown token, and letting the bold pass see them would consume
|
|
164
|
+
# only two of the three markers and strand the leftover one mid-word.
|
|
165
|
+
# ***text*** -> *_text_*
|
|
166
|
+
#
|
|
167
|
+
# As in Markdown, an opening marker must be followed, and a closing one
|
|
168
|
+
# preceded, by non-whitespace, so "2 * 3 * 4" is not emphasis.
|
|
169
|
+
text = text.gsub(/(\*\*\*|___)(?=\S)(.+?)(?<=\S)\1/, "#{BOLD_OPEN}#{ITALIC_OPEN}\\2#{ITALIC_CLOSE}#{BOLD_CLOSE}")
|
|
170
|
+
|
|
171
|
+
# **text** or __text__ -> *text*
|
|
172
|
+
text = text.gsub(/(\*\*|__)(?=\S)(.+?)(?<=\S)\1/, "#{BOLD_OPEN}\\2#{BOLD_CLOSE}")
|
|
173
|
+
|
|
174
|
+
# *text* or _text_ -> _text_
|
|
175
|
+
text = text.gsub(/(?<!\*)\*(?![\s*])(.+?)(?<![\s*])\*(?!\*)/, "#{ITALIC_OPEN}\\1#{ITALIC_CLOSE}")
|
|
176
|
+
text = text.gsub(/(?<!_)_(?![\s_])(.+?)(?<![\s_])_(?!_)/, "#{ITALIC_OPEN}\\1#{ITALIC_CLOSE}")
|
|
177
|
+
|
|
178
|
+
# A literal slash before a bold marker would open a /* comment.
|
|
179
|
+
text = escape_typst(text).gsub(%r{/(?=#{BOLD_OPEN}|#{BOLD_CLOSE})}, "\\\\/")
|
|
180
|
+
|
|
181
|
+
text.tr("#{BOLD_OPEN}#{BOLD_CLOSE}#{ITALIC_OPEN}#{ITALIC_CLOSE}", "**__")
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# @return [String] a placeholder for +markup+, which {#restore_stash}
|
|
185
|
+
# swaps back in
|
|
186
|
+
def stash(markup, literal)
|
|
187
|
+
@tokens << StashedToken.new(markup, literal)
|
|
188
|
+
"#{STASH_OPEN}#{@tokens.length - 1}#{STASH_CLOSE}"
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
def stash_expression(markup)
|
|
192
|
+
stash("#{markup}#{EXPRESSION_END}", markup)
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
# Puts stashed markup back, then ends each embedded expression where the
|
|
196
|
+
# text after it would otherwise continue it.
|
|
197
|
+
def restore_stash(text)
|
|
198
|
+
expand_stash(text).gsub(/#{EXPRESSION_END}(?=\(|\.[\p{L}_])/, ";").delete(EXPRESSION_END)
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
# Swaps placeholders for their markup, including any stashed inside other
|
|
202
|
+
# markup, such as code in a link's text.
|
|
203
|
+
def expand_stash(text)
|
|
204
|
+
text.gsub(STASH_PATTERN) { expand_stash(@tokens[Regexp.last_match(1).to_i].markup) }
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# Writes +text+ as a Typst string literal. Stashed pieces inside it, such
|
|
208
|
+
# as a backslash escape in a URL, stand for their source text there.
|
|
209
|
+
def typst_string(text)
|
|
210
|
+
literal = text.gsub(STASH_PATTERN) { @tokens[Regexp.last_match(1).to_i].literal }
|
|
211
|
+
|
|
212
|
+
"\"#{literal.gsub(/[\\"]/) { |char| "\\#{char}" }}\""
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
# MARK: - Placeholder handling
|
|
216
|
+
|
|
217
|
+
# Stashes any of this class's sentinel characters that the caller's input
|
|
218
|
+
# already contained, so the emphasis passes cannot mistake them for markers
|
|
219
|
+
# they wrote themselves.
|
|
220
|
+
#
|
|
221
|
+
# Each occurrence is replaced by LITERAL_PLACEHOLDER and its original
|
|
222
|
+
# character recorded, in order, on +@placeholder_literals+.
|
|
223
|
+
#
|
|
224
|
+
# @param text [String] the source text
|
|
225
|
+
# @return [String] the text with pre-existing sentinels stashed
|
|
226
|
+
def protect_placeholder_bytes(text)
|
|
227
|
+
@placeholder_literals = []
|
|
228
|
+
return text unless text.match?(PLACEHOLDER_PATTERN)
|
|
229
|
+
|
|
230
|
+
text.gsub(PLACEHOLDER_PATTERN) do |char|
|
|
231
|
+
@placeholder_literals << char
|
|
232
|
+
LITERAL_PLACEHOLDER
|
|
233
|
+
end
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
# Puts back the characters stashed by {#protect_placeholder_bytes}, in the
|
|
237
|
+
# order they were found.
|
|
238
|
+
#
|
|
239
|
+
# @param text [String] the converted text
|
|
240
|
+
# @return [String] the text with the caller's original characters restored
|
|
241
|
+
def restore_placeholder_bytes(text)
|
|
242
|
+
return text if @placeholder_literals.empty?
|
|
243
|
+
|
|
244
|
+
index = -1
|
|
245
|
+
text.gsub(LITERAL_PLACEHOLDER) { @placeholder_literals[index += 1] }
|
|
246
|
+
end
|
|
247
|
+
end
|
|
248
|
+
end
|
|
@@ -1,18 +1,65 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "typst_rails/renderer"
|
|
4
|
+
require "typst_rails/erb_source"
|
|
5
|
+
|
|
3
6
|
module TypstRails
|
|
4
|
-
# Integration for Rage framework
|
|
7
|
+
# Integration for the Rage framework.
|
|
8
|
+
#
|
|
9
|
+
# Rage controllers render JSON or plain text and have no template handlers,
|
|
10
|
+
# so the integration adds a controller helper rather than a `.typ` handler.
|
|
5
11
|
module RageIntegration
|
|
6
|
-
|
|
7
|
-
|
|
12
|
+
# Mirrors the `assigns` reader Renderer expects from a view context, so
|
|
13
|
+
# locals get the same JSON conversion (models, dates) as in Rails.
|
|
14
|
+
ViewContext = Struct.new(:assigns)
|
|
8
15
|
|
|
9
|
-
|
|
16
|
+
# Mixed into RageController::API by {RageIntegration.setup}. Include it
|
|
17
|
+
# yourself if typst-rails loads before Rage's controllers are defined.
|
|
18
|
+
#
|
|
19
|
+
# @example
|
|
20
|
+
# class ReportsController < RageController::API
|
|
21
|
+
# def show
|
|
22
|
+
# @title = "Monthly Report"
|
|
23
|
+
# render_typst "app/views/reports/monthly.typ", { total: 42 }
|
|
24
|
+
# end
|
|
25
|
+
# end
|
|
26
|
+
module ControllerHelpers
|
|
27
|
+
include ::TypstRails::Helpers
|
|
10
28
|
|
|
11
|
-
#
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
29
|
+
# Renders a Typst template and responds with the PDF.
|
|
30
|
+
#
|
|
31
|
+
# The template runs through ERB first, in the controller's scope, with
|
|
32
|
+
# +locals+ as local variables; +locals+ are also written to
|
|
33
|
+
# typst_data.json for templates that read it.
|
|
34
|
+
#
|
|
35
|
+
# @param template [String] path to the .typ file
|
|
36
|
+
# @param locals [Hash] data for the template
|
|
37
|
+
# @param status [Integer, Symbol, nil] response status
|
|
38
|
+
# @return [void]
|
|
39
|
+
# @raise [TypstRails::Error] if compilation fails
|
|
40
|
+
def render_typst(template, locals = {}, status: nil, **extra)
|
|
41
|
+
# Ruby 2.7 binds a trailing symbol-keyed locals hash as keywords;
|
|
42
|
+
# fold those back into locals.
|
|
43
|
+
locals = locals.merge(extra) unless extra.empty?
|
|
44
|
+
source = ::TypstRails::ErbSource.render(File.read(template), self, locals)
|
|
45
|
+
pdf_data = ::TypstRails::Renderer.new(source).render(ViewContext.new(locals), locals)
|
|
46
|
+
|
|
47
|
+
# Rage's render(plain:) sets text/plain, so override it afterwards.
|
|
48
|
+
render plain: pdf_data, status: status
|
|
49
|
+
headers["content-type"] = "application/pdf"
|
|
15
50
|
end
|
|
16
51
|
end
|
|
52
|
+
|
|
53
|
+
# Adds {ControllerHelpers} to RageController::API, if it is loaded.
|
|
54
|
+
#
|
|
55
|
+
# @return [void]
|
|
56
|
+
def self.setup
|
|
57
|
+
return unless defined?(::Rage)
|
|
58
|
+
return unless defined?(::RageController::API)
|
|
59
|
+
return if ::RageController::API.include?(ControllerHelpers)
|
|
60
|
+
|
|
61
|
+
::RageController::API.include(ControllerHelpers)
|
|
62
|
+
nil
|
|
63
|
+
end
|
|
17
64
|
end
|
|
18
65
|
end
|
data/lib/typst_rails/railtie.rb
CHANGED
|
@@ -11,6 +11,13 @@ module TypstRails
|
|
|
11
11
|
end
|
|
12
12
|
end
|
|
13
13
|
|
|
14
|
+
initializer "typst_rails.view_helpers" do
|
|
15
|
+
ActiveSupport.on_load(:action_view) do
|
|
16
|
+
require "typst_rails/view_helpers"
|
|
17
|
+
include TypstRails::ViewHelpers
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
|
|
14
21
|
rake_tasks do
|
|
15
22
|
load File.expand_path("../tasks/typst_rails/tasks.rake", __dir__)
|
|
16
23
|
end
|
data/lib/typst_rails/renderer.rb
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require "
|
|
3
|
+
require "tmpdir"
|
|
4
|
+
require "fileutils"
|
|
4
5
|
require "json"
|
|
5
6
|
require "typst_rails/helpers"
|
|
6
7
|
require "typst_rails/backends"
|
|
@@ -53,8 +54,15 @@ module TypstRails
|
|
|
53
54
|
# Maximum source size (10MB) to prevent memory issues
|
|
54
55
|
MAX_SOURCE_SIZE = 10 * 1024 * 1024
|
|
55
56
|
|
|
56
|
-
#
|
|
57
|
-
|
|
57
|
+
# Name of the JSON file holding template data, read in Typst with
|
|
58
|
+
# `json("typst_data.json")`. It is written only when the template
|
|
59
|
+
# source mentions it.
|
|
60
|
+
DATA_FILE_NAME = "typst_data.json"
|
|
61
|
+
|
|
62
|
+
# Holds the filesystem paths used during a single compilation run. Each
|
|
63
|
+
# run gets its own directory so concurrent renders never share a
|
|
64
|
+
# typst_data.json.
|
|
65
|
+
TempPaths = Struct.new(:root, :dir, :typ_path, :data_file_path)
|
|
58
66
|
|
|
59
67
|
# MARK: - Attributes
|
|
60
68
|
|
|
@@ -149,7 +157,7 @@ module TypstRails
|
|
|
149
157
|
paths = TempPaths.new
|
|
150
158
|
begin
|
|
151
159
|
write_typst_source_file(paths, typst_source)
|
|
152
|
-
write_typst_data_file(paths, data)
|
|
160
|
+
write_typst_data_file(paths, data) if reads_data_file?(typst_source)
|
|
153
161
|
run_typst_compiler(paths)
|
|
154
162
|
rescue Error
|
|
155
163
|
raise
|
|
@@ -163,22 +171,39 @@ module TypstRails
|
|
|
163
171
|
end
|
|
164
172
|
|
|
165
173
|
def write_typst_source_file(paths, typst_source)
|
|
166
|
-
#
|
|
167
|
-
#
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
paths.
|
|
172
|
-
paths.
|
|
173
|
-
paths.
|
|
174
|
+
# Each run gets a private directory holding the template and its data,
|
|
175
|
+
# so json("typst_data.json") resolves next to the template. Typst only
|
|
176
|
+
# compiles files inside its root, so with a configured root the
|
|
177
|
+
# directory is created there; otherwise it doubles as the root.
|
|
178
|
+
paths.root = configured_root_path
|
|
179
|
+
paths.dir = make_run_dir(paths.root)
|
|
180
|
+
paths.root ||= paths.dir
|
|
181
|
+
paths.typ_path = File.join(paths.dir, "template.typ")
|
|
182
|
+
File.binwrite(paths.typ_path, typst_source)
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
def make_run_dir(root)
|
|
186
|
+
return Dir.mktmpdir("typst_rails_") unless root
|
|
187
|
+
|
|
188
|
+
begin
|
|
189
|
+
Dir.mktmpdir("typst_rails_", root)
|
|
190
|
+
rescue SystemCallError => e
|
|
191
|
+
raise Error, "Cannot create a working directory in default_root_path #{root}: #{e.message}"
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
# Assigns can hold whole models, so they are written to disk only for
|
|
196
|
+
# templates that load them.
|
|
197
|
+
def reads_data_file?(typst_source)
|
|
198
|
+
typst_source.include?(DATA_FILE_NAME)
|
|
174
199
|
end
|
|
175
200
|
|
|
176
201
|
def write_typst_data_file(paths, data)
|
|
177
202
|
return if data.nil? || data.empty?
|
|
178
203
|
|
|
179
|
-
#
|
|
204
|
+
# Write the JSON data file next to the Typst source.
|
|
180
205
|
# The Typst template would then use `json("typst_data.json")` to load this data.
|
|
181
|
-
paths.data_file_path = File.join(paths.dir,
|
|
206
|
+
paths.data_file_path = File.join(paths.dir, DATA_FILE_NAME)
|
|
182
207
|
File.write(paths.data_file_path, data.to_json)
|
|
183
208
|
rescue JSON::GeneratorError => e
|
|
184
209
|
raise Error, "Failed to serialize data to JSON: #{e.message}"
|
|
@@ -188,7 +213,7 @@ module TypstRails
|
|
|
188
213
|
|
|
189
214
|
def run_typst_compiler(paths)
|
|
190
215
|
backend = Backends::Registry.resolve(configured_backend)
|
|
191
|
-
backend.compile(paths.
|
|
216
|
+
backend.compile(paths.typ_path, paths.root)
|
|
192
217
|
rescue Error => e
|
|
193
218
|
log_error(e.message)
|
|
194
219
|
raise
|
|
@@ -204,16 +229,18 @@ module TypstRails
|
|
|
204
229
|
TypstRails.configuration&.backend
|
|
205
230
|
end
|
|
206
231
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
232
|
+
# @return [String, nil] the configured Typst root as an absolute path
|
|
233
|
+
def configured_root_path
|
|
234
|
+
return nil unless TypstRails.respond_to?(:configuration)
|
|
235
|
+
|
|
236
|
+
root = TypstRails.configuration&.default_root_path
|
|
237
|
+
root && File.expand_path(root.to_s)
|
|
213
238
|
end
|
|
214
239
|
|
|
215
|
-
def
|
|
216
|
-
|
|
240
|
+
def cleanup_temp_paths(paths)
|
|
241
|
+
return unless paths.dir
|
|
242
|
+
|
|
243
|
+
rescue_cleanup_errors("temp directory") { FileUtils.remove_entry(paths.dir) }
|
|
217
244
|
end
|
|
218
245
|
|
|
219
246
|
def rescue_cleanup_errors(description)
|
|
@@ -347,7 +374,10 @@ module TypstRails
|
|
|
347
374
|
# @raise [NoMethodError] if neither the renderer nor view_context respond to the method
|
|
348
375
|
#
|
|
349
376
|
# @see #respond_to_missing?
|
|
350
|
-
|
|
377
|
+
#
|
|
378
|
+
# ruby2_keywords keeps keyword arguments intact on every supported Ruby;
|
|
379
|
+
# an explicit **kwargs would pass a stray empty hash on Ruby 2.7.
|
|
380
|
+
ruby2_keywords def method_missing(method_name, *args, &block)
|
|
351
381
|
if @view_context.respond_to?(method_name)
|
|
352
382
|
@view_context.public_send(method_name, *args, &block)
|
|
353
383
|
else
|
|
@@ -11,12 +11,17 @@ module TypstRails
|
|
|
11
11
|
return unless defined?(::Sinatra)
|
|
12
12
|
|
|
13
13
|
require "typst_rails/renderer"
|
|
14
|
+
require "typst_rails/erb_source"
|
|
14
15
|
|
|
15
16
|
# Extend Sinatra with Typst rendering capabilities
|
|
16
17
|
::Sinatra::Base.class_eval do
|
|
17
|
-
|
|
18
|
+
include ::TypstRails::Helpers
|
|
19
|
+
|
|
20
|
+
# Renders a Typst template to PDF. The template runs through ERB
|
|
21
|
+
# first, in the route's scope, with +locals+ as local variables;
|
|
22
|
+
# +locals+ are also written to typst_data.json.
|
|
18
23
|
def typst(template, locals = {}, _options = {})
|
|
19
|
-
typst_source = File.read(template)
|
|
24
|
+
typst_source = ::TypstRails::ErbSource.render(File.read(template), self, locals)
|
|
20
25
|
renderer = ::TypstRails::Renderer.new(typst_source)
|
|
21
26
|
|
|
22
27
|
# Sinatra doesn't have the same view context as Rails,
|
data/lib/typst_rails/version.rb
CHANGED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "erb"
|
|
4
|
+
require "typst_rails/helpers"
|
|
5
|
+
|
|
6
|
+
module TypstRails
|
|
7
|
+
# {Helpers} as mixed into ActionView, so `.typ` templates can call
|
|
8
|
+
# `escape_typst`, `markdown_to_typst`, and the rest directly.
|
|
9
|
+
#
|
|
10
|
+
# The Railtie includes this module into ActionView::Base, which every view
|
|
11
|
+
# shares, HTML views included.
|
|
12
|
+
#
|
|
13
|
+
# @example In app/views/reports/monthly.typ
|
|
14
|
+
# = <%= escape_typst(@title) %>
|
|
15
|
+
module ViewHelpers
|
|
16
|
+
include Helpers
|
|
17
|
+
|
|
18
|
+
# ActionView::Base already includes ERB::Util#url_encode, which encodes a
|
|
19
|
+
# space as "%20"; {Helpers#url_encode} would encode it as "+". Keep the
|
|
20
|
+
# ActionView behavior so existing HTML views are unaffected.
|
|
21
|
+
#
|
|
22
|
+
# @param text [String, nil]
|
|
23
|
+
# @return [String]
|
|
24
|
+
def url_encode(text)
|
|
25
|
+
ERB::Util.url_encode(text)
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
data/lib/typst_rails.rb
CHANGED
|
@@ -87,7 +87,11 @@ module TypstRails
|
|
|
87
87
|
# @return [String] Path to the Typst executable (defaults to "typst" in PATH)
|
|
88
88
|
attr_accessor :typst_executable_path
|
|
89
89
|
|
|
90
|
-
# @return [String, nil]
|
|
90
|
+
# @return [String, Pathname, nil] Typst root directory. When set, templates
|
|
91
|
+
# compile inside it, so they can load files beneath it with root-relative
|
|
92
|
+
# paths such as `image("/images/logo.png")`. The directory must be
|
|
93
|
+
# writable: each render creates a short-lived working directory in it.
|
|
94
|
+
# When nil, each render uses a private directory under Dir.tmpdir.
|
|
91
95
|
attr_accessor :default_root_path
|
|
92
96
|
|
|
93
97
|
# @return [Symbol, TypstRails::Backends::Base] Which compilation backend to use.
|
|
@@ -101,7 +105,7 @@ module TypstRails
|
|
|
101
105
|
#
|
|
102
106
|
# Default values:
|
|
103
107
|
# - `typst_executable_path`: "typst" (assumes typst is in PATH)
|
|
104
|
-
# - `default_root_path`: nil (
|
|
108
|
+
# - `default_root_path`: nil (each render gets a private temporary root)
|
|
105
109
|
# - `backend`: `:auto` (prefer the `typst` gem, fall back to the CLI)
|
|
106
110
|
#
|
|
107
111
|
# @return [Configuration] A new configuration instance
|
|
@@ -121,7 +125,7 @@ module TypstRails
|
|
|
121
125
|
#
|
|
122
126
|
# Ensures that:
|
|
123
127
|
# - typst_executable_path is a non-empty string
|
|
124
|
-
# - default_root_path (if set) is a
|
|
128
|
+
# - default_root_path (if set) is a String or Pathname
|
|
125
129
|
#
|
|
126
130
|
# @return [true] if configuration is valid
|
|
127
131
|
# @raise [ArgumentError] if typst_executable_path is invalid
|
|
@@ -136,8 +140,8 @@ module TypstRails
|
|
|
136
140
|
|
|
137
141
|
raise ArgumentError, "typst_executable_path cannot be nil or empty" if typst_executable_path.empty?
|
|
138
142
|
|
|
139
|
-
if default_root_path && !default_root_path.is_a?(String)
|
|
140
|
-
raise ArgumentError, "default_root_path must be a String or nil"
|
|
143
|
+
if default_root_path && !default_root_path.is_a?(String) && !default_root_path.respond_to?(:to_path)
|
|
144
|
+
raise ArgumentError, "default_root_path must be a String, Pathname, or nil"
|
|
141
145
|
end
|
|
142
146
|
|
|
143
147
|
true
|
metadata
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: typst-rails
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.1
|
|
4
|
+
version: 0.2.1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- David J. Berube
|
|
8
|
+
autorequire:
|
|
8
9
|
bindir: exe
|
|
9
10
|
cert_chain: []
|
|
10
|
-
date:
|
|
11
|
+
date: 2026-11-14 00:00:00.000000000 Z
|
|
11
12
|
dependencies:
|
|
12
13
|
- !ruby/object:Gem::Dependency
|
|
13
14
|
name: nokogiri
|
|
@@ -186,14 +187,17 @@ files:
|
|
|
186
187
|
- lib/typst_rails/backends/cli.rb
|
|
187
188
|
- lib/typst_rails/backends/gem.rb
|
|
188
189
|
- lib/typst_rails/backends/registry.rb
|
|
190
|
+
- lib/typst_rails/erb_source.rb
|
|
189
191
|
- lib/typst_rails/framework_detection.rb
|
|
190
192
|
- lib/typst_rails/handler.rb
|
|
191
193
|
- lib/typst_rails/helpers.rb
|
|
194
|
+
- lib/typst_rails/markdown_converter.rb
|
|
192
195
|
- lib/typst_rails/rage_integration.rb
|
|
193
196
|
- lib/typst_rails/railtie.rb
|
|
194
197
|
- lib/typst_rails/renderer.rb
|
|
195
198
|
- lib/typst_rails/sinatra_integration.rb
|
|
196
199
|
- lib/typst_rails/version.rb
|
|
200
|
+
- lib/typst_rails/view_helpers.rb
|
|
197
201
|
homepage: https://github.com/durable-oss/typst-rails
|
|
198
202
|
licenses:
|
|
199
203
|
- MIT
|
|
@@ -205,6 +209,7 @@ metadata:
|
|
|
205
209
|
bug_tracker_uri: https://github.com/durable-oss/typst-rails/issues
|
|
206
210
|
documentation_uri: https://rubydoc.info/gems/typst-rails
|
|
207
211
|
rubygems_mfa_required: 'true'
|
|
212
|
+
post_install_message:
|
|
208
213
|
rdoc_options: []
|
|
209
214
|
require_paths:
|
|
210
215
|
- lib
|
|
@@ -219,7 +224,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
219
224
|
- !ruby/object:Gem::Version
|
|
220
225
|
version: '0'
|
|
221
226
|
requirements: []
|
|
222
|
-
rubygems_version: 3.
|
|
227
|
+
rubygems_version: 3.3.27
|
|
228
|
+
signing_key:
|
|
223
229
|
specification_version: 4
|
|
224
230
|
summary: Typst typesetting integration for Ruby applications
|
|
225
231
|
test_files: []
|