typst-rails 0.2.1 → 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.
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "typst_rails/diagnostics"
4
+
5
+ module TypstRails
6
+ # Error class for Typst-related errors.
7
+ #
8
+ # Raised when Typst compilation fails, when files cannot be created,
9
+ # or when other Typst-specific errors occur during rendering. Compilation
10
+ # failures raise the {CompileError} subclass, which carries Typst's
11
+ # diagnostics.
12
+ #
13
+ # @example Handling Typst errors
14
+ # begin
15
+ # renderer.render(nil, data)
16
+ # rescue TypstRails::Error => e
17
+ # Rails.logger.error "Typst compilation failed: #{e.message}"
18
+ # render plain: "PDF generation failed", status: 500
19
+ # end
20
+ class Error < StandardError; end
21
+
22
+ # Raised when Typst rejects a template.
23
+ #
24
+ # The message names the template and the location of the first error,
25
+ # followed by Typst's own output with the render's temporary paths
26
+ # replaced by the template's name. The parsed diagnostics are available
27
+ # as attributes.
28
+ #
29
+ # Line numbers count lines of the Typst source Typst compiled. For `.typ`
30
+ # views and the Sinatra and Rage helpers, that is the template after ERB
31
+ # evaluation, so a `<% %>` block that emits several lines (or none) can
32
+ # shift them relative to the file on disk. {#source_line} shows the
33
+ # compiled line.
34
+ #
35
+ # @example
36
+ # begin
37
+ # renderer.render(nil, data)
38
+ # rescue TypstRails::CompileError => e
39
+ # e.template #=> "app/views/reports/show.pdf.typ"
40
+ # e.line #=> 4
41
+ # e.column #=> 9
42
+ # e.diagnostics.first.message #=> "unknown variable: foo"
43
+ # end
44
+ class CompileError < Error
45
+ # @return [Array<Diagnostics::Diagnostic>] every error and warning Typst
46
+ # reported, in the order it printed them. Empty when the output could
47
+ # not be parsed.
48
+ attr_reader :diagnostics
49
+
50
+ # @return [String, nil] display name of the template, such as
51
+ # "app/views/reports/show.pdf.typ", or nil if none was given
52
+ attr_reader :template
53
+
54
+ # @return [String] Typst's raw output, with temporary paths rewritten
55
+ attr_reader :typst_message
56
+
57
+ # @return [Array<String>, nil] the command line the CLI backend ran, for
58
+ # debugging; nil for other backends
59
+ attr_reader :command
60
+
61
+ # @return [String, nil] the compiled source line the first error points
62
+ # at, when that error is in the template itself
63
+ attr_reader :source_line
64
+
65
+ # @param typst_message [String, nil] Typst's diagnostic output
66
+ # @param template [String, nil] display name of the template
67
+ # @param command [Array<String>, nil] command line that was run
68
+ # @param source [String, nil] the Typst source that was compiled, used
69
+ # to look up {#source_line}
70
+ def initialize(typst_message = nil, template: nil, command: nil, source: nil)
71
+ @typst_message = Diagnostics.clean(typst_message).strip
72
+ @template = template
73
+ @command = command
74
+ @diagnostics = Diagnostics.parse(@typst_message)
75
+ @source_line = find_source_line(source)
76
+ super(build_message)
77
+ end
78
+
79
+ # @return [Array<Diagnostics::Diagnostic>] the errors among {#diagnostics}
80
+ def errors
81
+ diagnostics.select(&:error?)
82
+ end
83
+
84
+ # @return [Array<Diagnostics::Diagnostic>] the warnings among {#diagnostics}
85
+ def warnings
86
+ diagnostics.select(&:warning?)
87
+ end
88
+
89
+ # @return [Integer, nil] line of the first error, counted from 1
90
+ def line
91
+ first_error&.line
92
+ end
93
+
94
+ # @return [Integer, nil] column of the first error, counted from 0 as
95
+ # Typst reports it
96
+ def column
97
+ first_error&.column
98
+ end
99
+
100
+ private
101
+
102
+ def first_error
103
+ errors.first
104
+ end
105
+
106
+ def template_name
107
+ template || Diagnostics::INLINE_SOURCE_NAME
108
+ end
109
+
110
+ def in_template?(diagnostic)
111
+ diagnostic&.path == template_name
112
+ end
113
+
114
+ def find_source_line(source)
115
+ return nil unless source && in_template?(first_error) && line&.positive?
116
+
117
+ source.to_s.lines[line - 1]&.chomp
118
+ end
119
+
120
+ def build_message
121
+ [summary, typst_message].reject(&:empty?).join("\n\n")
122
+ end
123
+
124
+ def summary
125
+ error = first_error
126
+ return template ? "Typst compilation failed for #{template}." : "Typst compilation failed." unless error
127
+
128
+ text = "Typst compilation failed"
129
+ text += " in #{error.location}" if error.location
130
+ text += ": #{error.message}"
131
+ if in_template?(error)
132
+ text += "\n(Line numbers count lines of the compiled Typst source, after any ERB evaluation.)"
133
+ elsif template
134
+ text += "\n(while rendering #{template})"
135
+ end
136
+ text
137
+ end
138
+ end
139
+ end
@@ -35,6 +35,7 @@ module TypstRails
35
35
  # `erb_engine.src` generates a string of Ruby code. This code, when executed,
