kiln 0.1.2 → 0.1.4

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: 2108cdc748f14c10c06ab2edbf346622c13887cac5ec16bc2fe6823dfb3d4b53
4
- data.tar.gz: f5aabfc64b54bd944d8d2bb3de6a57d980204e4f4070dd23f3340376980b8326
3
+ metadata.gz: c77d38afe49d8d5149ee6491636fb192aa74679bb7599bdfab23785cb8aa7add
4
+ data.tar.gz: 87f254094d83833b82afc4ccf67d9d6eacbe964a663e89c35d15612525923cce
5
5
  SHA512:
6
- metadata.gz: 6ec17dee2f07143628dbd3892c50ee258bde2aa1a2e0c4e5306b7ecd9d30856e2d0df0d50b78da273f658b7d0607e3ec4a4bd00fc5f8834c4aa7002e7938d814
7
- data.tar.gz: 9eafdc861711a6f733e9bc376a6c4f0c3519c104451fbaed5140c37642ea0d21edd6649793309ec64fb02e26b8b60ec8892398b5e0bc20f7e2c21a725940a943
6
+ metadata.gz: 4439279aef4385538b9a80b73bc813221d44b4b9bc0261cc36a9d14b960142073f8de11e0401c659481ba6ff20f8eb1ebaf66fc91805b968b60feebc28d0659c
7
+ data.tar.gz: a61d697784e845141f7f88f0660ac70f93c15d36bdd860bf95705777f44a55c5a2a547bdf96043379daee586f04b395d56b52e09a3a5d60e711389d992d20f9f
data/CHANGELOG.md CHANGED
@@ -1,5 +1,52 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.4 (2026-11-13)
4
+
5
+ Breaking:
6
+
7
+ - A production build always compiles assets into a temporary directory. An existing
8
+ `public/assets/.manifest.json` no longer skips the compile, so a stale `public/assets` can't ship
9
+ old assets.
10
+
11
+ ## 0.1.3 (2026-11-08)
12
+
13
+ Breaking:
14
+
15
+ - With `paths: :directory`, route helpers add a trailing slash (`about_path` is `/about/`), the URL a
16
+ static host serves `about/index.html` at. Kiln sets `trailing_slash: true` in the app's
17
+ `default_url_options` unless the app sets it. Paths with a dot keep no slash.
18
+ - The sitemap lists a page written as `now/index.html` at `/now/` instead of `/now`. Pages written
19
+ as `now.html` keep `/now`.
20
+ - Source positions use `data-md-source` instead of `data-tensaku-md`, and
21
+ `Kiln::Content.source_positions` is off until the app turns it on. Kiln no longer checks whether
22
+ Tensaku is loaded: set `Kiln::Content.source_positions = Rails.env.development?`.
23
+ - `paginate` is removed. A value list does the same:
24
+ `params :blog_page, page: -> { 2..Post.count.fdiv(10).ceil }`.
25
+ - Highlighted code blocks carry the fence's language as `data-language`, also when Rouge has no
26
+ lexer for it. Code that matches `<pre class="highlight ..."><code>` with a regex should select
27
+ `pre.highlight` instead.
28
+
29
+ - A build writes into `.OUTPUT.kiln-build` next to the output directory and replaces the output
30
+ only when it succeeds. A failed build leaves the previous output, and `tmp/kiln-manifest.json`,
31
+ as they were, instead of a half-written directory.
32
+
33
+ Added:
34
+
35
+ - `Kiln.render(path)` returns another page's body as the build writes it, for pages made from other
36
+ pages such as a search index. During a build each page is rendered once, shared between the build
37
+ and every `Kiln.render` call.
38
+ - `params :post, -> { ... }, locale: [ nil, "es" ]` combines a source with value lists.
39
+ - `Kiln::Content.file(path)` reads one Markdown file outside the content directory, such as a
40
+ README or CONTRIBUTING.md, as an entry with frontmatter, `html` and source positions. It is read
41
+ again when the file changes, and once per build. A name that does not end in `.md` raises
42
+ `ArgumentError`.
43
+ - The last line of `kiln:build` names the Rails environment the build ran in.
44
+
45
+ Fixed:
46
+
47
+ - `kiln:build` boots an app without its own secret with `SECRET_KEY_BASE_DUMMY`, so gems that read
48
+ `secret_key_base` while booting (turbo-rails) no longer fail the build.
49
+
3
50
  ## 0.1.2 (2026-11-07)
4
51
 
