kiln 0.1.1 → 0.1.3

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: 8ba761c39b8d2ffe60d03a4cdf48fdbb6ab1a7d4717b9716ab7107423dd2b2f1
4
- data.tar.gz: 29f9eb12df579857663e8a44b1713928c7b7bbd4106da3cd6b52e645b2791a0f
3
+ metadata.gz: a916926140a7c5f9d1863925d43a6c3d74f176ce78c5f8c2859e53398788189c
4
+ data.tar.gz: 2da891ee303f11614b4c7bb128e979bad49aed63d192c0b0e1a84eaa5ab0e82a
5
5
  SHA512:
6
- metadata.gz: 6597f99b761b60cdc3dcae600c18ebd8beab61e8ab82cd4fec4c57d797ba7f03213669ba5aa458338f68e508d7bf67a6dd582fb0d97e45ec7ac3b7c1b3725aac
7
- data.tar.gz: c2036e9a40ba3458de6ecedb40da6a84b2e4a36775ef003e711d2a198fa1f566a5574660913df4fc5f168b553c03d04b46f32bd73df801c4b5d4895f0d2e8875
6
+ metadata.gz: 3498e1a0cd83aa9b30ed67290039b7ab48b66089b38cd2ed5e96cee491b304dfb209779c7eb689d60ef5f7803794a97285a7c5674088f291dd9b83da7209fb43
7
+ data.tar.gz: 16d49359021d9d762e4faa27ea0ec514732f444370da92604b98b4834959f708b717e17fd3f190ce7642d96cba7d30cd183d813b61084b22ccbd1617602d9c7f
data/CHANGELOG.md CHANGED
@@ -1,5 +1,89 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.3 (2026-11-08)
4
+
5
+ Breaking:
6
+
7
+ - With `paths: :directory`, route helpers add a trailing slash (`about_path` is `/about/`), the URL a
8
+ static host serves `about/index.html` at. Kiln sets `trailing_slash: true` in the app's
9
+ `default_url_options` unless the app sets it. Paths with a dot keep no slash.
10
+ - The sitemap lists a page written as `now/index.html` at `/now/` instead of `/now`. Pages written
11
+ as `now.html` keep `/now`.
12
+ - Source positions use `data-md-source` instead of `data-tensaku-md`, and
13
+ `Kiln::Content.source_positions` is off until the app turns it on. Kiln no longer checks whether
14
+ Tensaku is loaded: set `Kiln::Content.source_positions = Rails.env.development?`.
15
+ - `paginate` is removed. A value list does the same:
16
+ `params :blog_page, page: -> { 2..Post.count.fdiv(10).ceil }`.
17
+ - Highlighted code blocks carry the fence's language as `data-language`, also when Rouge has no
18
+ lexer for it. Code that matches `<pre class="highlight ..."><code>` with a regex should select
19
+ `pre.highlight` instead.
20
+
21
+ - A build writes into `.OUTPUT.kiln-build` next to the output directory and replaces the output
22
+ only when it succeeds. A failed build leaves the previous output, and `tmp/kiln-manifest.json`,
23
+ as they were, instead of a half-written directory.
24
+
25
+ Added:
26
+
27
+ - `Kiln.render(path)` returns another page's body as the build writes it, for pages made from other
28
+ pages such as a search index. During a build each page is rendered once, shared between the build
29
+ and every `Kiln.render` call.
30
+ - `params :post, -> { ... }, locale: [ nil, "es" ]` combines a source with value lists.
31
+ - `Kiln::Content.file(path)` reads one Markdown file outside the content directory, such as a
32
+ README or CONTRIBUTING.md, as an entry with frontmatter, `html` and source positions. It is read
33
+ again when the file changes, and once per build. A name that does not end in `.md` raises
34
+ `ArgumentError`.
35
+ - The last line of `kiln:build` names the Rails environment the build ran in.
36
+
37
+ Fixed:
38
+
39
+ - `kiln:build` boots an app without its own secret with `SECRET_KEY_BASE_DUMMY`, so gems that read
40
+ `secret_key_base` while booting (turbo-rails) no longer fail the build.
41
+
42
+ ## 0.1.2 (2026-11-07)
43
+
44
+ Breaking:
45
+
46
+ - `Kiln.build_cache.fetch` caches only while `Kiln.building?`. Outside a build it runs the block
47
+ every time. `read`, `write` and `delete` are removed.
48
+ - `assert_repeatable_build` is removed. Use `kiln_build(repeatable: true) { |output| ... }`.
49
+ - In collections, `SLUG.LOCALE.md` (such as `2026-08.es.md`) is a translation of `SLUG.md` instead
50
+ of its own entry. Translations stay out of `all`, `find` and `each`, and a translation without
51
+ its entry fails when the collection loads.
52
+ - A collection filename that is only a date, such as `2026-08-01.md`, now sets `published_at`.
53
+ - Removed options: `config.verify` (every build verifies), `config.absolute_urls`,
54
+ `config.external_links`, `config.processors`, `config.before_build`, `config.after_build`,
55
+ `config.strip_source_maps` (source maps are always stripped), `config.sitemap` (written whenever
56
+ `url` is set), `config.host=` (the host comes from `url`, else `localhost`), `config.assets`
57
+ (only referenced assets are exported), `config.redirects` (always `_redirects`; the
58
+ `:meta_refresh`, `:both` and `false` modes are gone) and `config.copy_public` (`public/` is always
59
+ copied).
60
+ - Removed `Kiln::Processors.apply`, `Kiln::Processors::Context`, `Kiln::Build::Context`, and the
61
+ `AbsoluteUrls` and `ExternalLinks` processors.
62
+ - The content layer drops preview tokens: `Collection#find` takes only a slug, and
63
+ `Entry#preview_token` and `Kiln::Content.preview_secret` are removed. Drafts and scheduled
64
+ entries still show in development when Kiln is not building.
65
+
66
+ Added:
67
+
68
+ - `params :page, locale: [ nil, "es", "ja" ]` builds every combination of value lists. `nil`
69
+ leaves the key out, for optional segments. A list may be a lambda, called at build time.
70
+ - `kiln_build(repeatable: true)` builds twice, fails with the diff when the outputs differ, and
71
+ yields the first output.
72
+ - `entry.translation(:es)` and `entry.locale` in the content layer.
73
+ - Collection filenames may start with a `YYYY-MM` date, which means the 1st of that month.
74
+ - `Kiln::Content::Markdown.render_inline(text)` renders a single paragraph without its `<p>`.
75
+ - `config.cname = true` writes `CNAME` with the host from `config.url`.
76
+
77
+ Fixed:
78
+
79
+ - A production build precompiles assets into a temporary directory instead of `public/assets`, so
80
+ a development server that boots during the build no longer loads the production manifest.
81
+ Compiled assets are exported from that directory, and the build no longer needs
82
+ `config.public_file_server.enabled`.
83
+ - When `app/assets/builds` is created after boot (a fresh checkout without
84
+ `app/assets/builds/.keep`), the build stops with one error that says to track the `.keep` file,
85
+ instead of one missing-asset error per page.
86
+
3
87
  ## 0.1.1 (2026-11-07)
