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.
@@ -1,9 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "tempfile"
3
+ require "tmpdir"
4
+ require "fileutils"
4
5
  require "json"
6
+ require "typst_rails/errors"
5
7
  require "typst_rails/helpers"
6
8
  require "typst_rails/backends"
9
+ require "typst_rails/data_serializer"
7
10
 
8
11
  # Only require ActiveSupport extensions if available
9
12
  begin
@@ -53,8 +56,19 @@ module TypstRails
53
56
  # Maximum source size (10MB) to prevent memory issues
54
57
  MAX_SOURCE_SIZE = 10 * 1024 * 1024
55
58
 
56
- # Holds the filesystem paths used during a single compilation run.
57
- TempPaths = Struct.new(:typ_file, :dir, :data_file_path)
59
+ # Name of the JSON file holding template data, read in Typst with
60
+ # `json("typst_data.json")`. It is written only when the template
61
+ # source mentions it.
62
+ DATA_FILE_NAME = "typst_data.json"
63
+
64
+ # Root of the key paths that serialization errors give for locals, as in
65
+ # "locals.items[0].amount". Instance variables are named "@name" instead.
66
+ LOCALS_PATH = "locals"
67
+
68
+ # Holds the filesystem paths used during a single compilation run. Each
69
+ # run gets its own directory so concurrent renders never share a
70
+ # typst_data.json.
71
+ TempPaths = Struct.new(:root, :dir, :typ_path, :data_file_path)
58
72
 
59
73
  # MARK: - Attributes
60
74
 
@@ -64,21 +78,33 @@ module TypstRails
64
78
  # @return [Object, nil] The view context providing access to helpers and instance variables
65
79
  attr_reader :view_context
66
80
 
81
+ # @return [String, nil] Display name of the template, used in error
82
+ # messages and passed to {TypstRails::Configuration#on_warning}
83
+ attr_reader :template
84
+
67
85
  # MARK: - Initialization
68
86
 
69
87
  # Initializes the renderer with the Typst template source.
70
88
  #
71
89
  # @param source [String] The Typst template source code
90
+ # @param template [String, Pathname, nil] A name for the template, such as
91
+ # "app/views/reports/show.pdf.typ". Error messages and warnings use it
92
+ # in place of the temporary file Typst actually compiles. The Rails
93
+ # handler and the Sinatra and Rage helpers pass it for you.
72
94
  # @return [Renderer] A new renderer instance
73
95
  # @raise [ArgumentError] if source is nil
74
96
  # @raise [ArgumentError] if source is too large (exceeds MAX_SOURCE_SIZE)
75
97
  #
76
98
  # @example
77
99
  # renderer = Renderer.new("= Hello, Typst!")
78
- def initialize(source)
100
+ #
101
+ # @example Naming the template for error messages
102
+ # renderer = Renderer.new(File.read(path), template: path)
103
+ def initialize(source, template: nil)
79
104
  raise ArgumentError, "Source cannot be nil" if source.nil?
80
105
 
81
106
  @source = source.to_s
107
+ @template = template&.to_s
82
108
 
83
109
  return unless @source.bytesize > MAX_SOURCE_SIZE
84
110
 
@@ -98,7 +124,8 @@ module TypstRails
98
124
  # @return [String] Binary string containing the PDF data
99
125
  # @raise [ArgumentError] if local_assigns is not a Hash
100
126
  # @raise [ArgumentError] if source is empty
101
- # @raise [TypstRails::Error] if Typst compilation fails
127
+ # @raise [TypstRails::CompileError] if Typst rejects the template
128
+ # @raise [TypstRails::Error] if compilation fails for another reason
102
129
  #
103
130
  # @example Render with plain data
104
131
  # renderer = Renderer.new("= #data.title")
@@ -119,7 +146,10 @@ module TypstRails
119
146
  local_assigns
120
147
  end
121
148
 
122
- compile_typst_source(@source, data_for_typst)
149
+ warnings = []
150
+ pdf = compile_typst_source(@source, data_for_typst, warnings)
151
+ report_warnings(warnings)
152
+ pdf
123
153
  end