5
52
  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,17 +12,18 @@
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="#configuration">Configuration</a> ·
19
+ <a href="https://kiln.davafons.com">Documentation</a> ·
20
+ <a href="https://kiln.davafons.com/installation/">Installation</a> ·
16
21
  <a href="CHANGELOG.md">Changelog</a>
17
22
  </p>
18
23
 
19
- 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`.
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`.
20
25
 
21
- 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.
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.
22
27
 
23
28
  ## Build a site
24
29
 
@@ -27,6 +32,8 @@ Routes are the page list. A route that needs params and has no param source fail
27
32
  gem "kiln"
28
33
  ```
29
34
 
35
+ Routes without params need no declaration. Routes with params need a param source or a skip:
36
+
30
37
  ```ruby
31
38
  # config/kiln.rb
32
39
  Kiln.configure do |config|
@@ -41,112 +48,13 @@ end
41
48
  ```
42
49
 
43
50
  ```sh
44
- RAILS_ENV=production bin/rails kiln:build
51
+ RAILS_ENV=production bin/rails kiln:build # write the site to dist/
52
+ bin/rails kiln:serve # serve dist/ at http://localhost:4000
45
53
  ```
46
54
 
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.
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.
48
56
 
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, locale: [ nil, "es", "ja" ] # scope "(:locale)"
57
- params :archive, year: -> { Post.years }, locale: [ nil, "es" ] # every combination
58
- paginate :blog_page, per: 10, total: -> { Post.count }, start: 2 # /blog/page/2, /blog/page/3, ...
59
- skip :search, reason: "dynamic"
60
- end
61
- ```
62
-
63
- A hash of value lists builds every combination of the values. A `nil` value leaves the key out, which fills an optional segment such as `(:locale)` with nothing. A list may be a lambda, called at build time.
64
-
65
- 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.
66
-
67
- 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`.
68
-
69
- ## Develop and ship
70
-
71
- 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:
72
-
73
- ```sh
74
- RAILS_ENV=production bin/rails kiln:build # write the site; CI and deploys run this
75
- bin/rails kiln:serve # look at the output as a static host serves it
76
- ```
77
-
78
- `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.
79
-
80
- `kiln:serve` uses Cloudflare Pages and GitHub Pages path resolution and applies `_redirects`. It reads `PORT` (default 4000) and `BIND` (default localhost).
81
-
82
- ## Configuration
83
-
84
- | Option | Default | |
85
- |---|---|---|
86
- | `output` | `"dist"` | Relative to `Rails.root`, or absolute. Wiped at the start of every build. |
87
- | `url` | `nil` | Public base URL. Its host is sent with every request (`localhost` without it), and `sitemap.xml` is written only when it is set. |
88
- | `paths` | `:directory` | `/now` becomes `now/index.html`. `:file` writes `now.html`. |
89
- | `cname` | `nil` | Writes a `CNAME` file with this host. `true` takes the host from `url`. |
90
- | `not_found` | `nil` | Path rendered to `404.html`. It may respond with 200 or 404. |
91
- | `files` | `{}` | Files that aren't routes: `{ "octicons-license.txt" => "vendor/octicons/LICENSE" }`. |
92
- | `verify_skip` | `[]` | CSS selectors for sample markup whose links aren't checked, such as `"[data-example-preview]"`. |
93
-
94
- Every build exports the assets the output references (HTML, importmap, CSS `url()`), removes `sourceMappingURL` comments from JS and CSS, copies `public/` (minus `public/assets`), writes `_redirects` when a route redirects, and runs the verifier. The sitemap leaves out pages marked `noindex`.
95
-
96
- CSRF tokens and meta tags are always stripped. The rest of the HTML stays byte for byte as the app rendered it.
97
-
98
- ## Write views for a build
99
-
100
- - `Kiln.building?` is true while a build renders pages. Use it to hide development-only markup.
101
- - `Kiln.build_cache.fetch(key) { ... }` memoizes for one build and is cleared before and after it. Outside a build it runs the block every time, so a development server never serves stale data.
102
- - A production build precompiles assets into a temporary directory and exports them from there. `public/assets` is left alone, so a development server of the same app can run at the same time.
103
- - Propshaft only serves asset folders that exist when the app boots. Track `app/assets/builds/.keep`, as a new Rails app does, or the build stops with an error on a fresh checkout.
104
- - A build in development skips the precompile but still runs the steps hooked into `assets:precompile`, such as `tailwindcss:build`.
105
- - Development middleware that injects markup (Hotwire Spark, web-console, rack-mini-profiler) fails the build. Load it only under `bin/rails server`.
106
- - Root-absolute asset paths keep every page's `<head>` identical, so Turbo visits never force a full reload.
107
-
108
- ## Write in Markdown
109
-
110
- The content layer is optional and works in server-rendered apps too. It needs commonmarker and Rouge:
111
-
112
- ```ruby
113
- # Gemfile
114
- gem "commonmarker"
115
- gem "rouge"
116
-
117
- # config/application.rb, after Bundler.require
118
- require "kiln/content"
119
- ```
120
-
121
- `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.
122
-
123
- `Kiln::Content::Markdown.render(text)` returns HTML. `Kiln::Content::Markdown.render_inline(text)` drops the `<p>` around text that is a single paragraph, for titles and captions; other text renders as with `render`.
124
-
125
- 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.
126
-
127
- Collections read Markdown files with YAML frontmatter, such as `content/blog/2024-05-01-hello.md`:
128
-
129
- ```ruby
130
- posts = Kiln::Content.collection("blog")
131
- posts.all # visible entries, newest first
132
- posts.find("hello") # raises Kiln::Content::NotFound, which Rails maps to a 404
133
- post.title, post.published_at, post.html, post[:tags]
134
- ```
135
-
136
- A filename date may be `YYYY-MM-DD` or `YYYY-MM`. A month-only date sets `published_at` to the 1st of that month, and a filename that is only a date, such as `2026-08.md`, keeps the date as its slug.
137
-
138
- `SLUG.LOCALE.md` is a translation of the entry with that slug, such as `2026-08.es.md` for `2026-08.md`. A locale is two lowercase letters, optionally followed by a dash and two uppercase letters (`es`, `pt-BR`). Translations stay out of `all`, `find` and `each`:
139
-
140
- ```ruby
141
- post.locale # nil for SLUG.md, "es" for SLUG.es.md
142
- post.translation(:es) # the visible SLUG.es.md entry, or nil
143
- ```
144
-
145
- A translation whose entry does not exist fails when the collection loads.
146
-
147
- Entries with `draft: true` or a future `published_at` are hidden, except in development when Kiln is not building.
148
-
149
- ## Test the build
57
+ ## Test it
150
58
 
151
59
  ```ruby
