kiln 0.1.3 → 0.1.5

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: a916926140a7c5f9d1863925d43a6c3d74f176ce78c5f8c2859e53398788189c
4
- data.tar.gz: 2da891ee303f11614b4c7bb128e979bad49aed63d192c0b0e1a84eaa5ab0e82a
3
+ metadata.gz: 4ed9b4f5cdd14178de9a2c3ece073c6a5d07a70f7eb063642e8aa9aee99b1dbf
4
+ data.tar.gz: 7e1ae75b320371b33dc381c60c4565024adaf9e2cfa5f9ecff8bac681de0545f
5
5
  SHA512:
6
- metadata.gz: 3498e1a0cd83aa9b30ed67290039b7ab48b66089b38cd2ed5e96cee491b304dfb209779c7eb689d60ef5f7803794a97285a7c5674088f291dd9b83da7209fb43
7
- data.tar.gz: 16d49359021d9d762e4faa27ea0ec514732f444370da92604b98b4834959f708b717e17fd3f190ce7642d96cba7d30cd183d813b61084b22ccbd1617602d9c7f
6
+ metadata.gz: 0e3bab2700e117480fc97eb2b58bf05584034c6cd3d2d687d32580fda405b5ee4a1f09b93774dda48e346f2e080369bd1a8201ae0495219a2e76543d50d114b7
7
+ data.tar.gz: 60c4146504eb754b85a4ae33bbe8e5bf4d0f02c3fa6ebec33ef7ae9960586c73a3e0ffe4f84bcc21dd0f38d8f64cc190529c89d514fc7be1bd23ae50c0e8090b
data/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.5 (2026-11-13)
4
+
5
+ Breaking:
6
+
7
+ - `Kiln::Assets.precompile`, `precompile?` and `check_builds!` move to `Kiln::Assets::Compiler`
8
+ (`precompile` is now `Compiler.run`, which also checks `app/assets/builds`).
9
+ `Kiln::Assets.copy_public` is now `Kiln::Writer#copy_public`.
10
+ - `Kiln::Writer.new` takes `report:`, and every file it writes is recorded there.
11
+ `Kiln::Assets.new` takes `writer:` and `host:` instead of `output:` and `config:`.
12
+ `Kiln::Sitemap#write` and `Kiln::Redirects#write` take a writer instead of a directory.
13
+ - `Kiln::Report::KINDS` and `Kiln::Build#pages_dsl` and `#previous_manifest` are removed.
14
+
15
+ Added:
16
+
17
+ - `kiln_site` in `Kiln::TestHelper` returns the output of one build shared by every test in the
18
+ class. The directory is removed when the test run ends.
19
+
20
+ Fixed:
21
+
22
+ - An asset path that resolves outside the output directory is reported as an asset error instead
23
+ of being written there.
24
+ - The build summary counts `sitemap.xml`, and counts a copied `public/_redirects` that the build
25
+ extends once.
26
+ - `kiln:serve` boots an app without its own secret the way `kiln:build` does, instead of failing
27
+ with "Missing `secret_key_base`" in production.
28
+ - A page path that unescapes to invalid UTF-8 is reported as an invalid path.
29
+
30
+ ## 0.1.4 (2026-11-13)
31
+
32
+ Breaking:
33
+
34
+ - A production build always compiles assets into a temporary directory. An existing
35
+ `public/assets/.manifest.json` no longer skips the compile, so a stale `public/assets` can't ship
36
+ old assets.
37
+
3
38
  ## 0.1.3 (2026-11-08)
4
39
 
5
40
  Breaking:
data/README.md CHANGED
@@ -1,3 +1,7 @@
1
+ <p align="center">
2
+ <img src="assets/brand/logo.png" alt="Kiln mascot, a small brick kiln" width="150">
3
+ </p>
4
+
1
5
  <h1 align="center">Kiln</h1>
2
6
 
3
7
  <p align="center">
@@ -8,28 +12,28 @@
8
12
  </p>
9
13
 
10
14
  <p align="center">
11
- Fire a Rails app into a static site.
15
+ Build a Rails app into a static site.
12
16
  </p>
13
17
 
14
18
  <p align="center">
15
- <a href="https://kiln.davafons.com">Docs</a> ·
19
+ <a href="https://kiln.davafons.com">Documentation</a> ·
16
20
  <a href="https://kiln.davafons.com/installation/">Installation</a> ·
17
21
  <a href="CHANGELOG.md">Changelog</a>
18
22
  </p>
19
23
 
20
- Kiln renders every GET route of a Rails app through Rack and writes plain files that any static host can serve. You build pages with normal Rails: routes, controllers, views, helpers, Turbo and Stimulus. Development stays `bin/rails server`.
21
-
22
- Routes are the page list. A route that needs params and has no param source fails the build, and every render error, missing asset and broken link is reported at once. Kiln knows nothing about your data: models and repositories stay ordinary app code.
24
+ Kiln sends a GET request through Rack for every route of a Rails app and writes each response to a file. Any static host can serve the result. You write the site with routes, controllers, views, the asset pipeline, Turbo and Stimulus, and work on it with `bin/rails server`.
23
25
 