124
154
 
125
155
  # MARK: - Private Methods
@@ -137,20 +167,22 @@ module TypstRails
137
167
  #
138
168
  # @param typst_source [String] The Typst template source
139
169
  # @param data [Hash] Data to be made available to the Typst template via JSON
170
+ # @param warnings [Array<Diagnostics::Diagnostic>] receives warnings
171
+ # reported by a successful compile
140
172
  # @return [String] Binary PDF data
141
173
  # @raise [ArgumentError] if typst_source is empty or data is not a Hash
142
174
  # @raise [TypstRails::Error] if compilation fails or produces no output
143
175
  #
144
176
  # @note This method ensures all temporary files are cleaned up even if errors occur
145
- def compile_typst_source(typst_source, data = {})
177
+ def compile_typst_source(typst_source, data = {}, warnings = [])
146
178
  raise ArgumentError, "typst_source cannot be empty" if typst_source.nil? || typst_source.empty?
147
179
  raise ArgumentError, "data must be a Hash" unless data.is_a?(Hash)
148
180
 
149
181
  paths = TempPaths.new
150
182
  begin
151
183
  write_typst_source_file(paths, typst_source)
152
- write_typst_data_file(paths, data)
153
- run_typst_compiler(paths)
184
+ write_typst_data_file(paths, data) if reads_data_file?(typst_source)
185
+ run_typst_compiler(paths, warnings)
154
186
  rescue Error
155
187
  raise
156
188
  rescue StandardError => e
@@ -163,37 +195,106 @@ module TypstRails
163
195
  end
164
196
 
165
197
  def write_typst_source_file(paths, typst_source)
166
- # Create temp file in a directory that Typst can access.
167
- # Ensure it's in binary mode for writing source if it contains non-ASCII.
168
- paths.typ_file = Tempfile.new(["durable_typst_template_", ".typ"], binmode: true)
169
- paths.dir = File.dirname(paths.typ_file.path)
170
-
171
- paths.typ_file.write(typst_source)
172
- paths.typ_file.flush # Ensure content is written before Typst reads it.
173
- paths.typ_file.close # Close it so Typst can open it, especially important on Windows.
198
+ # Each run gets a private directory holding the template and its data,
199
+ # so json("typst_data.json") resolves next to the template. Typst only
200
+ # compiles files inside its root, so with a configured root the
201
+ # directory is created there; otherwise it doubles as the root.
202
+ paths.root = configured_root_path
203
+ paths.dir = make_run_dir(paths.root)
204
+ paths.root ||= paths.dir
205
+ paths.typ_path = File.join(paths.dir, "template.typ")
206
+ File.binwrite(paths.typ_path, typst_source)
207
+ end
208
+
209
+ def make_run_dir(root)
210
+ return Dir.mktmpdir("typst_rails_") unless root
211
+
212
+ begin
213
+ Dir.mktmpdir("typst_rails_", root)
214
+ rescue SystemCallError => e
215
+ raise Error, "Cannot create a working directory in default_root_path #{root}: #{e.message}"
216
+ end
174
217
  end
175
218
 
219
+ # Assigns can hold whole models, so they are written to disk only for
220
+ # templates that load them.
221
+ def reads_data_file?(typst_source)
222
+ typst_source.include?(DATA_FILE_NAME)
223
+ end
224
+
225
+ # Writes +data+ to typst_data.json next to the Typst source, where the
226
+ # template loads it with `json("typst_data.json")`.
227
+ #
228
+ # The data is converted with {DataSerializer} first, and every value is
229
+ # treated as a local: anything without a faithful JSON form raises. Data
230
+ # from {#collect_data_for_typst} is already plain, so this pass is cheap
231
+ # there; it does the real work for renders without a view context.
232
+ #
233
+ # @raise [SerializationError] if a value has no faithful JSON form
234
+ # @raise [TypstRails::Error] if the file cannot be written
176
235
  def write_typst_data_file(paths, data)