152
60
  require "kiln/test_helper"
@@ -154,23 +62,19 @@ require "kiln/test_helper"
154
62
  class StaticSiteTest < ActiveSupport::TestCase
155
63
  include Kiln::TestHelper
156
64
 
157
- test "the site builds repeatably" do
158
- kiln_build(repeatable: true) { |output| assert output.join("index.html").file? }
159
- end
160
-
161
- test("home page") { assert_page "/", selector: "h1", text: "Welcome" }
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" }
162
67
  end
163
68
  ```
164
69
 
165
- `kiln_build { |output| ... }` builds into a temp dir, fails with the report on any error, and yields the output path. With `repeatable: true` it builds twice, fails with the list of differing files when the outputs differ, and yields the first output.
70
+ ## Documentation
166
71
 
167
- ## Known limits
72
+ Start with the [introduction](https://kiln.davafons.com).
168
73
 
169
- - Pages render one at a time.
170
- - Redirects are written only as `_redirects`, which Cloudflare Pages and Netlify read. GitHub Pages ignores the file, so redirect routes do not redirect there.
171
- - Wildcard rules in your own `public/_redirects` are written out, but the verifier and `kiln:serve` only follow exact rules.
172
- - JS modules are found through the importmap. Relative `import "./x.js"` between files is not followed.
173
- - Collections read `*.md` files. `.md.erb` works for views only.
74
+ - [Install Kiln](https://kiln.davafons.com/installation/) and declare [pages](https://kiln.davafons.com/pages/).
75
+ - Read about [views and assets](https://kiln.davafons.com/views/) during a build, and the [Markdown](https://kiln.davafons.com/content/) layer.
76
+ - [Test](https://kiln.davafons.com/testing/) and [deploy](https://kiln.davafons.com/deploying/) the site.
77
+ - Look up [configuration](https://kiln.davafons.com/configuration/), the [build](https://kiln.davafons.com/build/) and the [known limits](https://kiln.davafons.com/limits/).
174
78
 
175
79
  ## Develop Kiln
176
80
 
@@ -180,7 +84,7 @@ bin/test
180
84
  bin/lint # RuboCop and bin/house-rules
181
85
  ```
182
86
 
183
- `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.
87
+ `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.
184
88
 
185
89
  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.