24
- Requires Ruby 4.0+ and Rails 8.1+.
26
+ Kiln needs Ruby 4.0 or later and Rails 8.1 or later. It is at an early version, and the [changelog](CHANGELOG.md) lists breaking changes.
25
27
 
26
- ## Quick start
28
+ ## Build a site
27
29
 
28
30
  ```ruby
29
31
  # Gemfile
30
32
  gem "kiln"
31
33
  ```
32
34
 
35
+ Routes without params need no declaration. Routes with params need a param source or a skip:
36
+
33
37
  ```ruby
34
38
  # config/kiln.rb
35
39
  Kiln.configure do |config|
@@ -45,10 +49,33 @@ end
45
49
 
46
50
  ```sh
47
51
  RAILS_ENV=production bin/rails kiln:build # write the site to dist/
48
- bin/rails kiln:serve # look at it as a static host serves it
52
+ bin/rails kiln:serve # serve dist/ at http://localhost:4000
49
53
  ```
50
54
 
51
- The [documentation](https://kiln.davafons.com) covers declaring pages, configuration, writing views for a build, the Markdown content layer, testing, deploying and the known limits.
55
+ A build reports every render error, missing asset, broken link and route without params at once, exits with status 1 and leaves the previous output in place. See [Build](https://kiln.davafons.com/build/#errors) for each message.
56
+
57
+ ## Test it
58
+
59
+ ```ruby
60
+ require "kiln/test_helper"
61
+
62
+ class StaticSiteTest < ActiveSupport::TestCase
63
+ include Kiln::TestHelper
64
+
65
+ test("the site builds repeatably") { kiln_build(repeatable: true) { assert it.join("index.html").file? } }
66
+ test("the home page") { assert_page "/", selector: "h1", text: "Welcome" }
67
+ test("the sitemap") { assert kiln_site.join("sitemap.xml").file? }
68
+ end
69
+ ```
70
+
71
+ ## Documentation
72
+
73
+ Start with the [introduction](https://kiln.davafons.com).
74
+
75
+ - [Install Kiln](https://kiln.davafons.com/installation/) and declare [pages](https://kiln.davafons.com/pages/).
76
+ - Read about [views and assets](https://kiln.davafons.com/views/) during a build, and the [Markdown](https://kiln.davafons.com/content/) layer.
77
+ - [Test](https://kiln.davafons.com/testing/) and [deploy](https://kiln.davafons.com/deploying/) the site.
78
+ - Look up [configuration](https://kiln.davafons.com/configuration/), the [build](https://kiln.davafons.com/build/) and the [known limits](https://kiln.davafons.com/limits/).
52
79
 
53
80
  ## Develop Kiln
54
81
 
@@ -58,7 +85,7 @@ bin/test
58
85
  bin/lint # RuboCop and bin/house-rules
59
86
  ```
60
87
 
61
- `test/dummy` is the Rails app the tests build. `docs/` is the documentation site, a Rails app that uses this repository's Kiln. Run `bin/rails server` there to work on it, and `RAILS_ENV=production bin/rails kiln:build` and `bin/rails test` to check it; CI runs both. `bin/house-rules` rejects em dashes, AI attribution, leftover tool-call markup, filler phrases and dead links in Markdown. [AGENTS.md](AGENTS.md) holds the rules a script cannot check.
88
+ `test/dummy` is the Rails app the tests build. `docs/` is the documentation site, a Rails app that uses this repository's Kiln. Run `bin/rails server` there to work on it, and `RAILS_ENV=production bin/rails kiln:build` and `bin/rails test` to check it; CI runs both. [AGENTS.md](AGENTS.md) holds the rules a script cannot check.
62
89
 
63
90
  Releases publish from a `vX.Y.Z` tag that matches `Kiln::VERSION`. CI runs first, then the release workflow publishes to RubyGems through trusted publishing.
64
91
 