177
236
  return if data.nil? || data.empty?
178
237
 
179
- # Create a temporary JSON data file in the same directory as the Typst source.
180
- # The Typst template would then use `json("typst_data.json")` to load this data.
181
- paths.data_file_path = File.join(paths.dir, "typst_data.json")
182
- File.write(paths.data_file_path, data.to_json)
238
+ json = JSON.generate(DataSerializer.normalize(data, path: LOCALS_PATH))
239
+ paths.data_file_path = File.join(paths.dir, DATA_FILE_NAME)
240
+ File.write(paths.data_file_path, json)
183
241
  rescue JSON::GeneratorError => e
184
242
  raise Error, "Failed to serialize data to JSON: #{e.message}"
243
+ rescue Error
244
+ raise
185
245
  rescue StandardError => e
186
246
  raise Error, "Failed to write data file: #{e.message}"
187
247
  end
188
248
 
189
- def run_typst_compiler(paths)
249
+ # Backends may yield diagnostic output from a successful compile; the
250
+ # warnings in it are collected here and reported once rendering is done,
251
+ # so an on_warning handler that raises is not mistaken for a compile
252
+ # failure.
253
+ def run_typst_compiler(paths, warnings)
190
254
  backend = Backends::Registry.resolve(configured_backend)
191
- backend.compile(paths.typ_file.path, paths.dir)
255
+ backend.compile(paths.typ_path, paths.root) do |diagnostic_text|
256
+ warnings.concat(Diagnostics.parse(path_rewriter(paths).rewrite(diagnostic_text)).select(&:warning?))
257
+ end
258
+ rescue CompileError => e
259
+ error = contextualize(e, paths)
260
+ log_error(error.message)
261
+ raise error
192
262
  rescue Error => e
193
263
  log_error(e.message)
194
264
  raise
195
265
  end
196
266
 
267
+ # Rebuilds a backend's CompileError with the template's name in place of
268
+ # the temporary paths. The original stays available as #cause.
269
+ def contextualize(error, paths)
270
+ CompileError.new(
271
+ path_rewriter(paths).rewrite(error.typst_message),
272
+ template: @template, command: error.command, source: @source
273
+ )
274
+ end
275
+
276
+ def path_rewriter(paths)
277
+ Diagnostics::PathRewriter.new(
278
+ typ_path: paths.typ_path, run_dir: paths.dir, root: paths.root, template: @template
279
+ )
280
+ end
281
+
282
+ def report_warnings(warnings)
283
+ return if warnings.empty?
284
+
285
+ handler = configured_warning_handler
286
+ handler&.call(warnings, @template)
287
+ end
288
+
289
+ # @return [#call, nil] TypstRails.configuration.on_warning, or the default
290
+ # logger when TypstRails has not been configured
291
+ def configured_warning_handler
292
+ config = TypstRails.respond_to?(:configuration) ? TypstRails.configuration : nil
293
+ return Diagnostics.method(:log_warnings) unless config
294
+
295
+ config.on_warning
296
+ end
297
+
197
298
  # @return [Symbol, Backends::Base, nil] the backend preference from
198
299
  # TypstRails.configuration, or nil if the top-level TypstRails module
199
300
  # (and its Configuration) hasn't been loaded (e.g. when only
@@ -204,16 +305,18 @@ module TypstRails
204
305
  TypstRails.configuration&.backend
205
306
  end
206
307
 
207
- def cleanup_temp_paths(paths)
208
- # Clean up all temporary files, suppressing any errors during cleanup
209
- rescue_cleanup_errors("temp Typst file") do
210
- paths.typ_file.unlink if paths.typ_file&.path && File.exist?(paths.typ_file.path)
211
- end
212
- rescue_cleanup_errors("temp data file") { safe_unlink(paths.data_file_path) }
308
+ # @return [String, nil] the configured Typst root as an absolute path
309
+ def configured_root_path
310
+ return nil unless TypstRails.respond_to?(:configuration)
311
+
312
+ root = TypstRails.configuration&.default_root_path
313
+ root && File.expand_path(root.to_s)
213
314
  end
