kiln 0.1.4 → 0.1.6

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c77d38afe49d8d5149ee6491636fb192aa74679bb7599bdfab23785cb8aa7add
4
- data.tar.gz: 87f254094d83833b82afc4ccf67d9d6eacbe964a663e89c35d15612525923cce
3
+ metadata.gz: 2f32e8bbaa7ee4f8dd14fa25c2303cb0c030e49a899bb73db1b746bdcb177f41
4
+ data.tar.gz: b4adb00dfe11eca35cbb4297e5d48626869e5fa57b0aa16f660eb302b7f7658a
5
5
  SHA512:
6
- metadata.gz: 4439279aef4385538b9a80b73bc813221d44b4b9bc0261cc36a9d14b960142073f8de11e0401c659481ba6ff20f8eb1ebaf66fc91805b968b60feebc28d0659c
7
- data.tar.gz: a61d697784e845141f7f88f0660ac70f93c15d36bdd860bf95705777f44a55c5a2a547bdf96043379daee586f04b395d56b52e09a3a5d60e711389d992d20f9f
6
+ metadata.gz: 2a5d738c7589388db0f1714d2ba840936412c39b5f05c7a16ca4bc270fa0f27ae02652ed3f00dc343a0bf2cf9cd75e335bdaa141ac8bbbd9d53dd9ffcf388924
7
+ data.tar.gz: 90852ee81ad4e6a60ae7084cf62bc9cdd9beaf0664755adacc713abcf8b6da47031e6bd532603958084863416058f0a31c06a9b3ebe221f333f8a8c910b5c2b7
data/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.6 (2026-11-14)
4
+
5
+ Fixed:
6
+
7
+ - Markdown renders a line break inside a paragraph as a space, as CommonMark does, instead of
8
+ `<br>`. Commonmarker turns hardbreaks on by default, so files wrapped at a column rendered a
9
+ break at every wrap. Two trailing spaces or a backslash still break the line.
10
+
11
+ ## 0.1.5 (2026-11-13)
12
+
13
+ Breaking:
14
+
15
+ - `Kiln::Assets.precompile`, `precompile?` and `check_builds!` move to `Kiln::Assets::Compiler`
16
+ (`precompile` is now `Compiler.run`, which also checks `app/assets/builds`).
17
+ `Kiln::Assets.copy_public` is now `Kiln::Writer#copy_public`.
18
+ - `Kiln::Writer.new` takes `report:`, and every file it writes is recorded there.
19
+ `Kiln::Assets.new` takes `writer:` and `host:` instead of `output:` and `config:`.
20
+ `Kiln::Sitemap#write` and `Kiln::Redirects#write` take a writer instead of a directory.
21
+ - `Kiln::Report::KINDS` and `Kiln::Build#pages_dsl` and `#previous_manifest` are removed.
22
+
23
+ Added:
24
+
25
+ - `kiln_site` in `Kiln::TestHelper` returns the output of one build shared by every test in the
26
+ class. The directory is removed when the test run ends.
27
+
28
+ Fixed:
29
+
30
+ - An asset path that resolves outside the output directory is reported as an asset error instead
31
+ of being written there.
32
+ - The build summary counts `sitemap.xml`, and counts a copied `public/_redirects` that the build
33
+ extends once.
34
+ - `kiln:serve` boots an app without its own secret the way `kiln:build` does, instead of failing
35
+ with "Missing `secret_key_base`" in production.
36
+ - A page path that unescapes to invalid UTF-8 is reported as an invalid path.
37
+
3
38
  ## 0.1.4 (2026-11-13)
4
39
 
5
40
  Breaking:
data/README.md CHANGED
@@ -64,6 +64,7 @@ class StaticSiteTest < ActiveSupport::TestCase
64
64
 
65
65
  test("the site builds repeatably") { kiln_build(repeatable: true) { assert it.join("index.html").file? } }
66
66
  test("the home page") { assert_page "/", selector: "h1", text: "Welcome" }
67
+ test("the sitemap") { assert kiln_site.join("sitemap.xml").file? }
67
68
  end