4
88
 
5
89
  - Kiln has two tasks, `kiln:build` and `kiln:serve`. `kiln:verify`, `kiln:routes` and `kiln:check` are removed: every build verifies and reports uncovered routes, and committed output can be checked with `git status --porcelain` after a build.
data/README.md CHANGED
@@ -12,7 +12,8 @@
12
12
  </p>
13
13
 
14
14
  <p align="center">
15
- <a href="#configuration">Configuration</a> ·
15
+ <a href="https://kiln.davafons.com">Docs</a> ·
16
+ <a href="https://kiln.davafons.com/installation/">Installation</a> ·
16
17
  <a href="CHANGELOG.md">Changelog</a>
17
18
  </p>
18
19
 
@@ -20,7 +21,9 @@ Kiln renders every GET route of a Rails app through Rack and writes plain files
20
21
 
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.
22
23
 
23
- ## Build a site
24
+ Requires Ruby 4.0+ and Rails 8.1+.
25
+
26
+ ## Quick start
24
27
 
25
28
  ```ruby
26
29
  # Gemfile
@@ -41,132 +44,11 @@ end
41
44
  ```
42
45
 
43
46
  ```sh
44
- RAILS_ENV=production bin/rails kiln:build
45
- ```
46
-
47
- The site lands in `dist/`. Kiln precompiles assets in-process, renders each page, exports the assets the pages reference, copies `public/`, and writes `_redirects`, `sitemap.xml` and `404.html`. Then it checks every internal link, anchor and importmap module, and exits non-zero on any problem.
48
-
49
- ## Declare the pages
50
-
51
- A GET route with no required params is built automatically. A route with params needs a param source:
52
-
53
- ```ruby
54
- Kiln.pages do
55
- params :post, -> { Post.published.map { { slug: it.slug } } }
56
- params :page, -> { %w[en es ja].map { { locale: it } } + [ {} ] } # scope "(:locale)"
57
- paginate :blog_page, per: 10, total: -> { Post.count }, start: 2 # /blog/page/2, /blog/page/3, ...
58
- skip :search, reason: "dynamic"
59
- end
60
- ```
61
-
62
- A route that needs params and has neither a param source nor a skip fails the build, and the error names the line to add. Rails internals, the health check, mounted engines and turbo-rails' native navigation routes are skipped by default. Redirect routes become redirects, and mounted Rack apps are built like any other route.
63
-
64
- Feeds, `robots.txt`, `llms.txt` and JSON files are ordinary routes with views. The content type picks the extension, so `get "api"` rendering JSON is written as `api.json`.
65
-
66
- ## Develop and ship
67
-
68
- Develop with `bin/rails server` and whatever reloading the app already has, such as Hotwire Spark. Kiln adds no dev server. It has two commands:
69
-
70
- ```sh
71
- RAILS_ENV=production bin/rails kiln:build # write the site; CI and deploys run this
72
- bin/rails kiln:serve # look at the output as a static host serves it
73
- ```
74
-
75
- `kiln:build` verifies every internal link, anchor and importmap module, and lists the pages that changed since the previous build. Set `VERBOSE=1` to see request logs. A repository that commits its output can check it in CI: run `kiln:build`, then fail if `git status --porcelain docs` prints anything.
76
-
77
- `kiln:serve` uses Cloudflare Pages and GitHub Pages path resolution and applies `_redirects`. It reads `PORT` (default 4000) and `BIND` (default localhost).
78
-
79
- ## Configuration
80
-
81
- | Option | Default | |
82
- |---|---|---|
83
- | `output` | `"dist"` | Relative to `Rails.root`, or absolute. Wiped at the start of every build. |
84
- | `url` | `nil` | Public base URL, for the sitemap and absolute URLs. |
85
- | `host` | from `url`, else `"localhost"` | Host header sent with every request. |
86
- | `paths` | `:directory` | `/now` becomes `now/index.html`. `:file` writes `now.html`. |
87
- | `assets` | `:referenced` | Assets the output references (HTML, importmap, CSS `url()`). `:all` exports everything. |
88
- | `cname` | `nil` | Writes a `CNAME` file. |
89
- | `not_found` | `nil` | Path rendered to `404.html`. It may respond with 200 or 404. |
90
- | `redirects` | `:file` | `:file` (`_redirects`), `:meta_refresh` (HTML pages for GitHub Pages), `:both`, or `false`. |
91
- | `sitemap` | `true` | Writes `sitemap.xml` when `url` is set. Pages marked `noindex` stay out. |
92
- | `files` | `{}` | Files that aren't routes: `{ "octicons-license.txt" => "vendor/octicons/LICENSE" }`. |
93
- | `strip_source_maps` | `true` | Removes `sourceMappingURL` comments from JS and CSS. |
94
- | `absolute_urls` | `false` | Makes image URLs absolute (img, srcset, og: and twitter: images). |
95
- | `external_links` | `false` | Adds `target="_blank" rel="noopener"` to links to other hosts. |
96
- | `processors` | `[]` | Your HTML processors: `call(html, context)` returning a String. |
97
- | `verify` | `true` | Runs the verifier after every build. |
98
- | `verify_skip` | `[]` | CSS selectors for sample markup whose links aren't checked, such as `"[data-example-preview]"`. |
99
- | `copy_public` | `true` | Copies `public/` (minus `public/assets`) into the output. |
100
-
101
- Hooks receive a context with `output`, `env`, `manifest` and `report`:
102
-
103
- ```ruby
104
- Kiln.configure do |config|
105
- config.before_build { |context| SearchIndex.generate! }
106
- config.after_build { |context| puts "#{context.manifest.entries.size} pages" }
107
- end
108
- ```
109
-
110
- CSRF tokens and meta tags are always stripped. The rest of the HTML stays byte for byte as the app rendered it.
111
-
112
- ## Write views for a build
113
-
114
- - `Kiln.building?` is true while a build renders pages. Use it to hide development-only markup.
115
- - `Kiln.build_cache.fetch(key) { ... }` memoizes for one build and is cleared before and after it.
116
- - Builds fetch assets through the app, so keep `config.public_file_server.enabled = true` for the build environment.
117
- - A build in development skips the precompile but still runs the steps hooked into `assets:precompile`, such as `tailwindcss:build`.
118
- - Development middleware that injects markup (Hotwire Spark, web-console, rack-mini-profiler) fails the build. Load it only under `bin/rails server`.
119
- - Root-absolute asset paths keep every page's `<head>` identical, so Turbo visits never force a full reload.
120
-
121
- ## Write in Markdown
122
-
123
- The content layer is optional and works in server-rendered apps too. It needs commonmarker and Rouge:
124
-
125
- ```ruby
126
- # Gemfile
127
- gem "commonmarker"
128
- gem "rouge"
129
-
130
- # config/application.rb, after Bundler.require
131
- require "kiln/content"
47
+ 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
132
49
  ```