214
315
 
215
- def safe_unlink(path)
216
- File.unlink(path) if path && File.exist?(path)
316
+ def cleanup_temp_paths(paths)
317
+ return unless paths.dir
318
+
319
+ rescue_cleanup_errors("temp directory") { FileUtils.remove_entry(paths.dir) }
217
320
  end
218
321
 
219
322
  def rescue_cleanup_errors(description)
@@ -222,90 +325,114 @@ module TypstRails
222
325
  warn "Failed to clean up #{description}: #{e.message}"
223
326
  end
224
327
 
225
- # Collects data from view_context (instance variables) and local_assigns.
328
+ # Collects the data for typst_data.json from the view context's instance
329
+ # variables (its `assigns`) and +local_assigns+, which win on a name clash.
330
+ #
331
+ # Values are converted with {DataSerializer}, under two policies:
332
+ #
333
+ # - A local was passed on purpose, so one without a faithful JSON form
334
+ # raises {SerializationError}, naming its key path.
335
+ # - Instance variables include incidental ones (a form object, a service,
336
+ # a Proc), so one without a faithful JSON form is left out, and a single
337
+ # warning per render lists what was left out and why.
226
338
  #
227
- # This method extracts instance variables from the view context (if available via
228
- # `assigns`) and merges them with local variables. The result is a hash suitable
229
- # for JSON serialization and injection into Typst templates.
339
+ # Assigns whose names begin with an underscore are skipped silently. Rails
340
+ # keeps its own controller state in such variables and filters them from
341
+ # `assigns` itself; gems that add their own (such as `@_current_ability`)
342
+ # are skipped the same way.
343
+ #
344
+ # Conversion happens only when the template reads typst_data.json. For
345
+ # other templates the merged values are returned as they are, since they
346
+ # are never written.
230
347
  #
231
348
  # @param view_context [Object] The view context (typically from Rails/Sinatra)
232
349
  # @param local_assigns [Hash] Local variables passed to the template
233
- # @return [Hash] A hash of data suitable for JSON serialization, with symbolized keys
350
+ # @return [Hash{Symbol => Object}] The data, keyed by symbolized name
234
351
  # @raise [ArgumentError] if local_assigns is not a Hash
352
+ # @raise [SerializationError] if a local has no faithful JSON form
235
353
  # @raise [TypstRails::Error] if data collection fails
236
- #
237
- # @note Instance variables from view_context take precedence over local_assigns
238
- # @note All values are transformed for JSON serialization (dates to ISO8601, etc.)
239
354
  def collect_data_for_typst(view_context, local_assigns)
240
355
  raise ArgumentError, "local_assigns must be a Hash" unless local_assigns.is_a?(Hash)
241
356
 
242
- data = {}
357
+ locals = local_assigns.symbolize_keys
358
+ assigns = data_assigns(view_context).reject { |name, _| locals.key?(name) }
359
+ return assigns.merge(locals) unless reads_data_file?(@source)
243
360
 
244
- # Instance variables from the controller are available in view_context.assigns.
245
- if view_context.respond_to?(:assigns)
246
- assigns = view_context.assigns
247
- if assigns.is_a?(Hash)
248
- assigns.each do |key, value|
249
- data[key.to_sym] = value # Convert keys to symbols for consistency.
250
- end
251
- end
361
+ data = normalize_assigns(assigns)
362
+ locals.each do |name, value|
363
+ data[name] = DataSerializer.normalize(value, path: DataSerializer.child_path(LOCALS_PATH, name))
252
364
  end
253
-
254
- # Local assigns (e.g., from `render locals: {...}`) merge in, taking precedence.
255
- data.merge!(local_assigns.symbolize_keys)
256
-
257
- # Transform values to ensure they are JSON-serializable.
258
- data.transform_values do |value|
259
- transform_value_for_json_serialization(value)
260
- end
261
- rescue ArgumentError
365
+ data
366
+ rescue ArgumentError, Error
262
367
  raise