36
36
  # evaluates the ERB template and appends results to the `eoutvar` (i.e., `@output_buffer`).
37
37
  erb_evaluation_code = erb_engine.src
38
+ renderer_args = renderer_arguments(template)
38
39
 
39
40
  # The string returned by this `call` method is the final piece of Ruby code
40
41
  # that ActionView will `instance_eval`.
@@ -43,26 +44,67 @@ module TypstRails
43
44
  # capturing the result. This allows dynamic Ruby evaluation within the .typ file.
44
45
  # 2. Passes the ERB-processed Typst source to our `TypstRails::Renderer`
45
46
  # which then handles the actual Typst compilation.
47
+ #
48
+ # Only the outermost .typ template compiles. A .typ partial (or any .typ
49
+ # template rendered from inside another one) returns its ERB-processed
50
+ # source, so the parent can splice it in and compile the whole document
51
+ # once. The flag lives on the view context, which every nested render
52
+ # shares.
46
53
  <<-RUBY_CODE
54
+ _typst_rails_outermost = !@_typst_rails_rendering
55
+ @_typst_rails_rendering = true
56
+
47
57
  # Preserve the current @output_buffer if one exists (e.g., if rendering a partial).
48
58
  # A new buffer is created for ERB processing of the Typst template to isolate its output.
49
59
  _original_typst_handler_output_buffer = @output_buffer
50
60
  @output_buffer = ActionView::OutputBuffer.new
51
61
 
52
- #{erb_evaluation_code}
53
-
54
- # After the above ERB code executes, @output_buffer contains the
55
- # ERB-processed Typst template source as a string.
56
- processed_typst_source = @output_buffer.to_s
62
+ begin
63
+ #{erb_evaluation_code}
57
64
 
58
- # Restore the original output buffer that was in place before this handler ran.
59
- @output_buffer = _original_typst_handler_output_buffer
65
+ # After the above ERB code executes, @output_buffer contains the
66
+ # ERB-processed Typst template source as a string.
67
+ processed_typst_source = @output_buffer.to_s
68
+ ensure
69
+ # Restore the original output buffer that was in place before this handler ran.
70
+ @output_buffer = _original_typst_handler_output_buffer
71
+ @_typst_rails_rendering = false if _typst_rails_outermost
72
+ end
60
73
 