68
69
  ```
69
70
 
@@ -0,0 +1,84 @@
1
+ require "fileutils"
2
+
3
+ module Kiln
4
+ class Assets
5
+ # Gets the app's assets ready before pages render.
6
+ module Compiler
7
+ class << self
8
+ # Compiles assets in-process when the app does not serve them dynamically. The compile goes to
9
+ # a temporary directory, never public/assets, so a development server of the same app that
10
+ # boots meanwhile never sees a production manifest. Returns a callable that restores the asset
11
+ # config and removes the directory, or nil when nothing was compiled. When assets are served
12
+ # dynamically, still runs the build steps hooked into assets:precompile (tailwindcss:build,
13
+ # javascript:build, css:build), so a development build never ships stale bundles.
14
+ def run(app)
15
+ cleanup = precompile?(app) ? compile(app) : build_bundles(app)
16
+ check_builds!(app)
17
+ cleanup
18
+ rescue Kiln::Error
19
+ cleanup&.call
20
+ raise
21
+ end
22
+
23
+ # A compiled public/assets is ignored: it can be older than the source, and a build must ship
24
+ # the assets the source compiles to now.
25
+ def precompile?(app)
26
+ assets = app.config.respond_to?(:assets) && app.config.assets
27
+ return false unless assets.respond_to?(:server) && assets.manifest_path
28
+
29
+ !assets.server
30
+ end
31
+
32
+ # Propshaft only adds load paths that exist at boot. On a fresh checkout, a bundler such as
33
+ # tailwindcss:build creates app/assets/builds during the build, too late to be served.
34
+ def check_builds!(app)
35
+ builds = app.root.join("app/assets/builds")
36
+ paths = app.config.respond_to?(:assets) && app.config.assets.respond_to?(:paths) && app.config.assets.paths
37
+ return unless paths && builds.directory? && paths.none? { Pathname(it) == builds }
38
+
39
+ raise Kiln::Error, "app/assets/builds did not exist when the app booted, so its assets are not served. " \
40
+ "Track app/assets/builds/.keep in version control, as a new Rails app does, and build again."
41
+ end
42
+
43
+ private
44
+ def compile(app)
45
+ assets = app.config.assets
46
+ original = assets.slice(:output_path, :manifest_path)
47
+ dir = Pathname(Dir.mktmpdir("kiln-assets"))
48
+ cleanup = -> do
49
+ assets.merge!(original)
50
+ FileUtils.rm_rf(dir)
51
+ end
52
+ assets.merge!(output_path: dir, manifest_path: dir.join(".manifest.json"))
53
+ begin
54
+ invoke(precompile_task(app))
55
+ rescue Kiln::Error
56
+ cleanup.call
57
+ raise
58
+ end
59
+ cleanup
60
+ end
61
+
62
+ def build_bundles(app)
63
+ precompile_task(app)&.prerequisite_tasks&.each do |task|
64
+ invoke(task) unless task.name.end_with?("environment")
65
+ end
66
+ nil
67
+ end
68
+
69
+ def precompile_task(app)
70
+ require "rake"
71
+ app.load_tasks unless Rake::Task.task_defined?("assets:precompile")
72
+ Rake::Task["assets:precompile"] if Rake::Task.task_defined?("assets:precompile")
73
+ end
74
+
75
+ def invoke(task)
76
+ task.reenable
77
+ task.invoke
78
+ rescue StandardError => error
79
+ raise Kiln::Error, "#{task.name} failed: #{error.class}: #{error.message}"
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
data/lib/kiln/assets.rb CHANGED
@@ -1,5 +1,3 @@
1
- require "fileutils"
2
- require "json"
3
1
  require "nokogiri"
4
2
  require "set"
5
3
 
@@ -10,108 +8,10 @@ module Kiln
10
8
  CSS_REFERENCE = /url\(\s*["']?([^"')]+?)["']?\s*\)|@import\s+["']([^"']+)["']/
11
9
  EXTERNAL = %r{\A(?:[a-z][a-z0-9+.-]*:|//|#)}i
12
10
 
13
- class << self
14
- # Compiles assets in-process when the app does not serve them dynamically. The compile goes to a
15
- # temporary directory, never public/assets, so a development server of the same app that boots
16
- # meanwhile never sees a production manifest. Returns a callable that restores the asset config
17
- # and removes the directory, or nil when nothing was compiled. When assets are served
18
- # dynamically, still runs the build steps hooked into assets:precompile (tailwindcss:build,
19
- # javascript:build, css:build), so a development build never ships stale bundles.
20
- def precompile(app)
21
- return build_bundles(app) unless precompile?(app)
22
-
23
- assets = app.config.assets
24
- original = assets.slice(:output_path, :manifest_path)
25
- dir = Pathname(Dir.mktmpdir("kiln-assets"))
26
- cleanup = -> do
27
- assets.merge!(original)
28
- FileUtils.rm_rf(dir)
29
- end
30
- assets.merge!(output_path: dir, manifest_path: dir.join(".manifest.json"))
31
- begin
32
- run_precompile(app)
33
- rescue Kiln::Error
34
- cleanup.call
35
- raise
36
- end
37
- cleanup
38
- end
39
-
40
- # A compiled public/assets is ignored: it can be older than the source, and a build must ship the
41
- # assets the source compiles to now.
42
- def precompile?(app)
43
- assets = app.config.respond_to?(:assets) && app.config.assets
44
- return false unless assets.respond_to?(:server) && assets.manifest_path
45
-
46
- !assets.server
47
- end
48
-
49
- # Propshaft only adds load paths that exist at boot. On a fresh checkout, a bundler such as
50
- # tailwindcss:build creates app/assets/builds during the build, too late to be served.
51
- def check_builds!(app)
52
- builds = app.root.join("app/assets/builds")
53
- paths = app.config.respond_to?(:assets) && app.config.assets.respond_to?(:paths) && app.config.assets.paths
54
- return unless paths && builds.directory? && paths.none? { Pathname(it) == builds }
55
-
56
- raise Kiln::Error, "app/assets/builds did not exist when the app booted, so its assets are not served. " \
57
- "Track app/assets/builds/.keep in version control, as a new Rails app does, and build again."
58
- end
59
-
60
- # Copies public/ into the output, minus public/assets. Files already in the output win, with a
61
- # warning unless they are listed in `generated` (files Kiln writes on purpose, like 404.html).
62
- def copy_public(from:, to:, report:, generated: [])
63
- from = Pathname(from)
64
- return unless from.directory?
65
-
66
- Dir.glob("**/*", File::FNM_DOTMATCH, base: from).sort.each do |relative|
67
- source = from.join(relative)
68
- next if source.directory? || relative.start_with?("assets/")
69
-
70
- target = Pathname(to).join(relative)
71
- if target.exist?
72
- next if generated.include?(relative)
73
-
74
- report.warn(:write, "public/#{relative} not copied, a rendered file already exists", path: "/#{relative}")
75
- else
76
- FileUtils.mkdir_p(target.dirname)
77
- FileUtils.cp(source, target)
78
- report.wrote(relative)
79
- end
80
- end
81
- end
82
-
83
- private
84
- def build_bundles(app)
85
- precompile_task(app)&.prerequisite_tasks&.each do |task|
86
- next if task.name.end_with?("environment")
87
-
88
- task.reenable
89
- task.invoke
90
- rescue StandardError => error
91
- raise Kiln::Error, "#{task.name} failed: #{error.class}: #{error.message}"
92
- end
93
- nil
94
- end
95
-
96
- def precompile_task(app)
97
- require "rake"
98
- app.load_tasks unless Rake::Task.task_defined?("assets:precompile")
99
- Rake::Task["assets:precompile"] if Rake::Task.task_defined?("assets:precompile")
100
- end
101
-
102
- def run_precompile(app)
103
- task = precompile_task(app)
104
- task.reenable
105
- task.invoke
106
- rescue StandardError => error
107
- raise Kiln::Error, "assets:precompile failed: #{error.class}: #{error.message}"
108
- end
109
- end
110
-
111
- def initialize(renderer:, output:, config:, report:, app: Rails.application)
11
+ def initialize(renderer:, writer:, host:, report:, app: Rails.application)
112
12
  @renderer = renderer
113
- @output = Pathname(output)
114
- @config = config
13
+ @writer = writer
14
+ @host = host
115
15
  @report = report
116
16
  @app = app
117
17
  end
@@ -141,7 +41,7 @@ module Kiln
141
41
 
142
42
  extension = File.extname(path)
143
43
  body = Processors::StripSourceMaps.call(body) if %w[.js .css].include?(extension)
144
- write(path, body)
44
+ @writer.write_file(path.delete_prefix("/"), body)
145
45
  extension == ".css" ? css_references(path, body) : []
146
46
  rescue StandardError => error
147
47
  @report.error(:asset, "#{error.class}: #{error.message}", path:)
@@ -158,33 +58,15 @@ module Kiln
158
58
  file.binread if file.to_s.start_with?("#{dir}/") && file.file?
159
59
  end
160
60
 
161
- def write(path, body)
162
- relative = path.delete_prefix("/")
163
- file = @output.join(relative)
164
- FileUtils.mkdir_p(file.dirname)
165
- File.binwrite(file, body)
166
- @report.wrote(relative)
167
- end
168
-
61
+ # Invalid importmaps are left to the verifier, which reports them with their page.
169
62
  def referenced_paths
170
- Dir.glob("**/*.html", base: @output).sort.flat_map do |relative|
171
- html_references(Nokogiri::HTML(File.read(@output.join(relative))))
63
+ Dir.glob("**/*.html", base: @writer.output).sort.flat_map do |relative|
64
+ doc = Nokogiri::HTML5(@writer.output.join(relative).read)
65
+ doc.xpath(Links::ELEMENTS).flat_map { Links.in(it) } +
66
+ doc.css('script[type="importmap"]').flat_map { Links.importmap(it.text).to_a }
172
67
  end.filter_map { asset_path(it) }.uniq
173
68
  end
174
69
 
175
- def html_references(doc)
176
- urls = doc.xpath("//@href | //@src").map(&:value)
177
- urls += doc.xpath("//@srcset").flat_map { |attr| attr.value.split(",").map { it.strip.split(/\s+/).first } }
178
- doc.css('script[type="importmap"]').each do |script|
179
- map = JSON.parse(script.text)
180
- urls += map.fetch("imports", {}).values
181
- urls += map.fetch("scopes", {}).values.flat_map(&:values)
182
- rescue JSON::ParserError
183
- @report.error(:asset, "invalid importmap JSON")
184
- end
185
- urls.compact
186
- end
187
-
188
70
  def css_references(css_path, body)
189
71
  body.to_s.scan(CSS_REFERENCE).filter_map do |url, import|
190
72
  ref = (url || import).strip
@@ -199,7 +81,7 @@ module Kiln
199
81
  # Normalizes a URL to an asset path ("/assets/app-abc.css"), or nil when it isn't one of ours.
200
82
  def asset_path(url)
201
83
  uri = URI.parse(url.to_s.strip)
202
- return if uri.host && uri.host != @config.host
84
+ return if uri.host && uri.host != @host
203
85
 
204
86
  uri.path if uri.path&.start_with?("#{prefix}/")
205
87
  rescue URI::Error
data/lib/kiln/build.rb CHANGED
@@ -10,12 +10,12 @@ module Kiln
10
10
  # layer's own data-md-source.
11
11
  EDITOR_MARKUP = /\sdata-(?:herb-[\w-]+|tensaku-[\w-]+|md-source)=/
12
12
 
13
- attr_reader :app, :config, :pages_dsl, :output, :report, :manifest, :previous_manifest
13
+ attr_reader :app, :config, :output, :report, :manifest
14
14
 
15
15
  def initialize(app: Rails.application, config: Kiln.config, pages: Kiln.pages, output: nil)
16
16
  @app = app
17
17
  @config = config
18
- @pages_dsl = pages
18
+ @pages = pages
19
19
  @output = Pathname(output || config.output_path(app.root))
20
20
  # Pages are written here and replace the output only when the whole build succeeds, so a failed
21
21
  # build leaves the previous output as it was.
@@ -28,7 +28,7 @@ module Kiln
28
28
 
29
29
  # Pages added, removed and changed since the previous build of the configured output, or nil.
30
30
  def changes
31
- previous_manifest&.diff(manifest)
31
+ @previous_manifest&.diff(manifest)
32
32
  end
33
33
 
34
34
  def run
@@ -36,23 +36,12 @@ module Kiln
36
36
  guard_output!
37
37
  guard_dev_middleware!
38
38
  ensure_secret_key_base
39
- cleanup = Assets.precompile(app)
39
+ cleanup = Assets::Compiler.run(app)
40
40
  begin
41
- Assets.check_builds!(app)
42
- prepare_output
43
-
44
- pages = Router.new(app.routes, pages_dsl, report:).pages
45
- pages.reject { it.path == config.not_found }.each { render_page(it) }
46
- render_not_found if config.not_found
47
- report_editor_markup
48
-
49
- Assets.new(renderer:, output: @stage, config:, report:, app:).export
50
- write_files
51
- Assets.copy_public(from: app.root.join("public"), to: @stage, report:, generated: generated_files)
52
- write_redirects if @redirects.any?
53
- Sitemap.new(manifest, url: config.url).write(@stage) if config.url
54
- write_cname if config.cname
55
-
41
+ prepare_stage
42
+ render_pages
43
+ Assets.new(renderer:, writer:, host: config.host, report:, app:).export
44
+ write_extras
56
45
  Verifier.new(@stage, config:).verify(report)
57
46
  publish if report.success?
58
47
  ensure
@@ -69,7 +58,14 @@ module Kiln
69
58
  end
70
59
 
71
60
  def writer
72
- @writer ||= Writer.new(@stage, mode: config.paths)
61
+ @writer ||= Writer.new(@stage, mode: config.paths, report:)
62
+ end
63
+
64
+ def render_pages
65
+ pages = Router.new(app.routes, @pages, report:).pages
66
+ pages.reject { it.path == config.not_found }.each { render_page(it) }
67
+ render_not_found if config.not_found
68
+ report_editor_markup
73
69
  end
74
70
 
75
71
  def render_page(page)
@@ -78,11 +74,10 @@ module Kiln
78
74
  if response.redirect?
79
75
  @redirects << Redirects::Entry.new(from: page.path, to: response.location, status: response.status)
80
76
  elsif response.success?
81
- body = response.html? ? Processors::StripCSRF.call(response.body) : response.body
77
+ body = response.output_body
82
78
  @editor_markup << page.path if response.html? && body.match?(EDITOR_MARKUP)
83
79
  file = writer.write(page.path, response.content_type, body)
84
80
  manifest.add(page.path, file:, body:, content_type: response.content_type, noindex: Sitemap.noindex?(response, body))
85
- report.wrote(file)
86
81
  else
87
82
  report.error(:render, "responded with #{response.status}", path: page.path)
88
83
  end
@@ -90,42 +85,34 @@ module Kiln
90
85
  report.error(:render, describe(error), path: page.path)
91
86
  end
92
87
 
93
- def report_editor_markup
94
- return if @editor_markup.empty?
95
-
96
- pages = @editor_markup.first(3).join(", ") + (@editor_markup.size > 3 ? " and #{@editor_markup.size - 3} more" : "")
97
- report.error(:editor_markup, "data-herb-*, data-tensaku-* or data-md-source attributes reached #{pages}. " \
98
- "Turn off Herb source attribution, Tensaku and Kiln::Content.source_positions outside development, " \
99
- "or build in production.")
100
- end
101
-
88
+ # The not_found path is written only as 404.html, whether or not it is a route.
102
89
  def render_not_found
103
90
  response = Kiln.response_for(config.not_found)
104
91
  unless [ 200, 404 ].include?(response.status)
105
92
  return report.error(:render, "404 page responded with #{response.status}", path: config.not_found)
106
93
  end
107
94
 
108
- body = Processors::StripCSRF.call(response.body)
109
- report.wrote(writer.write_file("404.html", body))
95
+ writer.write_file("404.html", response.output_body)
110
96
  rescue StandardError => error
111
97
  report.error(:render, describe(error), path: config.not_found)
112
98
  end
113
99
 
114
- def write_redirects
115
- report.wrote(Redirects.new(@redirects, host: config.host).write(@stage))
116
- end
100
+ def report_editor_markup
101
+ return if @editor_markup.empty?
117
102
 
118
- # The manifest is build state, not part of the site: it lives in tmp/, and only for the configured
119
- # output, so throwaway builds (tests, temp dirs) never overwrite it.
120
- def manifest_dir
121
- app.root.join("tmp") if output.expand_path == config.output_path(app.root).expand_path
103
+ pages = @editor_markup.first(3).join(", ") + (@editor_markup.size > 3 ? " and #{@editor_markup.size - 3} more" : "")
104
+ report.error(:editor_markup, "data-herb-*, data-tensaku-* or data-md-source attributes reached #{pages}. " \
105
+ "Turn off Herb source attribution, Tensaku and Kiln::Content.source_positions outside development, " \
106
+ "or build in production.")
122
107
  end
123
108
 
124
- def write_manifest
125
- return unless manifest_dir
126
-
127
- FileUtils.mkdir_p(manifest_dir)
128
- manifest.write(manifest_dir)
109
+ # Everything in the output that is not a rendered page or an asset.
110
+ def write_extras
111
+ write_files
112
+ writer.copy_public(app.root.join("public"), generated: generated_files)
113
+ Redirects.new(@redirects, host: config.host).write(writer) if @redirects.any?
114
+ Sitemap.new(manifest, url: config.url).write(writer) if config.url
115
+ write_cname if config.cname
129
116
  end
130
117
 
131
118
  def write_files
@@ -133,7 +120,7 @@ module Kiln
133
120
  source = app.root.join(source)
134
121
  next report.error(:write, "#{source} does not exist", path: "/#{target}") unless source.file?
135
122
 
136
- report.wrote(writer.write_file(target.to_s, source.binread))
123
+ writer.write_file(target.to_s, source.binread)
137
124
  rescue Kiln::Error => error
138
125
  report.error(:write, error.message, path: "/#{target}")
139
126
  end
@@ -149,10 +136,16 @@ module Kiln
149
136
  host = config.cname == true ? config.url && URI(config.url).host : config.cname
150
137
  return report.error(:write, "config.cname = true needs config.url", path: "/CNAME") unless host
151
138
 
152
- report.wrote(writer.write_file("CNAME", "#{host}\n"))
139
+ writer.write_file("CNAME", "#{host}\n")
153
140
  end
154
141
 
155
- def prepare_output
142
+ # The manifest is build state, not part of the site: it lives in tmp/, and only for the configured
143
+ # output, so throwaway builds (tests, temp dirs) never overwrite it.
144
+ def manifest_dir
145
+ app.root.join("tmp") if output.expand_path == config.output_path(app.root).expand_path
146
+ end
147
+
148
+ def prepare_stage
156
149
  previous = manifest_dir&.join(Manifest::FILENAME)
157
150
  @previous_manifest = Manifest.load(previous) if previous&.file?
158
151
  FileUtils.rm_rf(@stage)
@@ -162,7 +155,10 @@ module Kiln
162
155
  def publish
163
156
  FileUtils.rm_rf(output)
164
157
  File.rename(@stage, output)
165
- write_manifest
158
+ return unless manifest_dir
159
+
160
+ FileUtils.mkdir_p(manifest_dir)
161
+ manifest.write(manifest_dir)
166
162
  end
167
163
 
168
164
  # Refuse to wipe anything that contains the app.
@@ -2,7 +2,9 @@ module Kiln
2
2
  module Content
3
3
  module Markdown
4
4
  OPTIONS = {
5
- render: { unsafe: true },
5
+ # Commonmarker turns hardbreaks on by default. Off, a line break inside a paragraph is a
6
+ # space, as CommonMark says, so files wrapped at a column read as whole paragraphs.
7
+ render: { unsafe: true, hardbreaks: false },
6
8
  extension: { table: true, strikethrough: true, autolink: true, header_ids: "" }
7
9
  }.freeze
8
10
  PLUGINS = { syntax_highlighter: nil }.freeze
data/lib/kiln/links.rb ADDED
@@ -0,0 +1,29 @@
1
+ require "json"
2
+
3
+ module Kiln
4
+ # The URLs a page points at, as written in its HTML. The asset export and the verifier both read
5
+ # pages through this.
6
+ module Links
7
+ ATTRIBUTES = %w[href src srcset].freeze
8
+ ELEMENTS = "//*[@href or @src or @srcset]"
9
+
10
+ # URLs in an element's href, src and srcset attributes.
11
+ def self.in(element)
12
+ ATTRIBUTES.flat_map do |name|
13
+ value = element[name]
14
+ next [] if value.nil?
15
+
16
+ name == "srcset" ? value.split(",").filter_map { it.split.first } : [ value ]
17
+ end
18
+ end
19
+
20
+ # Module URLs in an importmap's imports and scopes, or nil when the JSON is not an importmap.
21
+ def self.importmap(json)
22
+ map = JSON.parse(json)
23
+ urls = map.fetch("imports", {}).values + map.fetch("scopes", {}).values.flat_map(&:values)
24
+ urls if urls.all?(String)
25
+ rescue JSON::ParserError, NoMethodError, TypeError
26
+ nil
27
+ end
28
+ end
29
+ end
data/lib/kiln/manifest.rb CHANGED
@@ -12,12 +12,10 @@ module Kiln
12
12
 
13
13
  def initialize(entries = {})
14
14
  @entries = entries
15
- @mutex = Mutex.new
16
15
  end
17
16
 
18
17
  def add(path, file:, body:, content_type:, noindex: false)
19
- entry = { content_type:, digest: Digest::SHA256.hexdigest(body), file: file.to_s, noindex: }
20
- @mutex.synchronize { @entries[path] = entry }
18
+ @entries[path] = { content_type:, digest: Digest::SHA256.hexdigest(body), file: file.to_s, noindex: }
21
19
  end
22
20
 
23
21
  def entries
@@ -22,11 +22,10 @@ module Kiln
22
22
  end
23
23
 
24
24
  # Rules from a copied public/_redirects come first, so hand-written rules win. Returns the filename.
25
- def write(output)
26
- file = Pathname(output).join(FILENAME)
25
+ def write(writer)
26
+ file = writer.output.join(FILENAME)
27
27
  existing = file.exist? ? file.read.chomp.then { it.empty? ? "" : "#{it}\n" } : ""
28
- File.write(file, existing + @entries.map { "#{it.from} #{it.to} #{it.status}\n" }.join)
29
- FILENAME
28
+ writer.write_file(FILENAME, existing + @entries.map { "#{it.from} #{it.to} #{it.status}\n" }.join)
30
29
  end
31
30
 
32
31
  private
data/lib/kiln/report.rb CHANGED
@@ -3,30 +3,29 @@ module Kiln
3
3
  class Report
4
4
  Entry = Data.define(:kind, :message, :path)
5
5
 
6
- KINDS = %i[uncovered_route render editor_markup asset broken_link missing_anchor importmap redirect write other].freeze
7
-
8
- attr_reader :errors, :warnings, :written
6
+ attr_reader :errors, :warnings
9
7
 
10
8
  def initialize
11
9
  @errors = []
12
10
  @warnings = []
13
- @written = []
14
- @mutex = Mutex.new
11
+ @written = Set.new
15
12
  end
16
13
 
17
14
  def error(kind, message, path: nil)
18
- @mutex.synchronize { @errors << Entry.new(kind:, message:, path:) }
15
+ @errors << Entry.new(kind:, message:, path:)
19
16
  end
20
17
 
21
18
  def warn(kind, message, path: nil)
22
- @mutex.synchronize { @warnings << Entry.new(kind:, message:, path:) }
19
+ @warnings << Entry.new(kind:, message:, path:)
23
20
  end
24
21
 
25
- # Records a file written to the output (relative path).
22
+ # Records a file written to the output (relative path). A file written twice counts once.
26
23
  def wrote(file)
27
- @mutex.synchronize { @written << file.to_s }
24
+ @written << file.to_s
28
25
  end
29
26
 
27
+ def written = @written.to_a
28
+
30
29
  def success? = errors.empty?
31
30
  def failure? = !success?
32
31
 
@@ -42,7 +41,7 @@ module Kiln
42
41
  entries.each { lines << " #{format_entry(it)}" }
43
42
  end
44
43
  else
45
- lines << "#{title} succeeded: #{written.size} #{"file".pluralize(written.size)} written."
44
+ lines << "#{title} succeeded: #{@written.size} #{"file".pluralize(@written.size)} written."
46
45
  end
47
46
  lines.join("\n")
48
47
  end
data/lib/kiln/response.rb CHANGED
@@ -9,5 +9,10 @@ module Kiln
9
9
  def success? = status.between?(200, 299)
10
10
  def redirect? = [ 301, 302, 303, 307, 308 ].include?(status)
11
11
  def location = headers["location"]
12
+
13
+ # The body as a build writes it: HTML without CSRF tokens, anything else unchanged.
14
+ def output_body
15
+ html? ? Processors::StripCSRF.call(body) : body
16
+ end
12
17
  end
13
18
  end
data/lib/kiln/sitemap.rb CHANGED
@@ -20,19 +20,19 @@ module Kiln
20
20
  @url = url.chomp("/")
21
21
  end
22
22
 
23
- def write(output)
23
+ # Returns the relative file written.
24
+ def write(writer)
24
25
  urls = @manifest.entries.filter_map do |path, entry|
25
26
  next if entry[:noindex] || entry[:content_type] != "text/html"
26
27
 
27
28
  " <url><loc>#{ERB::Util.html_escape(@url + served_path(path, entry[:file]))}</loc></url>\n"
28
29
  end
29
30
 
30
- File.write(Pathname(output).join(FILENAME), <<~XML)
31
+ writer.write_file(FILENAME, <<~XML)
31
32
  <?xml version="1.0" encoding="UTF-8"?>
32
33
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
33
34
  #{urls.join}</urlset>
34
35
  XML
35
- FILENAME
36
36
  end
37
37
 
38
38
  private
@@ -12,8 +12,12 @@ module Kiln
12
12
  #
13
13
  # test("builds repeatably") { kiln_build(repeatable: true) { assert it.join("index.html").file? } }
14
14
  # test("home page") { assert_page "/", selector: "h1", text: "Home" }
15
+ # test("sitemap") { assert kiln_site.join("sitemap.xml").file? }
15
16
  # end
16
17
  module TestHelper
18
+ # Builds shared by kiln_site, one per test class, app and config.
19
+ SITES = {}
20
+
17
21
  # Builds into a temp dir, fails with the report on any error, and yields the output path.
18
22
  # Returns the Build when no block is given (the temp dir is then left for the caller).
19
23
  # With repeatable: true it builds a second time and fails with the diff when the two outputs
@@ -35,14 +39,26 @@ module Kiln
35
39
  FileUtils.rm_rf(dir) if dir && block_given?
36
40
  end
37
41
 
42
+ # The output of one build shared by every test in the class, as a Pathname. The first call builds
43
+ # into a temp dir, removed when the test run ends. When that build fails, every test that calls
44
+ # kiln_site fails with its report, and the site is not built again.
45
+ def kiln_site(app: Rails.application, config: Kiln.config)
46
+ build = SITES[[ self.class, app, config ]] ||= begin
47
+ dir = Pathname(Dir.mktmpdir("kiln-site"))
48
+ Minitest.after_run { FileUtils.rm_rf(dir) }
49
+ Build.new(app:, config:, output: dir).tap(&:run)
50
+ end
51
+ assert build.report.success?, build.report.to_s
52
+ build.output
53
+ end
54
+
38
55
  # Renders one path the way a build does (CSRF tokens stripped) and asserts it succeeds.
39
56
  # Optional `selector` must match, and contain `text` when given. Returns the processed body.
40
57
  def assert_page(path, status: 200, selector: nil, text: nil, app: Rails.application, config: Kiln.config)
41
58
  response = Kiln.building! { Renderer.new(app, host: config.host).get(path) }
42
59
  assert_equal status, response.status, "Expected #{path} to respond with #{status}"
43
60
 
44
- body = response.body
45
- body = Processors::StripCSRF.call(body) if response.html?
61
+ body = response.output_body
46
62
 
47
63
  if selector
48
64
  nodes = Nokogiri::HTML5(body).css(selector)
data/lib/kiln/verifier.rb CHANGED
@@ -1,8 +1,6 @@
1
1
  module Kiln
2
2
  # Checks the built output: internal links, anchors and importmap modules.
3
3
  class Verifier
4
- LINK_ATTRIBUTES = %w[href src srcset].freeze
5
-
6
4
  def initialize(output, config:)
7
5
  @output = Pathname(output)
8
6
  @host = config.host.downcase
@@ -25,23 +23,12 @@ module Kiln
25
23
  doc = parse(@output.join(file))
26
24
  skipped = @skip ? doc.css(@skip).flat_map { [ it, *it.css("*") ] }.to_set : Set.new
27
25
 
28
- doc.xpath("//*[@href or @src or @srcset]").each do |element|
29
- next if skipped.include?(element)
30
-
31
- urls_in(element).each { check_link(it, page) }
26
+ doc.xpath(Links::ELEMENTS).each do |element|
27
+ Links.in(element).each { check_link(it, page) } unless skipped.include?(element)
32
28
  end
33
29
  doc.css('script[type="importmap"]').each { check_importmap(it.text, page) }
34
30
  end
35
31
 
36
- def urls_in(element)
37
- LINK_ATTRIBUTES.flat_map do |name|
38
- value = element[name]
39
- next [] if value.nil?
40
-
41
- name == "srcset" ? value.split(",").filter_map { it.split.first } : [ value ]
42
- end
43
- end
44
-
45
32
  def check_link(url, page)
46
33
  uri = internal_uri(url, page) or return
47
34
  target = @resolver.resolve(uri.path)
@@ -57,16 +44,14 @@ module Kiln
57
44
  end
58
45
 
59
46
  def check_importmap(json, page)
60
- map = JSON.parse(json)
61
- urls = map.fetch("imports", {}).values + map.fetch("scopes", {}).values.flat_map(&:values)
47
+ urls = Links.importmap(json) or return error(:importmap, "invalid importmap JSON", page)
48
+
62
49
  urls.each do |url|
63
50
  uri = internal_uri(url, page)
64
51
  error(:importmap, url, page) if uri && @resolver.resolve(uri.path).nil?
65
52
  rescue URI::Error
66
53
  error(:importmap, url, page)
67
54
  end
68
- rescue JSON::ParserError, NoMethodError, TypeError
69
- error(:importmap, "invalid importmap JSON", page)
70
55
  end
71
56
 
72
57
  # The URL resolved against the page, or nil when it points somewhere Kiln doesn't serve.
data/lib/kiln/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Kiln
2
- VERSION = "0.1.4"
2
+ VERSION = "0.1.6"
3
3
  end
data/lib/kiln/writer.rb CHANGED
@@ -1,13 +1,17 @@
1
1
  require "fileutils"
2
2
 
3
3
  module Kiln
4
- # Maps request paths to files under the output directory and writes them.
4
+ # Every file a build writes goes through here: it maps request paths to files under the output
5
+ # directory, refuses paths outside it, and records each file in the report.
5
6
  class Writer
6
- def initialize(output, mode:)
7
+ attr_reader :output
8
+
9
+ def initialize(output, mode:, report:)
7
10
  raise Kiln::Error, "Unknown paths mode #{mode.inspect} (expected :directory or :file)" unless %i[directory file].include?(mode)
8
11
 
9
12
  @output = Pathname(output).expand_path
10
13
  @mode = mode
14
+ @report = report
11
15
  end
12
16
 
13
17
  # Relative file for a request path: "/now" -> "now/index.html" (or "now.html" in :file mode).
@@ -31,7 +35,7 @@ module Kiln
31
35
  write_file(file_for(path, content_type), body)
32
36
  end
33
37
 
34
- # Writes a file at a path relative to the output directory.
38
+ # Writes a file at a path relative to the output directory. Returns the relative path.
35
39
  def write_file(relative, body)
36
40
  target = @output.join(relative).expand_path
37
41
  unless target.to_s.start_with?("#{@output}/")
@@ -40,9 +44,28 @@ module Kiln
40
44
 
41
45
  FileUtils.mkdir_p(target.dirname)
42
46
  File.binwrite(target, body)
47
+ @report.wrote(relative)
43
48
  relative.to_s
44
49
  end
45
50
 
51
+ # Copies public/ into the output, minus public/assets. Files already in the output win, with a
52
+ # warning unless they are listed in `generated` (files Kiln writes on purpose, like 404.html).
53
+ def copy_public(from, generated: [])
54
+ from = Pathname(from)
55
+ return unless from.directory?
56
+
57
+ Dir.glob("**/*", File::FNM_DOTMATCH, base: from).sort.each do |relative|
58
+ source = from.join(relative)
59
+ next if source.directory? || relative.start_with?("assets/")
60
+
61
+ if @output.join(relative).exist?
62
+ @report.warn(:write, "public/#{relative} not copied, a rendered file already exists", path: "/#{relative}") unless generated.include?(relative)
63
+ else
64
+ write_file(relative, source.binread)
65
+ end
66
+ end
67
+ end
68
+
46
69
  private
47
70
  def extension_for(content_type)
48
71
  symbol = Mime::Type.lookup(content_type).symbol if content_type.present?
@@ -53,7 +76,7 @@ module Kiln
53
76
  segments = path.to_s.split("?").first.to_s.split("/").reject(&:empty?).map do
54
77
  Rack::Utils.unescape_path(it).force_encoding(Encoding::UTF_8)
55
78
  end
56
- if segments.any? { it == ".." || it == "." || it.include?("/") || it.include?("\0") }
79
+ if segments.any? { it == ".." || it == "." || it.include?("/") || it.include?("\0") || !it.valid_encoding? }
57
80
  raise Kiln::Error, "Invalid path #{path.inspect}"
58
81
  end
59
82
  segments
data/lib/kiln.rb CHANGED
@@ -57,7 +57,7 @@ module Kiln
57
57
  response = response_for(path)
58
58
  raise Error, "Kiln.render(#{path.inspect}) got a #{response.status} response" unless response.success?
59
59
 
60
- response.html? ? Processors::StripCSRF.call(response.body) : response.body
60
+ response.output_body
61
61
  end
62
62
 
63
63
  # The app's response for a path, cached for the build so the build and Kiln.render share it.
@@ -1,6 +1,6 @@
1
1
  namespace :kiln do
2
2
  desc "Serve the built output like a static host (PORT, default 4000; BIND, default localhost)"
3
- task serve: :environment do
3
+ task serve: [ :secret_key_base, :environment ] do
4
4
  output = Kiln.config.output_path
5
5
  abort "Kiln: #{output} does not exist. Run kiln:build first." unless output.directory?
6
6
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kiln
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.4
4
+ version: 0.1.6
5
5
  platform: ruby
6
6
  authors:
7
7
  - David Afonso
@@ -79,6 +79,7 @@ files:
79
79
  - README.md
80
80
  - lib/kiln.rb
81
81
  - lib/kiln/assets.rb
82
+ - lib/kiln/assets/compiler.rb
82
83
  - lib/kiln/build.rb
83
84
  - lib/kiln/build_cache.rb
84
85
  - lib/kiln/configuration.rb
@@ -88,6 +89,7 @@ files:
88
89
  - lib/kiln/content/frontmatter.rb
89
90
  - lib/kiln/content/handlers.rb
90
91
  - lib/kiln/content/markdown.rb
92
+ - lib/kiln/links.rb
91
93
  - lib/kiln/manifest.rb
92
94
  - lib/kiln/page.rb
93
95
  - lib/kiln/pages.rb