@@ -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,106 +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
- def precompile?(app)
41
- assets = app.config.respond_to?(:assets) && app.config.assets
42
- return false unless assets.respond_to?(:server) && assets.manifest_path
43
-
44
- !assets.server && !Pathname(assets.manifest_path).exist?
45
- end
46
-
47
- # Propshaft only adds load paths that exist at boot. On a fresh checkout, a bundler such as
48
- # tailwindcss:build creates app/assets/builds during the build, too late to be served.
49
- def check_builds!(app)
50
- builds = app.root.join("app/assets/builds")
51
- paths = app.config.respond_to?(:assets) && app.config.assets.respond_to?(:paths) && app.config.assets.paths
52
- return unless paths && builds.directory? && paths.none? { Pathname(it) == builds }
53
-
54
- raise Kiln::Error, "app/assets/builds did not exist when the app booted, so its assets are not served. " \
55
- "Track app/assets/builds/.keep in version control, as a new Rails app does, and build again."
56
- end
57
-
58
- # Copies public/ into the output, minus public/assets. Files already in the output win, with a
59
- # warning unless they are listed in `generated` (files Kiln writes on purpose, like 404.html).
60
- def copy_public(from:, to:, report:, generated: [])
61
- from = Pathname(from)
62
- return unless from.directory?
63
-
64
- Dir.glob("**/*", File::FNM_DOTMATCH, base: from).sort.each do |relative|
65
- source = from.join(relative)
66
- next if source.directory? || relative.start_with?("assets/")
67
-
68
- target = Pathname(to).join(relative)
69
- if target.exist?
70
- next if generated.include?(relative)
71
-
72
- report.warn(:write, "public/#{relative} not copied, a rendered file already exists", path: "/#{relative}")
73
- else
74
- FileUtils.mkdir_p(target.dirname)
75
- FileUtils.cp(source, target)
76
- report.wrote(relative)
77
- end
78
- end
79
- end
80
-
81
- private
82
- def build_bundles(app)
83
- precompile_task(app)&.prerequisite_tasks&.each do |task|
84
- next if task.name.end_with?("environment")
85
-
86
- task.reenable
87
- task.invoke
88
- rescue StandardError => error
89
- raise Kiln::Error, "#{task.name} failed: #{error.class}: #{error.message}"
90
- end
91
- nil
92
- end
93
-
94
- def precompile_task(app)
95
- require "rake"
96
- app.load_tasks unless Rake::Task.task_defined?("assets:precompile")
97
- Rake::Task["assets:precompile"] if Rake::Task.task_defined?("assets:precompile")
98
- end
99
-
100
- def run_precompile(app)
101
- task = precompile_task(app)
102
- task.reenable
103
- task.invoke
104
- rescue StandardError => error
105
- raise Kiln::Error, "assets:precompile failed: #{error.class}: #{error.message}"
106
- end
107
- end
108
-
109
- def initialize(renderer:, output:, config:, report:, app: Rails.application)
11
+ def initialize(renderer:, writer:, host:, report:, app: Rails.application)
110
12
  @renderer = renderer
111
- @output = Pathname(output)
112
- @config = config
13
+ @writer = writer
14
+ @host = host
113
15
  @report = report
114
16
  @app = app
115
17
  end
@@ -139,7 +41,7 @@ module Kiln
139
41
 
140
42
  extension = File.extname(path)
141
43
  body = Processors::StripSourceMaps.call(body) if %w[.js .css].include?(extension)
142
- write(path, body)
44
+ @writer.write_file(path.delete_prefix("/"), body)
143
45
  extension == ".css" ? css_references(path, body) : []
144
46
  rescue StandardError => error
145
47
  @report.error(:asset, "#{error.class}: #{error.message}", path:)
@@ -156,33 +58,15 @@ module Kiln
156
58
  file.binread if file.to_s.start_with?("#{dir}/") && file.file?
157
59
  end
158
60
 
159
- def write(path, body)
160
- relative = path.delete_prefix("/")
161
- file = @output.join(relative)
162
- FileUtils.mkdir_p(file.dirname)
163
- File.binwrite(file, body)
164
- @report.wrote(relative)
165
- end
166
-
61
+ # Invalid importmaps are left to the verifier, which reports them with their page.
167
62
  def referenced_paths
168
- Dir.glob("**/*.html", base: @output).sort.flat_map do |relative|
169
- 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 }
170
67
  end.filter_map { asset_path(it) }.uniq
171
68
  end
172
69
 
173
- def html_references(doc)
174
- urls = doc.xpath("//@href | //@src").map(&:value)
175
- urls += doc.xpath("//@srcset").flat_map { |attr| attr.value.split(",").map { it.strip.split(/\s+/).first } }
176
- doc.css('script[type="importmap"]').each do |script|
177
- map = JSON.parse(script.text)
178
- urls += map.fetch("imports", {}).values
179
- urls += map.fetch("scopes", {}).values.flat_map(&:values)
180
- rescue JSON::ParserError
181
- @report.error(:asset, "invalid importmap JSON")
182
- end
183
- urls.compact
184
- end
185
-
186
70
  def css_references(css_path, body)
187
71
  body.to_s.scan(CSS_REFERENCE).filter_map do |url, import|
188
72
  ref = (url || import).strip
@@ -197,7 +81,7 @@ module Kiln
197
81
  # Normalizes a URL to an asset path ("/assets/app-abc.css"), or nil when it isn't one of ours.
198
82
  def asset_path(url)
199
83
  uri = URI.parse(url.to_s.strip)
200
- return if uri.host && uri.host != @config.host
84
+ return if uri.host && uri.host != @host
201
85
 
202
86
  uri.path if uri.path&.start_with?("#{prefix}/")
203
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.
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.3"
2
+ VERSION = "0.1.5"
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.3
4
+ version: 0.1.5
5
5
  platform: ruby
6
6
  authors:
7
7
  - David Afonso
@@ -66,8 +66,8 @@ dependencies:
66
66
  - !ruby/object:Gem::Version
67
67
  version: '2.6'
68
68
  description: Kiln renders every GET route of a Rails app through Rack and writes plain
69
- files that any static host can serve. Routes are the single source of truth, and
70
- the build fails loudly.
69
+ files that any static host can serve. Every GET route is accounted for, and a build
70
+ reports every error at once.
71
71
  email:
72
72
  - dav@davafons.com
73
73
  executables: []
@@ -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