263
368
  rescue StandardError => e
264
369
  raise Error, "Failed to collect data for Typst template: #{e.message}"
265
370
  end
266
371
 
267
- # Transforms various Ruby objects into JSON-friendly representations.
372
+ # @return [Hash{Symbol => Object}] the view context's assigns, minus
373
+ # underscore-prefixed internals
374
+ def data_assigns(view_context)
375
+ return {} unless view_context.respond_to?(:assigns)
376
+
377
+ assigns = view_context.assigns
378
+ return {} unless assigns.is_a?(Hash)
379
+
380
+ assigns.each_with_object({}) do |(key, value), result|
381
+ result[key.to_sym] = value unless key.to_s.start_with?("_")
382
+ end
383
+ end
384
+
385
+ # Converts each assign, leaving out and warning about those that have no
386
+ # faithful JSON form.
268
387
  #
269
- # This method recursively transforms Ruby objects to ensure they can be
270
- # serialized to JSON for Typst template consumption. It handles:
271
- # - ActiveRecord objects (via as_json)
272
- # - Date/Time objects (to ISO8601 strings)
273
- # - Arrays (recursively transform elements)
274
- # - Hashes (recursively transform values)
388
+ # @return [Hash{Symbol => Object}]
389
+ def normalize_assigns(assigns)
390
+ omitted = []
391
+ data = assigns.each_with_object({}) do |(name, value), result|
392
+ result[name] = DataSerializer.normalize(value, path: "@#{name}")
393
+ rescue SerializationError => e
394
+ omitted << "@#{name} (#{e.path} #{e.reason})"
395
+ end
396
+ warn_about_omitted_assigns(omitted) unless omitted.empty?
397
+ data
398
+ end
399
+
400
+ def warn_about_omitted_assigns(omitted)
401
+ log_warning("Left #{omitted.size} instance variable(s) out of #{DATA_FILE_NAME} because they are not " \
402
+ "JSON-serializable: #{omitted.join("; ")}. If the template needs one, pass it as a local " \
403
+ "in a serializable form.")
404
+ end
405
+
406
+ # Transforms a value into plain JSON data.
275
407
  #
276
- # @param value [Object] The value to transform
277
- # @return [Object] A JSON-friendly representation of the value
408
+ # Kept for compatibility; it delegates to {DataSerializer.normalize}. Hash
409
+ # keys and Symbols come back as Strings, and values with no faithful JSON
410
+ # form raise {SerializationError} rather than passing through unchanged.
278
411
  #
279
- # @example Transforming a date
280
- # transform_value_for_json_serialization(Date.today)
281
- # # => "2024-01-15"
412
+ # @param value [Object] The value to transform
413
+ # @return [Object] Plain JSON data
414
+ # @raise [SerializationError] if the value has no faithful JSON form
282
415
  #
283
- # @example Transforming an array
284
- # transform_value_for_json_serialization([Date.today, "text"])
285
- # # => ["2024-01-15", "text"]
416
+ # @example
417
+ # transform_value_for_json_serialization([Date.new(2024, 1, 15), :draft])
418
+ # # => ["2024-01-15", "draft"]
286
419
  def transform_value_for_json_serialization(value)
287
- if active_record_value?(value)
288
- value.as_json # Use Rails' built-in JSON serialization for ActiveRecord objects.
289
- elsif value.is_a?(Date) || value.is_a?(Time) || value.is_a?(DateTime)
290
- value.iso8601 # Convert date/time objects to ISO8601 strings.
291
- elsif value.is_a?(Array)
292
- value.map { |v| transform_value_for_json_serialization(v) } # Recursively transform array elements.
293
- elsif value.is_a?(Hash)
294
- # Recursively transform hash values.
295
- value.transform_values do |v_hash|
296
- transform_value_for_json_serialization(v_hash)
297
- end
298
- else
299
- value # Return other types as-is, assuming they are JSON-serializable.
300
- end
420
+ DataSerializer.normalize(value, path: "value")
301
421
  end
302
422
 