186
90
 
data/lib/kiln/assets.rb CHANGED
@@ -37,11 +37,13 @@ module Kiln
37
37
  cleanup
38
38
  end
39
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.
40
42
  def precompile?(app)
41
43
  assets = app.config.respond_to?(:assets) && app.config.assets
42
44
  return false unless assets.respond_to?(:server) && assets.manifest_path
43
45
 
44
- !assets.server && !Pathname(assets.manifest_path).exist?
46
+ !assets.server
45
47
  end
46
48
 
47
49
  # Propshaft only adds load paths that exist at boot. On a fresh checkout, a bundler such as
data/lib/kiln/build.rb CHANGED
@@ -6,8 +6,9 @@ module Kiln
6
6
  class Build
7
7
  # Development middleware that injects markup into every HTML response.
8
8
  DEV_MIDDLEWARE = %w[Hotwire::Spark::Middleware WebConsole::Middleware Rack::MiniProfiler Rack::LiveReload].freeze
9
- # Source-position attributes from in-page editors (Herb source attribution, Tensaku).
10
- 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)=/
11
12
 
12
13
  attr_reader :app, :config, :pages_dsl, :output, :report, :manifest, :previous_manifest
13
14
 
@@ -16,6 +17,9 @@ module Kiln
16
17
  @config = config
17
18
  @pages_dsl = pages
18
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")
19
23
  @report = Report.new
20
24
  @manifest = Manifest.new
21
25
  @redirects = []
@@ -28,7 +32,7 @@ module Kiln
28
32
  end
29
33
 
30
34
  def run
31
- Kiln.building! do
35
+ Kiln.building!(renderer:) do
32
36
  guard_output!
33
37
  guard_dev_middleware!
34
38
  ensure_secret_key_base
@@ -42,17 +46,18 @@ module Kiln
42
46
  render_not_found if config.not_found
43
47
  report_editor_markup
44
48
 
45
- Assets.new(renderer:, output:, config:, report:, app:).export
49
+ Assets.new(renderer:, output: @stage, config:, report:, app:).export
46
50
  write_files
47
- Assets.copy_public(from: app.root.join("public"), to: output, report:, generated: generated_files)
51
+ Assets.copy_public(from: app.root.join("public"), to: @stage, report:, generated: generated_files)
48
52
  write_redirects if @redirects.any?
49
- Sitemap.new(manifest, url: config.url).write(output) if config.url
53
+ Sitemap.new(manifest, url: config.url).write(@stage) if config.url
50
54
  write_cname if config.cname
51
- write_manifest
52
55
 
53
- Verifier.new(output, config:).verify(report)
56
+ Verifier.new(@stage, config:).verify(report)
57
+ publish if report.success?
54
58
  ensure
55
59
  cleanup&.call
60
+ FileUtils.rm_rf(@stage)
56
61
  end
57
62
  end
58
63
  report
@@ -64,11 +69,11 @@ module Kiln
64
69
  end
65
70
 
66
71
  def writer
67
- @writer ||= Writer.new(output, mode: config.paths)
72
+ @writer ||= Writer.new(@stage, mode: config.paths)
68
73
  end
69
74
 
70
75
  def render_page(page)
71
- response = renderer.get(page.path)
76
+ response = Kiln.response_for(page.path)
72
77
 
73
78
  if response.redirect?
74
79
  @redirects << Redirects::Entry.new(from: page.path, to: response.location, status: response.status)
@@ -89,12 +94,13 @@ module Kiln
89
94
  return if @editor_markup.empty?
90
95
 
91
96
  pages = @editor_markup.first(3).join(", ") + (@editor_markup.size > 3 ? " and #{@editor_markup.size - 3} more" : "")
92
- report.error(:editor_markup, "data-herb-* or data-tensaku-* attributes reached #{pages}. " \
93
- "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.")
94
100
  end
95
101
 
96
102
  def render_not_found
97
- response = renderer.get(config.not_found)
103
+ response = Kiln.response_for(config.not_found)
98
104
  unless [ 200, 404 ].include?(response.status)
99
105
  return report.error(:render, "404 page responded with #{response.status}", path: config.not_found)
100
106
  end
@@ -106,7 +112,7 @@ module Kiln
106
112
  end
107
113
 
108
114
  def write_redirects
109
- report.wrote(Redirects.new(@redirects, host: config.host).write(output))
115
+ report.wrote(Redirects.new(@redirects, host: config.host).write(@stage))
110
116
  end
111
117
 
