kiln 0.1.0 → 0.1.1

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: 651c0899f42d04129a81c15dffe03cf24d95cdfb1cf7de0ec04ca4474c7e62e8
4
- data.tar.gz: 23e810402d542846992a347836560c327e05d719a178301a4c76ccd77fdbb755
3
+ metadata.gz: 8ba761c39b8d2ffe60d03a4cdf48fdbb6ab1a7d4717b9716ab7107423dd2b2f1
4
+ data.tar.gz: 29f9eb12df579857663e8a44b1713928c7b7bbd4106da3cd6b52e645b2791a0f
5
5
  SHA512:
6
- metadata.gz: 606f816dc7ff50268542d41386d744d621cbe28faeea446cf8f60b2fe4fe7115d6c54e08d6099105a831c881f8ac59acd0c2600d63f77b4b4591cbc53b9b6fd9
7
- data.tar.gz: 49a7c794bf38f681e794e8141da259ba3d0699ec257e9f32fe8dd16677bc4d6ed9b126cc914a3e569d91f2372de4acf5b6b0b192ee168589ba997c1897b4c7b1
6
+ metadata.gz: 6597f99b761b60cdc3dcae600c18ebd8beab61e8ab82cd4fec4c57d797ba7f03213669ba5aa458338f68e508d7bf67a6dd582fb0d97e45ec7ac3b7c1b3725aac
7
+ data.tar.gz: c2036e9a40ba3458de6ecedb40da6a84b2e4a36775ef003e711d2a198fa1f566a5574660913df4fc5f168b553c03d04b46f32bd73df801c4b5d4895f0d2e8875
data/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1 (2026-11-07)
4
+
5
+ - 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.
6
+ - `config.verify_skip`: CSS selectors for sample markup (component demos, previews) whose links the
7
+ verifier ignores.
8
+ - `kiln:serve` takes `BIND` (default localhost), for process managers that expect 127.0.0.1.
9
+ - `config.files` copies files that aren't routes (licenses, verification files) into the output.
10
+ - Development builds run the bundle builds hooked into `assets:precompile` (`tailwindcss:build`,
11
+ `javascript:build`, `css:build`) instead of shipping stale bundles.
12
+ - The build fails when development middleware that injects markup (Hotwire Spark, web-console,
13
+ rack-mini-profiler) is active.
14
+ - The manifest moved from the output to `tmp/kiln-manifest.json`, so it is no longer published.
15
+ - LICENSE names the copyright holder.
16
+ - A production build of an app without `secret_key_base` uses a throwaway secret instead of failing.
17
+ - The build fails when `data-herb-*` or `data-tensaku-*` editor attributes reach the output.
18
+ - The content layer renders Markdown with commonmarker instead of Redcarpet: replace `gem "redcarpet"`
19
+ with `gem "commonmarker"`. The HTML changes, for example lists directly under a paragraph become lists and `^` is no longer superscript. Headings keep a plain `id`.
20
+ - `Kiln::Content.source_positions` marks rendered Markdown blocks with `data-tensaku-md` source
21
+ positions. On by default only in development with Tensaku loaded, never while building.
22
+
3
23
  ## 0.1.0 (2026-11-07)
4
24
 
5
25
  - First release.