133
50
 
134
- `app/views/pages/about.html.md` renders through the layout like any view, and `.md.erb` runs ERB first. commonmarker renders GitHub Flavored Markdown with tables, strikethrough, autolinks and heading ids; raw HTML passes through. Code blocks get Rouge CSS classes.
135
-
136
- With `Kiln::Content.source_positions` on, each rendered block of a `.md` view or collection entry carries `data-tensaku-md="path:startLine:startCol-endLine:endCol"` for the Tensaku editor. The format is a draft. `.md.erb` views get none, because ERB shifts the line numbers. The setting defaults to on in development when Tensaku is loaded, and is always off while Kiln is building.
137
-
138
- Collections read Markdown files with YAML frontmatter, such as `content/blog/2024-05-01-hello.md`:
139
-
140
- ```ruby
141
- posts = Kiln::Content.collection("blog")
142
- posts.all # visible entries, newest first
143
- posts.find("hello") # raises Kiln::Content::NotFound, which Rails maps to a 404
144
- post.title, post.published_at, post.html, post[:tags]
145
- ```
146
-
147
- Entries with `draft: true` or a future `published_at` are hidden, except in development when Kiln is not building. A server-rendered app can share a hidden entry with `posts.find(slug, preview_token: params[:token])`.
148
-
149
- ## Test the build
150
-
151
- ```ruby
152
- require "kiln/test_helper"
153
-
154
- class StaticSiteTest < ActiveSupport::TestCase
155
- include Kiln::TestHelper
156
-
157
- test("builds the same output twice") { assert_repeatable_build }
158
- test("home page") { assert_page "/", selector: "h1", text: "Welcome" }
159
- end
160
- ```
161
-
162
- `kiln_build { |output| ... }` builds into a temp dir, fails with the report on any error, and yields the output path.
163
-
164
- ## Known limits
165
-
166
- - Pages render one at a time.
167
- - Wildcard rules in your own `public/_redirects` are written out, but the verifier and `kiln:serve` only follow exact rules.
168
- - JS modules are found through the importmap. Relative `import "./x.js"` between files is not followed.
169
- - Collections read `*.md` files. `.md.erb` works for views only.
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.
170
52
 