112
118
  # The manifest is build state, not part of the site: it lives in tmp/, and only for the configured
@@ -149,8 +155,14 @@ module Kiln
149
155
  def prepare_output
150
156
  previous = manifest_dir&.join(Manifest::FILENAME)
151
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
152
163
  FileUtils.rm_rf(output)
153
- FileUtils.mkdir_p(output)
164
+ File.rename(@stage, output)
165
+ write_manifest
154
166
  end
155
167
 
156
168
  # Refuse to wipe anything that contains the app.
@@ -11,8 +11,8 @@ module Kiln
11
11
  attr_reader :collection, :path, :slug, :locale, :attributes, :body, :published_at
12
12
 
13
13
  def initialize(collection, path)
14
- @collection, @path = collection.to_s, Pathname(path)
15
- match = FILENAME.match(@path.basename.to_s)
14
+ @collection, @path = collection&.to_s, Pathname(path)
15
+ match = FILENAME.match(@path.basename.to_s) or raise ArgumentError, "#{@path} is not a Markdown file: its name must end in .md"
16
16
  @locale = match[:locale]
17
17
  dated = DATED.match(match[:name])
18
18
  @slug = (dated && dated[:slug]) || match[:name]
@@ -31,19 +31,23 @@ module Kiln
31
31
  end
32
32
 
33
33
  # Swaps a code block for raw HTML highlighted by Rouge, with CSS classes and no inline styles.
34
+ # data-language keeps the fence's language as written, also when Rouge has no lexer for it.
34
35
  def self.highlight(node, sourcepos:)
35
36
  code = node.string_content