303
- # @return [Boolean] whether +value+ is an ActiveRecord model or relation
304
- def active_record_value?(value)
305
- return false unless defined?(::ActiveRecord::Base)
306
-
307
- value.is_a?(::ActiveRecord::Base) ||
308
- (defined?(::ActiveRecord::Relation) && value.is_a?(::ActiveRecord::Relation))
423
+ # Logs a warning to Rails.logger when available, otherwise with warn.
424
+ #
425
+ # @param message [String] The warning, without the "TypstRails:" prefix
426
+ # @return [void]
427
+ def log_warning(message)
428
+ formatted_message = "TypstRails: #{message}"
429
+ if defined?(::Rails) && ::Rails.respond_to?(:logger) && ::Rails.logger
430
+ ::Rails.logger.warn formatted_message
431
+ else
432
+ warn formatted_message
433
+ end
434
+ rescue StandardError
435
+ warn formatted_message
309
436
  end
310
437
 
311
438
  # Logs an error message to the appropriate logger.
@@ -347,7 +474,10 @@ module TypstRails
347
474
  # @raise [NoMethodError] if neither the renderer nor view_context respond to the method
348
475
  #
349
476
  # @see #respond_to_missing?
350
- def method_missing(method_name, *args, &block)
477
+ #
478
+ # ruby2_keywords keeps keyword arguments intact on every supported Ruby;
479
+ # an explicit **kwargs would pass a stray empty hash on Ruby 2.7.
480
+ ruby2_keywords def method_missing(method_name, *args, &block)
351
481
  if @view_context.respond_to?(method_name)
352
482
  @view_context.public_send(method_name, *args, &block)
353
483
  else
@@ -369,18 +499,4 @@ module TypstRails
369
499
  @view_context.respond_to?(method_name, include_private) || super
370
500
  end
371
501
  end
372
-
373
- # Error class for Typst-related errors.
374
- #
375
- # Raised when Typst compilation fails, when files cannot be created,
376
- # or when other Typst-specific errors occur during rendering.
377
- #
378
- # @example Handling Typst errors
379
- # begin
380
- # renderer.render(nil, data)
381
- # rescue TypstRails::Error => e
382
- # Rails.logger.error "Typst compilation failed: #{e.message}"
383
- # render plain: "PDF generation failed", status: 500
384
- # end
385
- class Error < StandardError; end
386
502
  end
@@ -1,28 +1,27 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "typst_rails/template_rendering"
4
+
3
5
  module TypstRails
4
6
  # Integration for Sinatra framework
5
7
  module SinatraIntegration
6
8
  # Simple view context wrapper providing the `assigns` reader that
7
- # Renderer expects, mirroring Rails' view context interface.
8
- ViewContext = Struct.new(:assigns)
9
+ # Renderer expects, mirroring Rails' view context interface. Kept for
10
+ # compatibility; the helper now goes through {TemplateRendering}.
11
+ ViewContext = ::TypstRails::TemplateRendering::ViewContext
9
12
 
10
13
  def self.setup
11
14
  return unless defined?(::Sinatra)
12
15
 
13
- require "typst_rails/renderer"
14
-
15
16
  # Extend Sinatra with Typst rendering capabilities
16
17
  ::Sinatra::Base.class_eval do
17
- # Helper method to render Typst templates in Sinatra
18
- def typst(template, locals = {}, _options = {})
19
- typst_source = File.read(template)
20
- renderer = ::TypstRails::Renderer.new(typst_source)
18
+ include ::TypstRails::Helpers
21
19
 
22
- # Sinatra doesn't have the same view context as Rails,
23
- # so we create a simple wrapper
24
- view_context = ::TypstRails::SinatraIntegration::ViewContext.new(locals)
25
- pdf_data = renderer.render(view_context, locals)
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.
23
+ def typst(template, locals = {}, _options = {})
24
+ pdf_data = ::TypstRails::TemplateRendering.render_file(template, self, locals, locals)
26
25
 
27
26
  content_type "application/pdf"
28
27
  pdf_data