171
53
  ## Develop Kiln
172
54
 
@@ -176,7 +58,7 @@ bin/test
176
58
  bin/lint # RuboCop and bin/house-rules
177
59
  ```
178
60
 
179
- `test/dummy` is the Rails app the tests build. `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.
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.
180
62
 
181
63
  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.
182
64
 
data/lib/kiln/assets.rb CHANGED
@@ -4,25 +4,37 @@ require "nokogiri"
4
4
  require "set"
5
5
 
6
6
  module Kiln
7
- # Finds the /assets/* files the output uses and fetches them through the app, so the same code works
8
- # with dynamic Propshaft (development, test) and with precompiled assets served from public/assets.
7
+ # Finds the /assets/* files the output uses and exports them. Compiled assets are read from the
8
+ # compile directory; dynamic Propshaft (development, test) serves them through the app.
9
9
  class Assets
10
10
  CSS_REFERENCE = /url\(\s*["']?([^"')]+?)["']?\s*\)|@import\s+["']([^"']+)["']/
11
11
  EXTERNAL = %r{\A(?:[a-z][a-z0-9+.-]*:|//|#)}i
12
12
 
13
13
  class << self
14
- # Compiles assets in-process when the app does not serve them dynamically. Returns a callable that
15
- # removes what the precompile created, or nil when nothing was compiled. When assets are served
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
16
18
  # dynamically, still runs the build steps hooked into assets:precompile (tailwindcss:build,
17
19
  # javascript:build, css:build), so a development build never ships stale bundles.
18
20
  def precompile(app)
19
21
  return build_bundles(app) unless precompile?(app)
20
22
 
21
- output_path = Pathname(app.config.assets.output_path)
22
- created = !output_path.exist?
23
- run_precompile(app)
24
-
25
- -> { created ? FileUtils.rm_rf(output_path) : FileUtils.rm_f(app.config.assets.manifest_path) }
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
26
38
  end
27
39
 
28
40
  def precompile?(app)
@@ -32,6 +44,17 @@ module Kiln
32
44
  !assets.server && !Pathname(assets.manifest_path).exist?
33
45
  end
34
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
+
35
58
  # Copies public/ into the output, minus public/assets. Files already in the output win, with a
36
59
  # warning unless they are listed in `generated` (files Kiln writes on purpose, like 404.html).
37
60
  def copy_public(from:, to:, report:, generated: [])
@@ -93,7 +116,6 @@ module Kiln
93
116
 
94
117
  def export
95
118
  queue = referenced_paths
96
- queue.concat(all_paths) if @config.assets == :all
97
119
  seen = Set.new
98
120
 
99
121
  while (path = queue.shift)
@@ -105,15 +127,18 @@ module Kiln
105
127
  private
106
128
  # Writes one asset and returns the asset paths it references (CSS url() and @import).
107
129
  def fetch(path)
108
- response = @renderer.get(path)
109
- unless response.success?
110
- @report.error(:asset, "responded with #{response.status}", path:)
111
- return []
130
+ body = compiled(path)
131
+ unless body
132
+ response = @renderer.get(path)
133
+ unless response.success?
134
+ @report.error(:asset, "responded with #{response.status}", path:)
135
+ return []
136
+ end
137
+ body = response.body
112
138
  end
113
139
 
114
140
  extension = File.extname(path)
115
- body = response.body
116
- body = Processors::StripSourceMaps.call(body) if @config.strip_source_maps && %w[.js .css].include?(extension)
141
+ body = Processors::StripSourceMaps.call(body) if %w[.js .css].include?(extension)
117
142
  write(path, body)
118
143
  extension == ".css" ? css_references(path, body) : []
119
144
  rescue StandardError => error
@@ -121,6 +146,16 @@ module Kiln
121
146
  []
122
147
  end
123
148
 
149
+ # The file from the compile directory when assets are precompiled, or nil.
150
+ def compiled(path)
151
+ assets = @app.config.assets
152
+ return if assets.server
153
+
154
+ dir = Pathname(assets.manifest_path).dirname.expand_path
155
+ file = dir.join(path.delete_prefix("#{prefix}/")).expand_path
156
+ file.binread if file.to_s.start_with?("#{dir}/") && file.file?
157
+ end
158
+
124
159
  def write(path, body)
125
160
  relative = path.delete_prefix("/")
126
161
  file = @output.join(relative)
@@ -159,10 +194,6 @@ module Kiln
159
194
  end
160
195
  end
161
196
 
162
- def all_paths
163
- @app.assets.load_path.assets.map { "#{prefix}/#{it.digested_path}" }
164
- end
165
-
166
197
  # Normalizes a URL to an asset path ("/assets/app-abc.css"), or nil when it isn't one of ours.
167
198
  def asset_path(url)
168
199
  uri = URI.parse(url.to_s.strip)
data/lib/kiln/build.rb CHANGED
@@ -4,13 +4,11 @@ module Kiln
4
4
  # Runs the whole pipeline and returns a Report. Never raises for page-level problems: those go in
5
5
  # the report so the build can show every failure at once.
6
6
  class Build
7
- # Passed to before_build / after_build hooks.
8
- Context = Data.define(:output, :env, :manifest, :report)
9
-
10
7
  # Development middleware that injects markup into every HTML response.
11
8
  DEV_MIDDLEWARE = %w[Hotwire::Spark::Middleware WebConsole::Middleware Rack::MiniProfiler Rack::LiveReload].freeze
12
- # Source-position attributes from in-page editors (Herb source attribution, Tensaku).
13
- EDITOR_MARKUP = /\sdata-(?:herb|tensaku)-[\w-]+=/
9
+ # Source-position attributes for in-page editors: Herb source attribution, Tensaku, and the content
10
+ # layer's own data-md-source.
11
+ EDITOR_MARKUP = /\sdata-(?:herb-[\w-]+|tensaku-[\w-]+|md-source)=/
14
12
 
15
13
  attr_reader :app, :config, :pages_dsl, :output, :report, :manifest, :previous_manifest
16
14
 
@@ -19,6 +17,9 @@ module Kiln
19
17
  @config = config
20
18
  @pages_dsl = pages
21
19
  @output = Pathname(output || config.output_path(app.root))
20
+ # Pages are written here and replace the output only when the whole build succeeds, so a failed
21
+ # build leaves the previous output as it was.
22
+ @stage = @output.dirname.join(".#{@output.basename}.kiln-build")
22
23
  @report = Report.new
23
24
  @manifest = Manifest.new
24
25
  @redirects = []
@@ -31,14 +32,13 @@ module Kiln
31
32
  end
32
33
 
33
34
  def run
34
- Kiln.building! do
35
+ Kiln.building!(renderer:) do
35
36
  guard_output!
36
37
  guard_dev_middleware!
37
38
  ensure_secret_key_base
38
- guard_static_files!
39
39
  cleanup = Assets.precompile(app)
40
40
  begin
41
- run_hooks(config.before_build_hooks)
41
+ Assets.check_builds!(app)
42
42
  prepare_output
43
43
 
44
44
  pages = Router.new(app.routes, pages_dsl, report:).pages
@@ -46,18 +46,18 @@ module Kiln
46
46
  render_not_found if config.not_found
47
47
  report_editor_markup
48
48
 
49
- Assets.new(renderer:, output:, config:, report:).export
49
+ Assets.new(renderer:, output: @stage, config:, report:, app:).export
50
50
  write_files
51
- Assets.copy_public(from: app.root.join("public"), to: output, report:, generated: generated_files) if config.copy_public
52
- write_redirects if config.redirects && @redirects.any?
53
- Sitemap.new(manifest, url: config.url).write(output) if config.sitemap && config.url
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
54
  write_cname if config.cname
55
- write_manifest
56
55
 
57
- Verifier.new(output, config:).verify(report) if config.verify
58
- run_hooks(config.after_build_hooks)
56
+ Verifier.new(@stage, config:).verify(report)
57
+ publish if report.success?
59
58
  ensure
60
59
  cleanup&.call
60
+ FileUtils.rm_rf(@stage)
61
61
  end
62
62
  end
63
63
  report
@@ -69,16 +69,16 @@ module Kiln
69
69
  end
70
70
 
71
71
  def writer
72
- @writer ||= Writer.new(output, mode: config.paths)
72
+ @writer ||= Writer.new(@stage, mode: config.paths)
73
73
  end
74
74
 
75
75
  def render_page(page)
76
- response = renderer.get(page.path)
76
+ response = Kiln.response_for(page.path)
77
77
 
78
78
  if response.redirect?
79
79
  @redirects << Redirects::Entry.new(from: page.path, to: response.location, status: response.status)
80
80
  elsif response.success?
81
- body = response.html? ? Processors.apply(response.body, Processors::Context.new(path: page.path, config:, response:)) : response.body
81
+ body = response.html? ? Processors::StripCSRF.call(response.body) : response.body
82
82
  @editor_markup << page.path if response.html? && body.match?(EDITOR_MARKUP)
83
83
  file = writer.write(page.path, response.content_type, body)
84
84
  manifest.add(page.path, file:, body:, content_type: response.content_type, noindex: Sitemap.noindex?(response, body))
@@ -94,24 +94,25 @@ module Kiln
94
94
  return if @editor_markup.empty?
95
95
 
96
96
  pages = @editor_markup.first(3).join(", ") + (@editor_markup.size > 3 ? " and #{@editor_markup.size - 3} more" : "")
97
- report.error(:editor_markup, "data-herb-* or data-tensaku-* attributes reached #{pages}. " \
98
- "Turn off Herb source attribution and Tensaku outside development, or build in production.")
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.")
99
100
  end
100
101
 
101
102
  def render_not_found
102
- response = renderer.get(config.not_found)
103
+ response = Kiln.response_for(config.not_found)
103
104
  unless [ 200, 404 ].include?(response.status)
104
105
  return report.error(:render, "404 page responded with #{response.status}", path: config.not_found)
105
106
  end
106
107
 
107
- body = Processors.apply(response.body, Processors::Context.new(path: config.not_found, config:, response:))
108
+ body = Processors::StripCSRF.call(response.body)
108
109
  report.wrote(writer.write_file("404.html", body))
109
110
  rescue StandardError => error
110
111
  report.error(:render, describe(error), path: config.not_found)
111
112
  end
112
113
 
113
114
  def write_redirects
114
- Redirects.new(@redirects, mode: config.redirects, writer:, host: config.host, url: config.url).write(output).each { report.wrote(it) }
115
+ report.wrote(Redirects.new(@redirects, host: config.host).write(@stage))
115
116
  end
116
117
 
117
118
  # The manifest is build state, not part of the site: it lives in tmp/, and only for the configured
@@ -143,24 +144,25 @@ module Kiln
143
144
  [ ("404.html" if config.not_found), ("CNAME" if config.cname), *config.files.keys.map(&:to_s) ].compact
144
145
  end
145
146
 
147
+ # config.cname = true takes the host from config.url.
146
148
  def write_cname
147
- report.wrote(writer.write_file("CNAME", "#{config.cname}\n"))
148
- end
149
+ host = config.cname == true ? config.url && URI(config.url).host : config.cname
150
+ return report.error(:write, "config.cname = true needs config.url", path: "/CNAME") unless host
149
151
 
150
- def run_hooks(hooks)
151
- context = Context.new(output:, env: Rails.env, manifest:, report:)
152
- hooks.each do |hook|
153
- hook.call(context)
154
- rescue StandardError => error
155
- report.error(:hook, describe(error))
156
- end
152
+ report.wrote(writer.write_file("CNAME", "#{host}\n"))
157
153
  end
158
154
 
159
155
  def prepare_output
160
156
  previous = manifest_dir&.join(Manifest::FILENAME)
161
157
  @previous_manifest = Manifest.load(previous) if previous&.file?
158
+ FileUtils.rm_rf(@stage)
159
+ FileUtils.mkdir_p(@stage)
160
+ end
161
+
162
+ def publish
162
163
  FileUtils.rm_rf(output)
163
- FileUtils.mkdir_p(output)
164
+ File.rename(@stage, output)
165
+ write_manifest
164
166
  end
165
167
 
166
168
  # Refuse to wipe anything that contains the app.
@@ -188,15 +190,6 @@ module Kiln
188
190
  app.config.secret_key_base = SecureRandom.hex(64)
189
191
  end
190
192
 
191
- # After a precompile, assets are fetched from public/assets through ActionDispatch::Static.
192
- def guard_static_files!
193
- return unless app.config.respond_to?(:assets) && !app.config.assets.server
194
- return if app.config.public_file_server.enabled
195
-
196
- raise Kiln::Error, "Kiln fetches compiled assets through the public file server. " \
197
- "Set config.public_file_server.enabled = true for the build environment."
198
- end
199
-
200
193
  def describe(error)
201
194
  where = error.backtrace&.find { it.start_with?(app.root.to_s) }&.delete_prefix("#{app.root}/")
202
195
  [ "#{error.class}: #{error.message}", where && "(#{where})" ].compact.join(" ")
@@ -1,6 +1,7 @@
1
1
  module Kiln
2
2
  # A plain in-memory store that returns the cached objects themselves (no copies), so memoized
3
- # repositories and collections keep their state for the whole build.
3
+ # repositories and collections keep their state for the whole build. Outside a build, fetch runs
4
+ # the block every time, so a development server never serves stale data.
4
5
  class BuildCache
5
6
  def initialize
6
7
  @store = {}
@@ -8,6 +9,8 @@ module Kiln
8
9
  end
9
10
 
10
11
  def fetch(key)
12
+ return yield unless Kiln.building?
13
+
11
14
  @mutex.synchronize do
12
15
  return @store[key] if @store.key?(key)
13
16
 
@@ -15,9 +18,6 @@ module Kiln
15
18
  end
16
19
  end
17
20
 
18
- def read(key) = @mutex.synchronize { @store[key] }
19
- def write(key, value) = @mutex.synchronize { @store[key] = value }
20
- def delete(key) = @mutex.synchronize { @store.delete(key) }
21
21
  def clear = @mutex.synchronize { @store.clear }
22
22
  end
23
23
  end