36
- lexer = Rouge::Lexer.find_fancy(node.fence_info.split.first.to_s, code) || Rouge::Lexers::PlainText.new
37
- position = node.source_position.values_at(:start_line, :start_column, :end_line, :end_column)
38
- attribute = %( data-sourcepos="%d:%d-%d:%d") % position if sourcepos
39
- html = %(<pre class="highlight #{lexer.tag}"#{attribute}><code>#{Rouge::Formatters::HTML.new.format(lexer.lex(code))}</code></pre>\n)
37
+ language = node.fence_info.split.first.to_s
38
+ lexer = Rouge::Lexer.find_fancy(language, code) || Rouge::Lexers::PlainText.new
39
+ attributes = +""
40
+ attributes << %( data-language="#{ERB::Util.html_escape(language)}") unless language.empty?
41
+ attributes << %( data-sourcepos="%d:%d-%d:%d") % node.source_position.values_at(:start_line, :start_column, :end_line, :end_column) if sourcepos
42
+ html = %(<pre class="highlight #{lexer.tag}"#{attributes}><code>#{Rouge::Formatters::HTML.new.format(lexer.lex(code))}</code></pre>\n)
40
43
  node.replace(Commonmarker::Node.new(:html_block, literal: html))
41
44
  end
42
45
  end
43
46
 
44
- # Editor markup for Tensaku: data-tensaku-md="path:startLine:startCol-endLine:endCol", with the
45
- # path relative to Rails.root. Only block elements carry it; commonmarker's positions on inline
46
- # elements are dropped. The format is a draft, and this is the one place that writes it.
47
+ # Editor markup: data-md-source="path:startLine:startCol-endLine:endCol", with the path relative
48
+ # to Rails.root, 1-based lines and commonmarker byte columns with an inclusive end. Only the
49
+ # elements in BLOCKS carry it; commonmarker's positions on inline elements are dropped. This is
50
+ # the one place that writes it.
47
51
  module SourcePosition
48
52
  BLOCKS = %w[p h1 h2 h3 h4 h5 h6 ul ol li blockquote pre table hr].to_set.freeze
49
53
  ATTRIBUTE = /<(\w+)([^>]*?) data-sourcepos="(\d+):(\d+)-(\d+):(\d+)"/
@@ -54,7 +58,7 @@ module Kiln
54
58
  tag, rest = $1, $2
55
59
  next "<#{tag}#{rest}" unless BLOCKS.include?(tag)
56
60
 
57
- %(<#{tag}#{rest} data-tensaku-md="#{relative}:#{$3.to_i + line_offset}:#{$4}-#{$5.to_i + line_offset}:#{$6}")
61
+ %(<#{tag}#{rest} data-md-source="#{relative}:#{$3.to_i + line_offset}:#{$4}-#{$5.to_i + line_offset}:#{$6}")
58
62
  end
59
63
  end
60
64
  end
data/lib/kiln/content.rb CHANGED
@@ -1,51 +1,8 @@
1
- # Kiln content layer: Markdown views and Markdown collections with YAML frontmatter.
2
- # Optional and independent of the exporter, so server-rendered Rails apps can use it too.
3
- #
4
- # # Gemfile
5
- # gem "commonmarker"
6
- # gem "rouge"
7
- #
8
- # # config/initializers/kiln.rb
9
- # require "kiln/content"
10
- #
11
- # Markdown views. app/views/pages/about.html.md renders through the layout like any view.
12
- # about.html.md.erb runs ERB first, then Markdown. commonmarker renders GitHub Flavored Markdown
13
- # (tables, strikethrough, autolinks, heading ids). Code blocks are highlighted by Rouge with CSS
14
- # classes, so add a Rouge theme to your stylesheet (`rougify style github`).
15
- #
16
- # Collections. content/blog/2024-05-01-hello.md:
17
- #
18
- # ---
19
- # title: Hello
20
- # tags: [rails]
21
- # ---
22
- # # Hello
23
- #
24
- # posts = Kiln::Content.collection("blog")
25
- # posts.all # visible entries, newest first
26
- # posts.find("hello") # raises Kiln::Content::NotFound (a 404 in Rails)
27
- # posts.find_by(slug: "hello") # or nil
28
- # post.slug, post.title, post.published_at, post.draft?, post.body, post.html, post[:tags], post.tags
29
- #
30
- # # config/kiln.rb
31
- # params :post, -> { Kiln::Content.collection("blog").map { { slug: it.slug } } }
32
- #
33
- # Filenames. A leading YYYY-MM-DD or YYYY-MM date sets published_at (a month means its 1st day); a
34
- # name that is only a date keeps it as the slug. SLUG.LOCALE.md is a translation of the SLUG entry,
35
- # where LOCALE is two lowercase letters with an optional -XX region (es, pt-BR). Translations stay out
36
- # of all/find/each: post.translation(:es) returns one or nil, and post.locale is nil or "es".
37
- #
38
- # Publishing. Entries with `draft: true` or a future `published_at` (frontmatter or filename date)
39
- # are hidden. They show in development unless Kiln is building; set Kiln::Content.show_drafts to
40
- # override.
41
- #
42
- # Source positions. With Kiln::Content.source_positions on, each rendered block of a .md view or
43
- # collection entry carries data-tensaku-md="path:startLine:startCol-endLine:endCol" for the Tensaku
44
- # editor. .md.erb views get none. It defaults to on in development when Tensaku is loaded, and is
45
- # always off while Kiln is building.
46
- #
47
- # Settings: Kiln::Content.root (default Rails.root/content), Kiln::Content.show_drafts,
48
- # Kiln::Content.source_positions.
1
+ # Kiln content layer: Markdown views (.html.md, .html.md.erb), collections of Markdown files with
2
+ # YAML frontmatter, and single Markdown files. Optional and independent of the exporter, so
3
+ # server-rendered Rails apps can use it too. Load it with `require "kiln/content"` after adding the
4
+ # commonmarker and rouge gems. The content page of the docs (docs/app/views/pages/content.html.md)
5
+ # describes every feature; comments here cover only what the code does not show.
49
6
  begin
50
7
  require "commonmarker"
51
8
  require "rouge"
@@ -80,8 +37,7 @@ module Kiln
80
37
 
81
38
  def source_positions
82
39
  return false if Kiln.building?
83
- return @source_positions unless @source_positions.nil?
84
- Rails.env.development? && !defined?(::Tensaku).nil?
40
+ @source_positions == true
85
41
  end
86
42
 
87
43
  def collection(name)
@@ -94,15 +50,33 @@ module Kiln
94
50
  end
95
51
  end
96
52
 
53
+ # One Markdown file anywhere, such as a README or CONTRIBUTING.md, as an entry with
54
+ # frontmatter, html and source positions. Read again when the file changes, once per build.
55
+ def file(path)
56
+ path = Pathname(path).expand_path
57
+ if Kiln.building?
58
+ Kiln.build_cache.fetch("kiln/content/file/#{path}") { Entry.new(nil, path) }
59
+ else
60
+ mtime = path.mtime
61
+ cached = files[path]
62
+ cached && cached[0] == mtime ? cached[1] : (files[path] = [ mtime, Entry.new(nil, path) ])[1]
63
+ end
64
+ end
65
+
97
66
  def reset!
98
67
  @root = @show_drafts = @source_positions = nil
99
68
  @collections = {}
69
+ @files = {}
100
70
  end
101
71
 
102
72
  private
103
73
  def collections
104
74
  @collections ||= {}
105
75
  end
76
+
77
+ def files
78
+ @files ||= {}
79
+ end
106
80
  end
107
81
  end
108
82
  end
data/lib/kiln/pages.rb CHANGED
@@ -10,34 +10,26 @@ module Kiln
10
10
 
11
11
  # params :post, -> { Post.all.map { { slug: it.slug } } }
12
12
  # params :health, locale: [ nil, "es", "ja" ]
13
+ # params :archive, -> { Archive.all.map { { year: it.year } } }, locale: [ nil, "es" ]
13
14
  #
14
15
  # Value lists build every combination of their values. A nil value leaves the key out, for
15
- # optional segments such as "(:locale)". A list may be a lambda, called at build time.
16
+ # optional segments such as "(:locale)". A list may be a lambda, called at build time. With both a
17
+ # source and value lists, every hash from the source is combined with every combination.
16
18
  def params(route_name, source = nil, **values)
17
- if values.any?
18
- raise ArgumentError, "params :#{route_name} takes a source or value lists, not both" if source
19
- source = -> { combinations(values) }
20
- end
21
- raise ArgumentError, "params :#{route_name} needs a callable source" unless source.respond_to?(:call)
22
- @sources[route_name.to_sym] = source
19
+ raise ArgumentError, "params :#{route_name} needs a callable source" unless source.nil? || source.respond_to?(:call)
20
+ raise ArgumentError, "params :#{route_name} needs a source or value lists" if source.nil? && values.empty?
21
+
22
+ @sources[route_name.to_sym] =
23
+ if values.empty? then source
24
+ elsif source.nil? then -> { combinations(values) }
25
+ else -> { source.call.to_a.product(combinations(values)).map { |params, extra| params.merge(extra) } }
26
+ end
23
27
  end
24
28
 
25
29
  def skip(route_name, reason: nil)
26
30
  @skips[route_name.to_sym] = reason
27
31
  end
28
32
 
29
- # paginate :posts_page, per: 10, total: -> { Post.count }
30
- # Builds pages start..last, where last is ceil(total / per). The start page is always built, so an
31
- # empty list still gets its first page. Use start: 2 when page 1 lives at another route.
32
- def paginate(route_name, per:, total:, param: :page, start: 1)
33
- raise ArgumentError, "paginate :#{route_name} needs a positive per:" unless per.is_a?(Integer) && per.positive?
34
-
35
- params route_name, -> do
36
- last = Integer(total.call).fdiv(per).ceil
37
- (start..[ start, last ].max).map { { param => it } }
38
- end
39
- end
40
-
41
33
  def declared_names = (sources.keys + skips.keys).uniq
42
34
 
43
35
  private
data/lib/kiln/railtie.rb CHANGED
@@ -15,6 +15,15 @@ module Kiln
15
15
  hosts << Kiln.config.host if hosts.any? && !hosts.include?(Kiln.config.host)
16
16
  end
17
17
 
18
+ # In :directory mode "/now" is written as now/index.html, which static hosts serve at "/now/" and
19
+ # reach from "/now" with a redirect. Route helpers add the trailing slash so links point at the
20
+ # served URL. Paths with a dot (feed.xml) are left alone, and an app that sets trailing_slash in
21
+ # default_url_options keeps its own value.
22
+ config.after_initialize do |app|
23
+ options = app.routes.default_url_options
24
+ options[:trailing_slash] = true if Kiln.config.paths == :directory && !options.key?(:trailing_slash)
25
+ end
26
+
18
27
  rake_tasks do
19
28
  Dir[File.expand_path("../tasks/kiln/*.rake", __dir__)].sort.each { load it }
20
29
  end
data/lib/kiln/sitemap.rb CHANGED
@@ -24,7 +24,7 @@ module Kiln
24
24
  urls = @manifest.entries.filter_map do |path, entry|
25
25
  next if entry[:noindex] || entry[:content_type] != "text/html"
26
26
 
27
- " <url><loc>#{ERB::Util.html_escape(@url + path)}</loc></url>\n"
27
+ " <url><loc>#{ERB::Util.html_escape(@url + served_path(path, entry[:file]))}</loc></url>\n"
28
28
  end
29
29
 
30
30
  File.write(Pathname(output).join(FILENAME), <<~XML)
@@ -34,5 +34,10 @@ module Kiln
34
34
  XML
35
35
  FILENAME
36
36
  end
37
+
38
+ private
39
+ def served_path(path, file)
40
+ File.basename(file.to_s) == "index.html" ? "/#{file.to_s.delete_suffix("index.html")}" : path
41
+ end
37
42
  end
38
43
  end
data/lib/kiln/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Kiln
2
- VERSION = "0.1.2"
2
+ VERSION = "0.1.4"
3
3
  end
data/lib/kiln.rb CHANGED
@@ -35,16 +35,50 @@ module Kiln
35
35
  @building == true
36
36
  end
37
37
 
38
- def building!
39
- previous = @building
38
+ def building!(renderer: nil)
39
+ previous = [ @building, @renderer ]
40
40
  @building = true
41
+ @renderer = renderer
41
42
  build_cache.clear
42
43
  yield
43
44
  ensure
44
- @building = previous
45
+ @building, @renderer = previous
45
46
  build_cache.clear
46
47
  end
47
48
 
49
+ # Another page's body as a build writes it (CSRF tokens stripped), for pages built from other
50
+ # pages, such as a search index. Raises Kiln::Error unless the page responds with 2xx.
51
+ #
52
+ # pages = Docs::PAGES.map { { url: page_path(it), html: Kiln.render(page_path(it)) } }
53
+ #
54
+ # During a build the response is shared: the build writes the same response, so every page is
55
+ # rendered once whichever asks for it first. Outside a build it renders on every call.
56
+ def render(path)
57
+ response = response_for(path)
58
+ raise Error, "Kiln.render(#{path.inspect}) got a #{response.status} response" unless response.success?
59
+
60
+ response.html? ? Processors::StripCSRF.call(response.body) : response.body
61
+ end
62
+
63
+ # The app's response for a path, cached for the build so the build and Kiln.render share it.
64
+ # "/now" and "/now/" are the same page. A page that renders itself, directly or through other
65
+ # pages, raises Kiln::Error.
66
+ def response_for(path)
67
+ path = path.to_s
68
+ path = path.chomp("/") unless path == "/"
69
+ build_cache.fetch([ :kiln_response, path ]) do
70
+ rendering = Thread.current[:kiln_rendering] ||= []
71
+ raise Error, "Kiln.render loops: #{[ *rendering, path ].join(" -> ")}" if rendering.include?(path)
72
+
73
+ rendering.push(path)
74
+ begin
75
+ (@renderer || Renderer.new(Rails.application, host: config.host)).get(path)
76
+ ensure
77
+ rendering.pop
78
+ end
79
+ end
80
+ end
81
+
48
82
  # Memoization store that lives for one build. Cleared before and after every build.
49
83
  def build_cache
50
84
  @build_cache ||= BuildCache.new
@@ -55,6 +89,7 @@ module Kiln
55
89
  @pages = nil
56
90
  @building = nil
57
91
  @build_cache = nil
92
+ @renderer = nil
58
93
  end
59
94
  end
60
95
  end
@@ -1,6 +1,15 @@
1
1
  namespace :kiln do
2
+ # Rails and gems such as turbo-rails read secret_key_base while the app boots. A build ships nothing
3
+ # signed, so an app without a secret of its own boots with Rails' dummy secret.
4
+ task :secret_key_base do
5
+ next unless ENV["SECRET_KEY_BASE"].to_s.empty? && ENV["RAILS_MASTER_KEY"].to_s.empty?
6
+ next if Dir[File.join(Dir.pwd, "config/{master.key,credentials/*.key}")].any?
7
+
8
+ ENV["SECRET_KEY_BASE_DUMMY"] ||= "1"
9
+ end
10
+
2
11
  desc "Render every page into the output directory"
3
- task build: :environment do
12
+ task build: [ :secret_key_base, :environment ] do
4
13
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
5
14
  build = Kiln::Build.new
6
15
  # One log line per request buries the report. Warnings and errors still show; VERBOSE=1 shows all.
@@ -13,7 +22,8 @@ namespace :kiln do
13
22
  puts "Pages since last build: #{summary}"
14
23
  changes.each { |kind, paths| paths.each { puts " #{kind}: #{it}" } }
15
24
  end
16
- puts format("Output: %s (%.1fs)", build.output, elapsed)
25
+ status = report.success? ? "Output" : "Output left unchanged"
26
+ puts format("%s: %s (%s, %.1fs)", status, build.output, Rails.env, elapsed)
17
27
  exit 1 if report.failure?
18
28
  end
19
29
  end
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.2
4
+ version: 0.1.4
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: []