61
- typst_renderer = ::TypstRails::Renderer.new(processed_typst_source)
62
- typst_renderer.render(self, local_assigns)
74
+ if _typst_rails_outermost
75
+ typst_renderer = ::TypstRails::Renderer.new(#{renderer_args})
76
+ typst_renderer.render(self, local_assigns)
77
+ else
78
+ processed_typst_source
79
+ end
63
80
  RUBY_CODE
64
81
  end
65
82
 
83
+ # Template methods that name the template, best first. short_identifier
84
+ # is the path relative to Rails.root.
85
+ TEMPLATE_NAME_METHODS = %i[short_identifier identifier virtual_path].freeze
86
+
87
+ # @param template [ActionView::Template]
88
+ # @return [String, nil] a name for the template in error messages, such
89
+ # as "app/views/reports/show.pdf.typ"
90
+ def self.template_display_name(template)
91
+ TEMPLATE_NAME_METHODS.each do |name|
92
+ next unless template.respond_to?(name)
93
+
94
+ value = template.public_send(name)
95
+ return value.to_s unless value.nil? || value.to_s.empty?
96
+ end
97
+ nil
98
+ end
99
+
100
+ # The template's name is computed once, here, and embedded in the
101
+ # generated code as a string literal.
102
+ def self.renderer_arguments(template)
103
+ name = template_display_name(template)
104
+ name ? "processed_typst_source, template: #{name.inspect}" : "processed_typst_source"
105
+ end
106
+ private_class_method :renderer_arguments
107
+
66
108
  # Indicates whether this template handler supports streaming.
67
109
  # Typst compilation generates a complete PDF file; it's not inherently a streaming process
68
110
  # where chunks of output can be sent progressively. Therefore, streaming is not supported.
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "typst_rails/renderer"
4
- require "typst_rails/erb_source"
3
+ require "typst_rails/template_rendering"
5
4
 
6
5
  module TypstRails
7
6
  # Integration for the Rage framework.
@@ -10,8 +9,9 @@ module TypstRails
10
9
  # so the integration adds a controller helper rather than a `.typ` handler.
11
10
  module RageIntegration
12
11
  # 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)
12
+ # locals get the same JSON conversion (models, dates) as in Rails. Kept
13
+ # for compatibility; the helper now goes through {TemplateRendering}.
14
+ ViewContext = ::TypstRails::TemplateRendering::ViewContext
15
15
 
16
16
  # Mixed into RageController::API by {RageIntegration.setup}. Include it
17
17
  # yourself if typst-rails loads before Rage's controllers are defined.
@@ -36,13 +36,13 @@ module TypstRails
36
36
  # @param locals [Hash] data for the template
37
37
  # @param status [Integer, Symbol, nil] response status
38
38
  # @return [void]
39
- # @raise [TypstRails::Error] if compilation fails
39
+ # @raise [TypstRails::CompileError] if Typst rejects the template
40
+ # @raise [TypstRails::Error] if compilation fails for another reason
40
41
  def render_typst(template, locals = {}, status: nil, **extra)
41
42
  # Ruby 2.7 binds a trailing symbol-keyed locals hash as keywords;
42
43
  # fold those back into locals.
43
44
  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)
45
+ pdf_data = ::TypstRails::TemplateRendering.render_file(template, self, locals, locals)
46
46
 
47
47
  # Rage's render(plain:) sets text/plain, so override it afterwards.
48
48
  render plain: pdf_data, status: status
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TypstRails
4
+ # Renders `.typ` views through a Rails controller, so app helpers, route
5
+ # helpers, and partials work as in a request. Backs
6
+ # {TypstRails.render_with_rails}.
7
+ #
8
+ # Nothing here loads Rails. ActionController is looked up when a render
9
+ # happens, so typst-rails can be required before actionpack.
10
+ #
11
+ # @api private
12
+ module RailsRendering
13
+ # Raised as a {TypstRails::Error} message when ActionController is absent.
14
+ MISSING_ACTION_CONTROLLER = "render_with_rails requires ActionController; use TypstRails.render"
15
+
16
+ module_function
17
+
18
+ # @param template [String, Symbol, Pathname] Rails template name
19
+ # @param locals [Hash] view locals
20
+ # @param assigns [Hash] view instance variables
21
+ # @param controller [Class, nil] controller class to render with
22
+ # @return [String] binary PDF data
23
+ # @raise [TypstRails::Error] if ActionController is not loaded
24
+ def render(template, locals: {}, assigns: {}, controller: nil)
25
+ raise ArgumentError, "locals must be a Hash" unless locals.is_a?(Hash)
26
+ raise ArgumentError, "assigns must be a Hash" unless assigns.is_a?(Hash)
27
+ raise Error, MISSING_ACTION_CONTROLLER unless defined?(::ActionController::Base)
28
+
29
+ controller ||= default_controller
30
+ body = controller.render(template: template.to_s, formats: [:pdf], locals: locals, assigns: assigns)
31
+ binary(body)
32
+ end
33
+
34
+ # ApplicationController when the app defines one that renders views,
35
+ # otherwise ActionController::Base. An ApplicationController based on
36
+ # ActionController::API cannot render templates, so it is skipped.
37
+ #
38
+ # @return [Class]
39
+ def default_controller
40
+ if Object.const_defined?(:ApplicationController)
41
+ app_controller = ::ApplicationController
42
+ return app_controller if app_controller.is_a?(Class) && app_controller <= ::ActionController::Base
43
+ end
44
+
45
+ ::ActionController::Base
46
+ end
47
+
48
+ # Returns the rendered body as a plain binary String. Rails may hand
49
+ # back an ActionView::OutputBuffer or an ActiveSupport::SafeBuffer;
50
+ # callers want bytes they can write to a file or attach.
51
+ #
52
+ # @param body [#to_s]
53
+ # @return [String]
54
+ def binary(body)
55
+ String.new(body.to_s, encoding: Encoding::BINARY)
56
+ end
57
+ end
58
+ end