data/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright TODO: Write your name
1
+ Copyright (c) 2026 David Afonso
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining
4
4
  a copy of this software and associated documentation files (the
data/README.md CHANGED
@@ -1,27 +1,26 @@
1
- # Kiln
1
+ <h1 align="center">Kiln</h1>
2
2
 
3
- Kiln fires a Rails app into a static site. Build pages with normal Rails (routes, controllers, views,
4
- helpers, Turbo, Stimulus), then run:
3
+ <p align="center">
4
+ <a href="https://rubygems.org/gems/kiln"><img src="https://img.shields.io/gem/v/kiln?color=b45d3c" alt="Gem version"></a>
5
+ <img src="https://img.shields.io/badge/ruby-4.0%2B-cc342d?logo=ruby&amp;logoColor=white" alt="Ruby 4.0+">
6
+ <img src="https://img.shields.io/badge/rails-8.1%2B-d30001?logo=rubyonrails&amp;logoColor=white" alt="Rails 8.1+">
7
+ <a href="https://github.com/davafons/kiln/actions/workflows/ci.yml"><img src="https://github.com/davafons/kiln/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
8
+ </p>
5
9
 
6
- ```sh
7
- RAILS_ENV=production bin/rails kiln:build
8
- ```
9
-
10
- Kiln renders every GET route through Rack, the same way a browser request goes through your app,
11
- and writes plain files to `dist/` that any static host can serve.
10
+ <p align="center">
11
+ Fire a Rails app into a static site.
12
+ </p>
12
13
 
13
- - **Routes are the page list.** A GET route with no params is built automatically. A route with
14
- params needs a param source or an explicit `skip`, or the build fails and names it.
15
- - **Builds fail loudly.** Every render error, missing asset and broken link is collected and printed
16
- as one report, and the task exits non-zero.
17
- - **Kiln knows nothing about your data.** Models and repositories stay ordinary app code.
14
+ <p align="center">
15
+ <a href="#configuration">Configuration</a> ·
16
+ <a href="CHANGELOG.md">Changelog</a>
17
+ </p>
18
18
 
19
- Requires Ruby 4.0+ and Rails 8.1+.
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`.
20
20
 
21
- Releases: push a `vX.Y.Z` tag matching `Kiln::VERSION`. CI runs, then the release workflow publishes
22
- to RubyGems through trusted publishing.
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.
23
22
 
24
- ## Setup
23
+ ## Build a site
25
24
 
26
25
  ```ruby
27
26
  # Gemfile
@@ -31,55 +30,75 @@ gem "kiln"
31
30
  ```ruby
32
31
  # config/kiln.rb
33
32
  Kiln.configure do |config|
34
- config.url = "https://example.com" # sitemap, absolute URLs, request host
35
- config.not_found = "/404" # rendered to 404.html
33
+ config.url = "https://example.com"
34
+ config.not_found = "/404"
36
35
  end
37
36
 
37
+ Kiln.pages do
38
+ params :post, -> { Post.published.map { { slug: it.slug } } }
39
+ skip :search, reason: "dynamic"
40
+ end
41
+ ```
42
+
43
+ ```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
38
54
  Kiln.pages do
39
55
  params :post, -> { Post.published.map { { slug: it.slug } } }
40
56
  params :page, -> { %w[en es ja].map { { locale: it } } + [ {} ] } # scope "(:locale)"
41
- paginate :blog_page, per: 10, total: -> { Post.count }, start: 2 # /blog/page/2 ...
57
+ paginate :blog_page, per: 10, total: -> { Post.count }, start: 2 # /blog/page/2, /blog/page/3, ...
42
58
  skip :search, reason: "dynamic"
43
59
  end
44
60
  ```
45
61
 
46
- `bin/rails kiln:routes` shows every GET route and whether it is built, skipped or uncovered.
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`.
47
65
 
48
- Rails internals (`/rails/*`), the health check, mounted engines and turbo-rails' native navigation
49
- routes are skipped by default. Redirect routes become redirects, and mounted Rack apps are built
50
- like any other route.
66
+ ## Develop and ship
51
67
 
52
- ## Tasks
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:
53
69
 
54
- | Task | What it does |
55
- |---|---|
56
- | `kiln:build` | Renders every page, exports assets, copies `public/`, writes redirects, sitemap and manifest, then verifies the output. Lists pages changed since the last build. `VERBOSE=1` shows request logs. |
57
- | `kiln:routes` | The route table. Exits 1 if any route is uncovered. |
58
- | `kiln:verify` | Checks internal links, anchors and importmap modules in the existing output. |
59
- | `kiln:check` | Builds into a temp dir and fails if the committed output differs. For CI. |
60
- | `kiln:serve` | Serves the output with static-host path resolution (`PORT`, default 4000). |
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).
61
78
 
62
79
  ## Configuration
63
80
 
64
81
  | Option | Default | |
65
82
  |---|---|---|
66
83
  | `output` | `"dist"` | Relative to `Rails.root`, or absolute. Wiped at the start of every build. |
67
- | `url` | `nil` | Public base URL. Needed for the sitemap and `absolute_urls`. |
84
+ | `url` | `nil` | Public base URL, for the sitemap and absolute URLs. |
68
85
  | `host` | from `url`, else `"localhost"` | Host header sent with every request. |
69
- | `paths` | `:directory` | `/now` → `now/index.html`. `:file` writes `now.html`. |
70
- | `assets` | `:referenced` | Only assets the output references (HTML, importmap, CSS `url()`). `:all` exports everything. |
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. |
71
88
  | `cname` | `nil` | Writes a `CNAME` file. |
72
89
  | `not_found` | `nil` | Path rendered to `404.html`. It may respond with 200 or 404. |
73
- | `redirects` | `:file` | `:file` (`_redirects`), `:meta_refresh` (HTML pages, for GitHub Pages), `:both`, or `false`. |
74
- | `sitemap` | `true` | Writes `sitemap.xml` (needs `url`). Pages marked `noindex` are left out. |
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" }`. |
75
93
  | `strip_source_maps` | `true` | Removes `sourceMappingURL` comments from JS and CSS. |
76
- | `absolute_urls` | `false` | Makes image URLs (img, srcset, og:/twitter: images) absolute. |
94
+ | `absolute_urls` | `false` | Makes image URLs absolute (img, srcset, og: and twitter: images). |
77
95
  | `external_links` | `false` | Adds `target="_blank" rel="noopener"` to links to other hosts. |
78
- | `processors` | `[]` | Your own HTML processors: `call(html, context)` returning a String. |
96
+ | `processors` | `[]` | Your HTML processors: `call(html, context)` returning a String. |
79
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]"`. |
80
99
  | `copy_public` | `true` | Copies `public/` (minus `public/assets`) into the output. |
81
100
 
82
- Hooks get a context with `output`, `env`, `manifest` and `report`:
101
+ Hooks receive a context with `output`, `env`, `manifest` and `report`:
83
102
 
84
103
  ```ruby
85
104
  Kiln.configure do |config|
@@ -88,22 +107,46 @@ Kiln.configure do |config|
88
107
  end
89
108
  ```
90
109
 
91
- CSRF tokens and meta tags are always stripped. Everything else in the HTML is left byte for byte as
92
- the app rendered it.
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"
132
+ ```
133
+
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.
93
135
 
94
- ## In your app
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.
95
137
 
96
- - `Kiln.building?` is true while a build renders pages. Use it to hide dev-only things.
97
- - `Kiln.build_cache.fetch(key) { ... }` memoizes for one build and is cleared before and after.
98
- - Builds run in production. Kiln runs `assets:precompile` in-process when needed and removes
99
- `public/assets` afterwards. Assets are fetched through the app, so keep
100
- `config.public_file_server.enabled = true` for builds.
101
- - Use root-absolute asset paths so every page's `<head>` stays identical and Turbo visits never
102
- force a full reload.
103
- - Feeds, `robots.txt`, `llms.txt` or JSON files are ordinary routes with views
104
- (`get "feed.xml"`). The file is written under the route's path.
138
+ Collections read Markdown files with YAML frontmatter, such as `content/blog/2024-05-01-hello.md`:
105
139
 
106
- ## Testing
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
107
150
 
108
151
  ```ruby
109
152
  require "kiln/test_helper"
@@ -116,49 +159,27 @@ class StaticSiteTest < ActiveSupport::TestCase
116
159
  end
117
160
  ```
118
161
 
119
- `kiln_build { |output| ... }` builds into a temp dir, fails with the report on any error and
120
- yields the output path.
162
+ `kiln_build { |output| ... }` builds into a temp dir, fails with the report on any error, and yields the output path.
121
163
 
122
- ## Content layer
164
+ ## Known limits
123
165
 
124
- Optional, and it works in server-rendered apps too:
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.
125
170
 
126
- ```ruby
127
- # Gemfile
128
- gem "redcarpet"
129
- gem "rouge"
171
+ ## Develop Kiln
130
172
 
131
- # config/application.rb, after Bundler.require
132
- require "kiln/content"
173
+ ```sh
174
+ bundle install
175
+ bin/test
176
+ bin/lint # RuboCop and bin/house-rules
133
177
  ```
134
178
 
135
- - **Markdown views:** `app/views/pages/about.html.md` renders through the layout like any view.
136
- `.md.erb` runs ERB first. Code blocks get Rouge CSS classes (`rougify style github`).
137
- - **Collections:** `content/blog/2024-05-01-hello.md` with YAML frontmatter.
138
-
139
- ```ruby
140
- posts = Kiln::Content.collection("blog")
141
- posts.all # visible entries, newest first
142
- posts.find("hello") # raises Kiln::Content::NotFound (a 404)
143
- post.title, post.published_at, post.html, post[:tags]
144
-
145
- # config/kiln.rb
146
- params :post, -> { Kiln::Content.collection("blog").map { { slug: it.slug } } }
147
- ```
148
-
149
- - **Publishing:** `draft: true` and future `published_at` entries are hidden, except in
150
- development when not building. `Kiln::Content.show_drafts` overrides this. Server-rendered apps
151
- can share a hidden entry with `posts.find(slug, preview_token: params[:token])`.
152
-
153
- ## Limitations in 0.1
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.
154
180
 
155
- - Pages render one at a time. Parallel rendering is planned.
156
- - Only exact `_redirects` rules count for the verifier and `kiln:serve`. Splat and placeholder
157
- rules in your own `public/_redirects` are written out but not followed.
158
- - JS modules are found through the importmap. Relative `import "./x.js"` between files is not
159
- followed.
160
- - Collections read `*.md` files only (`.md.erb` works for views).
181
+ 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.
161
182
 
162
183
  ## License
163
184
 
164
- MIT. See [LICENSE](LICENSE).
185
+ Copyright © 2026 David Afonso. Kiln is licensed under the [MIT License](LICENSE).
data/lib/kiln/assets.rb CHANGED
@@ -12,9 +12,11 @@ module Kiln
12
12
 
13
13
  class << self
14
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.
15
+ # removes what the precompile created, or nil when nothing was compiled. When assets are served
16
+ # dynamically, still runs the build steps hooked into assets:precompile (tailwindcss:build,
17
+ # javascript:build, css:build), so a development build never ships stale bundles.
16
18
  def precompile(app)
17
- return unless precompile?(app)
19
+ return build_bundles(app) unless precompile?(app)
18
20
 
19
21
  output_path = Pathname(app.config.assets.output_path)
20
22
  created = !output_path.exist?
@@ -54,10 +56,26 @@ module Kiln
54
56
  end
55
57
 
56
58
  private
57
- def run_precompile(app)
59
+ def build_bundles(app)
60
+ precompile_task(app)&.prerequisite_tasks&.each do |task|
61
+ next if task.name.end_with?("environment")
62
+
63
+ task.reenable
64
+ task.invoke
65
+ rescue StandardError => error
66
+ raise Kiln::Error, "#{task.name} failed: #{error.class}: #{error.message}"
67
+ end
68
+ nil
69
+ end
70
+
71
+ def precompile_task(app)
58
72
  require "rake"
59
73
  app.load_tasks unless Rake::Task.task_defined?("assets:precompile")
60
- task = Rake::Task["assets:precompile"]
74
+ Rake::Task["assets:precompile"] if Rake::Task.task_defined?("assets:precompile")
75
+ end
76
+
77
+ def run_precompile(app)
78
+ task = precompile_task(app)
61
79
  task.reenable
62
80
  task.invoke
63
81
  rescue StandardError => error
data/lib/kiln/build.rb CHANGED
@@ -7,6 +7,11 @@ module Kiln
7
7
  # Passed to before_build / after_build hooks.
8
8
  Context = Data.define(:output, :env, :manifest, :report)
9
9
 
10
+ # Development middleware that injects markup into every HTML response.
11
+ 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-]+=/
14
+
10
15
  attr_reader :app, :config, :pages_dsl, :output, :report, :manifest, :previous_manifest
11
16
 
12
17
  def initialize(app: Rails.application, config: Kiln.config, pages: Kiln.pages, output: nil)
@@ -17,9 +22,10 @@ module Kiln
17
22
  @report = Report.new
18
23
  @manifest = Manifest.new
19
24
  @redirects = []
25
+ @editor_markup = []
20
26
  end
21
27
 
22
- # Pages added, removed and changed since the previous build in the same output, or nil.
28
+ # Pages added, removed and changed since the previous build of the configured output, or nil.
23
29
  def changes
24
30
  previous_manifest&.diff(manifest)
25
31
  end
@@ -27,6 +33,8 @@ module Kiln
27
33
  def run
28
34
  Kiln.building! do
29
35
  guard_output!
36
+ guard_dev_middleware!
37
+ ensure_secret_key_base
30
38
  guard_static_files!
31
39
  cleanup = Assets.precompile(app)
32
40
  begin
@@ -36,13 +44,15 @@ module Kiln
36
44
  pages = Router.new(app.routes, pages_dsl, report:).pages
37
45
  pages.reject { it.path == config.not_found }.each { render_page(it) }
38
46
  render_not_found if config.not_found
47
+ report_editor_markup
39
48
 
40
49
  Assets.new(renderer:, output:, config:, report:).export
50
+ write_files
41
51
  Assets.copy_public(from: app.root.join("public"), to: output, report:, generated: generated_files) if config.copy_public
42
52
  write_redirects if config.redirects && @redirects.any?
43
53
  Sitemap.new(manifest, url: config.url).write(output) if config.sitemap && config.url
44
54
  write_cname if config.cname
45
- manifest.write(output)
55
+ write_manifest
46
56
 
47
57
  Verifier.new(output, config:).verify(report) if config.verify
48
58
  run_hooks(config.after_build_hooks)
@@ -69,6 +79,7 @@ module Kiln
69
79
  @redirects << Redirects::Entry.new(from: page.path, to: response.location, status: response.status)
70
80
  elsif response.success?
71
81
  body = response.html? ? Processors.apply(response.body, Processors::Context.new(path: page.path, config:, response:)) : response.body
82
+ @editor_markup << page.path if response.html? && body.match?(EDITOR_MARKUP)
72
83
  file = writer.write(page.path, response.content_type, body)
73
84
  manifest.add(page.path, file:, body:, content_type: response.content_type, noindex: Sitemap.noindex?(response, body))
74
85
  report.wrote(file)
@@ -79,6 +90,14 @@ module Kiln
79
90
  report.error(:render, describe(error), path: page.path)
80
91
  end
81
92
 
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-* or data-tensaku-* attributes reached #{pages}. " \
98
+ "Turn off Herb source attribution and Tensaku outside development, or build in production.")
99
+ end
100
+
82
101
  def render_not_found
83
102
  response = renderer.get(config.not_found)
84
103
  unless [ 200, 404 ].include?(response.status)
@@ -95,9 +114,33 @@ module Kiln
95
114
  Redirects.new(@redirects, mode: config.redirects, writer:, host: config.host, url: config.url).write(output).each { report.wrote(it) }
96
115
  end
97
116
 
117
+ # The manifest is build state, not part of the site: it lives in tmp/, and only for the configured
118
+ # output, so throwaway builds (tests, temp dirs) never overwrite it.
119
+ def manifest_dir
120
+ app.root.join("tmp") if output.expand_path == config.output_path(app.root).expand_path
121
+ end
122
+
123
+ def write_manifest
124
+ return unless manifest_dir
125
+
126
+ FileUtils.mkdir_p(manifest_dir)
127
+ manifest.write(manifest_dir)
128
+ end
129
+
130
+ def write_files
131
+ config.files.each do |target, source|
132
+ source = app.root.join(source)
133
+ next report.error(:write, "#{source} does not exist", path: "/#{target}") unless source.file?
134
+
135
+ report.wrote(writer.write_file(target.to_s, source.binread))
136
+ rescue Kiln::Error => error
137
+ report.error(:write, error.message, path: "/#{target}")
138
+ end
139
+ end
140
+
98
141
  # Files Kiln writes on purpose that may also exist in public/ (Rails ships a public/404.html).
99
142
  def generated_files
100
- [ ("404.html" if config.not_found), ("CNAME" if config.cname) ].compact
143
+ [ ("404.html" if config.not_found), ("CNAME" if config.cname), *config.files.keys.map(&:to_s) ].compact
101
144
  end
102
145
 
103
146
  def write_cname
@@ -114,8 +157,8 @@ module Kiln
114
157
  end
115
158
 
116
159
  def prepare_output
117
- previous = output.join(Manifest::FILENAME)
118
- @previous_manifest = Manifest.load(previous) if previous.file?
160
+ previous = manifest_dir&.join(Manifest::FILENAME)
161
+ @previous_manifest = Manifest.load(previous) if previous&.file?
119
162
  FileUtils.rm_rf(output)
120
163
  FileUtils.mkdir_p(output)
121
164
  end
@@ -129,6 +172,22 @@ module Kiln
129
172
  end
130
173
  end
131
174
 
175
+ def guard_dev_middleware!
176
+ active = app.middleware.map(&:name) & DEV_MIDDLEWARE
177
+ return if active.empty?
178
+
179
+ raise Kiln::Error, "#{active.to_sentence} would add development markup to every page. " \
180
+ "Load it only under bin/rails server (if defined?(Rails::Server)), or build in production."
181
+ end
182
+
183
+ # Rails refuses to render in production without a secret. A build ships nothing signed (CSRF tokens
184
+ # are stripped), so an app without one gets a throwaway secret instead of a failed build.
185
+ def ensure_secret_key_base
186
+ app.config.secret_key_base
187
+ rescue ArgumentError
188
+ app.config.secret_key_base = SecureRandom.hex(64)
189
+ end
190
+
132
191
  # After a precompile, assets are fetched from public/assets through ActionDispatch::Static.
133
192
  def guard_static_files!
134
193
  return unless app.config.respond_to?(:assets) && !app.config.assets.server
@@ -24,8 +24,13 @@ module Kiln
24
24
  attr_accessor :sitemap
25
25
  # Runs the verifier (links, anchors, importmap) after every build.
26
26
  attr_accessor :verify
27
+ # CSS selectors for sample markup whose links the verifier ignores (for example component demos).
28
+ attr_accessor :verify_skip
27
29
  # Copy public/ into the output (minus public/assets).
28
30
  attr_accessor :copy_public
31
+ # Extra files that aren't routes: { "octicons-license.txt" => "vendor/octicons/LICENSE" }.
32
+ # Sources are relative to Rails.root.
33
+ attr_accessor :files
29
34
 
30
35
  attr_reader :before_build_hooks, :after_build_hooks
31
36
  attr_writer :host
@@ -45,7 +50,9 @@ module Kiln
45
50
  @redirects = :file
46
51
  @sitemap = true
47
52
  @verify = true
53
+ @verify_skip = []
48
54
  @copy_public = true
55
+ @files = {}
49
56
  @before_build_hooks = []
50
57
  @after_build_hooks = []
51
58
  end
@@ -9,7 +9,9 @@ module Kiln
9
9
  @collection, @path = collection.to_s, Pathname(path)
10
10
  match = FILENAME.match(@path.basename.to_s)
11
11
  @slug = match[:slug]
12
- @attributes, @body = Frontmatter.parse(@path.read)
12
+ text = @path.read
13
+ @attributes, @body = Frontmatter.parse(text)
14
+ @frontmatter_lines = text.delete_suffix(body).count("\n")
13
15
  @published_at = attributes["published_at"] || (Date.iso8601(match[:date]) if match[:date])
14
16
  end
15
17
 
@@ -17,7 +19,12 @@ module Kiln
17
19
  def draft? = attributes["draft"] == true
18
20
  def scheduled? = published_at.present? && published_at.in_time_zone.future?
19
21
  def published? = !draft? && !scheduled?
20
- def html = @html ||= Markdown.render(body).html_safe
22
+
23
+ def html
24
+ return Markdown.render(body, path:, line_offset: @frontmatter_lines).html_safe if Content.source_positions
25
+ @html ||= Markdown.render(body).html_safe
26
+ end
27
+
21
28
  def to_param = slug
22
29
  def [](key) = attributes[key.to_s]
23
30
  def to_h = attributes
@@ -2,11 +2,16 @@ module Kiln
2
2
  module Content
3
3
  # ActionView template handlers. A handler returns Ruby source that evaluates to the output.
4
4
  module Handlers
5
- # Plain Markdown never changes between renders, so convert it once at compile time.
6
- Markdown = ->(_template, source) { "#{Content::Markdown.render(source).inspect}.html_safe" }
5
+ # Plain Markdown never changes between renders, so convert it once at compile time. Source
6
+ # positions are a development aid, so that variant renders on each request.
7
+ Markdown = ->(template, source) do
8
+ positioned = "Kiln::Content::Markdown.render(#{source.inspect}, path: #{template.identifier.inspect})"
9
+ "(Kiln::Content.source_positions ? #{positioned} : #{Content::Markdown.render(source).inspect}).html_safe"
10
+ end
7
11
 
8
12
  # ERB fills a fresh output buffer, then its result goes through Markdown on every render.
9
- # "begin;" keeps the ERB source on its original line numbers.
13
+ # "begin;" keeps the ERB source on its original line numbers. No source positions: after ERB,
14
+ # Markdown lines no longer match the lines in the template file.
10
15
  MarkdownERB = ->(template, source) do
11
16
  erb = ActionView::Template.registered_template_handler(:erb).call(template, source)
12
17
  "Kiln::Content::Markdown.render(begin;#{erb}\nend.to_s).html_safe"
@@ -1,18 +1,51 @@
1
1
  module Kiln
2
2
  module Content
3
3
  module Markdown
4
- EXTENSIONS = { fenced_code_blocks: true, tables: true, autolink: true, strikethrough: true }.freeze
4
+ OPTIONS = {
5
+ render: { unsafe: true },
6
+ extension: { table: true, strikethrough: true, autolink: true, header_ids: "" }
7
+ }.freeze
8
+ PLUGINS = { syntax_highlighter: nil }.freeze
9
+ # header_ids also appends an empty anchor link to every heading. Headings keep only the id;
10
+ # the app decides how to link them.
11
+ HEADING_ANCHOR = %r{<a href="#[^"]*" aria-label="[^"]*" data-heading-content="[^"]*" class="anchor"></a>}
5
12
 
6
- class Renderer < Redcarpet::Render::HTML
7
- def block_code(code, language)
8
- lexer = Rouge::Lexer.find_fancy(language.to_s, code) || Rouge::Lexers::PlainText.new
9
- %(<pre class="highlight #{lexer.tag}"><code>#{Rouge::Formatters::HTML.new.format(lexer.lex(code))}</code></pre>\n)
10
- end
13
+ # With a path, block elements carry their source position. line_offset is the number of lines
14
+ # above the text in that file, such as frontmatter.
15
+ def self.render(text, path: nil, line_offset: 0)
16
+ options = path ? OPTIONS.deep_merge(render: { sourcepos: true }) : OPTIONS
17
+ document = Commonmarker.parse(text.to_s, options:)
18
+ document.walk { highlight(it, sourcepos: path) if it.type == :code_block }
19
+ html = document.to_html(options:, plugins: PLUGINS).gsub(HEADING_ANCHOR, "")
20
+ path ? SourcePosition.rewrite(html, path, line_offset) : html
21
+ end
22
+
23
+ # Swaps a code block for raw HTML highlighted by Rouge, with CSS classes and no inline styles.
24
+ def self.highlight(node, sourcepos:)
25
+ code = node.string_content
26
+ lexer = Rouge::Lexer.find_fancy(node.fence_info.split.first.to_s, code) || Rouge::Lexers::PlainText.new
27
+ position = node.source_position.values_at(:start_line, :start_column, :end_line, :end_column)
28
+ attribute = %( data-sourcepos="%d:%d-%d:%d") % position if sourcepos
29
+ html = %(<pre class="highlight #{lexer.tag}"#{attribute}><code>#{Rouge::Formatters::HTML.new.format(lexer.lex(code))}</code></pre>\n)
30
+ node.replace(Commonmarker::Node.new(:html_block, literal: html))
11
31
  end
32
+ end
12
33
 
13
- # A new parser per call: Redcarpet parsers aren't safe to share between threads.
14
- def self.render(text)
15
- Redcarpet::Markdown.new(Renderer.new(with_toc_data: true), EXTENSIONS).render(text.to_s)
34
+ # Editor markup for Tensaku: data-tensaku-md="path:startLine:startCol-endLine:endCol", with the
35
+ # path relative to Rails.root. Only block elements carry it; commonmarker's positions on inline
36
+ # elements are dropped. The format is a draft, and this is the one place that writes it.
37
+ module SourcePosition
38
+ BLOCKS = %w[p h1 h2 h3 h4 h5 h6 ul ol li blockquote pre table hr].to_set.freeze
39
+ ATTRIBUTE = /<(\w+)([^>]*?) data-sourcepos="(\d+):(\d+)-(\d+):(\d+)"/
40
+
41
+ def self.rewrite(html, path, line_offset)
42
+ relative = ERB::Util.html_escape(Pathname(path).relative_path_from(Rails.root).to_s)
43
+ html.gsub(ATTRIBUTE) do
44
+ tag, rest = $1, $2
45
+ next "<#{tag}#{rest}" unless BLOCKS.include?(tag)
46
+
47
+ %(<#{tag}#{rest} data-tensaku-md="#{relative}:#{$3.to_i + line_offset}:#{$4}-#{$5.to_i + line_offset}:#{$6}")
48
+ end
16
49
  end
17
50
  end
18
51
  end
data/lib/kiln/content.rb CHANGED
@@ -2,14 +2,15 @@
2
2
  # Optional and independent of the exporter, so server-rendered Rails apps can use it too.
3
3
  #
4
4
  # # Gemfile
5
- # gem "redcarpet"
5
+ # gem "commonmarker"
6
6
  # gem "rouge"
7
7
  #
8
8
  # # config/initializers/kiln.rb
9
9
  # require "kiln/content"
10
10
  #
11
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. Code blocks are highlighted by Rouge with CSS
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
13
14
  # classes, so add a Rouge theme to your stylesheet (`rougify style github`).
14
15
  #
15
16
  # Collections. content/blog/2024-05-01-hello.md:
@@ -34,14 +35,19 @@
34
35
  # override. A server-rendered app can share a hidden entry with
35
36
  # `posts.find(params[:slug], preview_token: params[:token])`, where the token is `post.preview_token`.
36
37
  #
38
+ # Source positions. With Kiln::Content.source_positions on, each rendered block of a .md view or
39
+ # collection entry carries data-tensaku-md="path:startLine:startCol-endLine:endCol" for the Tensaku
40
+ # editor. .md.erb views get none. It defaults to on in development when Tensaku is loaded, and is
41
+ # always off while Kiln is building.
42
+ #
37
43
  # Settings: Kiln::Content.root (default Rails.root/content), Kiln::Content.show_drafts,
38
- # Kiln::Content.preview_secret (default secret_key_base).
44
+ # Kiln::Content.preview_secret (default secret_key_base), Kiln::Content.source_positions.
39
45
  begin
40
- require "redcarpet"
46
+ require "commonmarker"
41
47
  require "rouge"
42
48
  rescue LoadError => error
43
- raise LoadError, "kiln/content needs the redcarpet and rouge gems. " \
44
- "Add `gem \"redcarpet\"` and `gem \"rouge\"` to your Gemfile. (#{error.message})"
49
+ raise LoadError, "kiln/content needs the commonmarker and rouge gems. " \
50
+ "Add `gem \"commonmarker\"` and `gem \"rouge\"` to your Gemfile. (#{error.message})"
45
51
  end
46
52
 
47
53
  require "kiln"
@@ -57,7 +63,7 @@ module Kiln
57
63
  class NotFound < Kiln::Error; end
58
64
 
59
65
  class << self
60
- attr_writer :root, :show_drafts, :preview_secret
66
+ attr_writer :root, :show_drafts, :preview_secret, :source_positions
61
67
 
62
68
  def root
63
69
  Pathname(@root || Rails.root.join("content"))
@@ -68,6 +74,12 @@ module Kiln
68
74
  Rails.env.development? && !Kiln.building?
69
75
  end
70
76
 
77
+ def source_positions
78
+ return false if Kiln.building?
79
+ return @source_positions unless @source_positions.nil?
80
+ Rails.env.development? && !defined?(::Tensaku).nil?
81
+ end
82
+
71
83
  def preview_secret
72
84
  @preview_secret || Rails.application.secret_key_base
73
85
  end
@@ -83,7 +95,7 @@ module Kiln
83
95
  end
84
96
 
85
97
  def reset!
86
- @root = @show_drafts = @preview_secret = nil
98
+ @root = @show_drafts = @preview_secret = @source_positions = nil
87
99
  @collections = {}
88
100
  end
89
101
 
data/lib/kiln/report.rb CHANGED
@@ -3,7 +3,7 @@ module Kiln
3
3
  class Report
4
4
  Entry = Data.define(:kind, :message, :path)
5
5
 
6
- KINDS = %i[uncovered_route render asset broken_link missing_anchor importmap redirect write hook other].freeze
6
+ KINDS = %i[uncovered_route render editor_markup asset broken_link missing_anchor importmap redirect write hook other].freeze
7
7
 
8
8
  attr_reader :errors, :warnings, :written
9
9
 
data/lib/kiln/router.rb CHANGED
@@ -27,20 +27,6 @@ module Kiln
27
27
  @rows
28
28
  end
29
29
 
30
- # Text table for `kiln:routes`.
31
- def table
32
- lines = rows.map do |row|
33
- status = case row.status
34
- when :built then "built #{row.count}"
35
- when :skipped then "skipped: #{row.reason}"
36
- else "uncovered"
37
- end
38
- [ row.name || "-", row.path, status ]
39
- end
40
- widths = [ 0, 1 ].map { |i| lines.map { it[i].length }.max.to_i }
41
- lines.map { |name, path, status| "#{name.ljust(widths[0])} #{path.ljust(widths[1])} #{status}".rstrip }.join("\n")
42
- end
43
-
44
30
  private
45
31
  attr_reader :dsl, :report
46
32
 
data/lib/kiln/server.rb CHANGED
@@ -3,9 +3,9 @@ require "rack/mime"
3
3
  module Kiln
4
4
  # Rack app that serves the built output the way a static host would.
5
5
  class Server
6
- def self.start(root, port:)
6
+ def self.start(root, port:, host: "localhost")
7
7
  require "rackup"
8
- Rackup::Handler.default.run(new(root), Host: "localhost", Port: port)
8
+ Rackup::Handler.default.run(new(root), Host: host, Port: port)
9
9
  end
10
10
 
11
11
  def initialize(root)
data/lib/kiln/verifier.rb CHANGED
@@ -9,6 +9,7 @@ module Kiln
9
9
  @resolver = StaticResolver.new(@output)
10
10
  @redirect_sources = Redirects.load(@output.join(Redirects::FILENAME)).map(&:from).to_set
11
11
  @anchors = {}
12
+ @skip = config.verify_skip.join(", ").presence
12
13
  end
13
14
 
14
15
  def verify(report)
@@ -22,8 +23,11 @@ module Kiln
22
23
  def check_page(file)
23
24
  page = page_path(file)
24
25
  doc = parse(@output.join(file))
26
+ skipped = @skip ? doc.css(@skip).flat_map { [ it, *it.css("*") ] }.to_set : Set.new
25
27
 
26
28
  doc.xpath("//*[@href or @src or @srcset]").each do |element|
29
+ next if skipped.include?(element)
30
+
27
31
  urls_in(element).each { check_link(it, page) }
28
32
  end
29
33
  doc.css('script[type="importmap"]').each { check_importmap(it.text, page) }
data/lib/kiln/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Kiln
2
- VERSION = "0.1.0"
2
+ VERSION = "0.1.1"
3
3
  end
@@ -16,18 +16,4 @@ namespace :kiln do
16
16
  puts format("Output: %s (%.1fs)", build.output, elapsed)
17
17
  exit 1 if report.failure?
18
18
  end
19
-
20
- desc "Fail if the committed output differs from a fresh build"
21
- task check: :environment do
22
- result = Kiln::Check.new.run
23
- if result.report.failure?
24
- puts result.report
25
- elsif result.diff.empty?
26
- puts "Kiln check: #{Kiln.config.output_path} is up to date."
27
- else
28
- puts "Kiln check: #{Kiln.config.output_path} is out of date. Run kiln:build and commit the result."
29
- puts result.diff
30
- end
31
- exit 1 unless result.success?
32
- end
33
19
  end
@@ -1,11 +1,12 @@
1
1
  namespace :kiln do
2
- desc "Serve the built output like a static host (PORT, default 4000)"
2
+ desc "Serve the built output like a static host (PORT, default 4000; BIND, default localhost)"
3
3
  task serve: :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
 
7
7
  port = Integer(ENV.fetch("PORT", 4000))
8
- puts "Kiln: serving #{output} at http://localhost:#{port}"
9
- Kiln::Server.start(output, port:)
8
+ host = ENV.fetch("BIND", "localhost")
9
+ puts "Kiln: serving #{output} at http://#{host}:#{port}"
10
+ Kiln::Server.start(output, port:, host:)
10
11
  end
11
12
  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.0
4
+ version: 0.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - David Afonso
@@ -81,7 +81,6 @@ files:
81
81
  - lib/kiln/assets.rb
82
82
  - lib/kiln/build.rb
83
83
  - lib/kiln/build_cache.rb
84
- - lib/kiln/check.rb
85
84
  - lib/kiln/configuration.rb
86
85
  - lib/kiln/content.rb
87
86
  - lib/kiln/content/collection.rb
@@ -112,9 +111,7 @@ files:
112
111
  - lib/kiln/version.rb
113
112
  - lib/kiln/writer.rb
114
113
  - lib/tasks/kiln/build.rake
115
- - lib/tasks/kiln/routes.rake
116
114
  - lib/tasks/kiln/serve.rake
117
- - lib/tasks/kiln/verify.rake
118
115
  homepage: https://github.com/davafons/kiln
119
116
  licenses:
120
117
  - MIT
data/lib/kiln/check.rb DELETED
@@ -1,22 +0,0 @@
1
- require "tmpdir"
2
-
3
- module Kiln
4
- # Builds into a temp dir and compares the result with the committed output.
5
- class Check
6
- Result = Data.define(:report, :diff) do
7
- def success? = report.success? && diff.empty?
8
- end
9
-
10
- def initialize(app: Rails.application, config: Kiln.config)
11
- @app = app
12
- @config = config
13
- end
14
-
15
- def run
16
- Dir.mktmpdir("kiln-check") do |dir|
17
- report = Build.new(app: @app, config: @config, output: dir).run
18
- Result.new(report:, diff: TreeDiff.call(@config.output_path(@app.root), dir))
19
- end
20
- end
21
- end
22
- end
@@ -1,12 +0,0 @@
1
- namespace :kiln do
2
- desc "List every GET route and whether Kiln builds, skips, or misses it"
3
- task routes: :environment do
4
- report = Kiln::Report.new
5
- router = Kiln::Router.new(Rails.application.routes, Kiln.pages, report:)
6
- puts router.table
7
- if report.failure?
8
- puts "", report
9
- exit 1
10
- end
11
- end
12
- end
@@ -1,15 +0,0 @@
1
- namespace :kiln do
2
- desc "Check internal links, anchors and importmap modules in the built output"
3
- task verify: :environment do
4
- output = Kiln.config.output_path
5
- abort "Kiln: #{output} does not exist. Run kiln:build first." unless output.directory?
6
-
7
- report = Kiln::Verifier.new(output, config: Kiln.config).verify(Kiln::Report.new)
8
- if report.success?
9
- puts "Kiln verify: no problems found in #{output}."
10
- else
11
- puts report.to_s(title: "Kiln verify")
12
- exit 1
13
- end
14
- end
15
- end