jekyll-llms-generator 0.3.1 → 0.4.0

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: 8409a3c30c79e3ffef23420295ff8f62f75e6c4ed5d6a9967abfc11e52931eae
4
- data.tar.gz: f1ba06610f40eff111d59bfa6b7734ed6bb284793a74459c211d222b83d35008
3
+ metadata.gz: 62dba9651cf18715cdd8b2119cf2b342f9f72401686e8258cd518f82c8b39a05
4
+ data.tar.gz: '09f1435e5887482269137c59da2eb6f336b2780cdaf34a3576b1f50becfcfe24'
5
5
  SHA512:
6
- metadata.gz: 36926514eba932fb3a5e1cc53f07db07c71778d2be1d7efb5cfbbaadce353aa48de10530cf08ad9eb0b59fb2cd39427b48823bf5e006875b254824049b792ee1
7
- data.tar.gz: f0f88e6ec7392fdc2d58ee02ea47f163ec25604cf14a76b8baeba62cf372a9da19af4f64e21311fd18c7f7275c0d40eacb542ed4e039a51807bfc3e45738d2d8
6
+ metadata.gz: bc23a2e06e1154aea8ac1a9bb014c0d1e1e626c7e6ed8f30a78b3ec373ee49458daa1ef2a481279a0a13a8db59712bafaa9525852379c642e4fe1650c1bc232e
7
+ data.tar.gz: 889846150fb98dc73d6ad899d2da7538cfcb33f306c42c38340eaece42521ca17006a962ff97ececd8ebadd76d9ed22357e17b5960f40673e0264a117143edb2
data/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [0.4.0] - 2026-11-28
6
+
7
+ ### Fixed
8
+ - `llms-full.txt` bodies are now built from the page's content after Liquid has run, so raw `{% %}` and `{{ }}` tags no longer leak into the file, newlines are kept, and entries read as clean Markdown: `##` headings, blank-line separated paragraphs and lists, fenced code blocks, links as `[text](absolute-url)`, no HTML, entities decoded. The content comes from Jekyll's own single Liquid render, captured by a pass-through converter (highest priority, matches Markdown and HTML sources only, returns the content unchanged, contributes no output extension) and finalized in the `post_convert` hook. The plugin never renders Liquid a second time, so stateful tags such as numbered citations keep their numbering.
9
+ - If nothing was captured for an entry, a warning is logged and its body is left out of `llms-full.txt`.
10
+ - The description fallback no longer renders the excerpt, so a Liquid error there can't abort the build. It reads the excerpt source as plain text.
11
+ - The link to `llms.txt` is added to the final rendered output of every HTML page and document (`post_render`), so it works with layouts. Before, it only touched `site.pages` whose own source contained `</head>`. The href follows `baseurl`, and `link_tag: false` turns it off.
12
+ - Documents and pages are excluded when they have `sitemap: false`, a `robots` value containing `noindex`, or belong to a collection with `output: false`, as well as `llms_txt: false`.
13
+ - Titles are escaped for Markdown links (square brackets, newlines). A missing title falls back to one built from the slug or URL instead of `[](url)`.
14
+ - `pages:` entries now match documents in collections as well as pages, and no longer need the exact trailing slash.
15
+ - README said the description fell back to the first paragraph. It is the first sentence of it, and the README now says so.
16
+
17
+ ### Changed
18
+ - The injected tag is now `<link rel="describedby" href="/llms.txt">`, the relation the llmstxt.org spec recommends. `rel="ai"` is not part of the spec and is no longer emitted.
19
+ - The plugin is opt-in: with no `llms_txt` key in `_config.yml` it writes no files and injects no tags. Sites that already have the block are unaffected.
20
+ - Requires Ruby 3.0 or newer and Jekyll 4.2 or newer (`post_convert` hook).
21
+ - `llms-full.txt` has a blank line after each section heading.
22
+
23
+ ### Removed
24
+ - The unused `write_file` method.
25
+
26
+ ### Added
27
+ - Test suite run by `bundle exec rake`, and a GitHub Actions workflow (Ruby 3.1, 3.2, 3.3).
28
+
5
29
  ## [0.3.1] - 2026-08-20
6
30
 
7
31
  ### Changed
@@ -28,4 +52,4 @@ All notable changes to this project will be documented in this file.
28
52
  - Optional `/llms-full.txt` with stripped-HTML content (config: `full: true`)
29
53
  - Optional `<link rel="ai" href="/llms.txt">` injection into HTML `<head>`
30
54
  - Limit control per section (`limit:`)
31
- - Geocoding-style configuration with `title`, `tagline`, `intro`, and `sections`
55
+ - Configuration with `title`, `tagline`, `intro`, and `sections`
data/README.md CHANGED
@@ -1,19 +1,19 @@
1
1
  # jekyll-llms-generator
2
2
 
3
- A Jekyll generator plugin that automatically builds an `/llms.txt` file every time your site builds — keeping AI language models up to date with your latest content.
3
+ A Jekyll plugin that builds `/llms.txt` (and optionally `/llms-full.txt`) every time your site builds.
4
4
 
5
5
  [![Gem Version](https://badge.fury.io/rb/jekyll-llms-generator.svg)](https://badge.fury.io/rb/jekyll-llms-generator)
6
6
 
7
7
  ## What is llms.txt?
8
8
 
9
- [llms.txt](https://llmstxt.org/) is an emerging convention that lets website owners expose a structured plain-text summary of their site's content for AI models and LLM crawlers. It's like `robots.txt`, but instead of telling crawlers what to ignore it tells them what matters and where to find it.
9
+ [llms.txt](https://llmstxt.org/) is a convention for giving AI models a plain-text map of your site. It works a bit like `robots.txt`, but it lists what matters and where to find it.
10
10
 
11
11
  ## Installation
12
12
 
13
13
  Add to your site's `Gemfile`:
14
14
 
15
15
  ```ruby
16
- gem "jekyll-llms-generator", "~> 0.1"
16
+ gem "jekyll-llms-generator", "~> 0.4"
17
17
  ```
18
18
 
19
19
  Add to your `_config.yml` plugins list:
@@ -27,7 +27,7 @@ Then run `bundle install`.
27
27
 
28
28
  ## Configuration
29
29
 
30
- All configuration lives under the `llms_txt:` key in `_config.yml`.
30
+ The plugin is opt-in. Without an `llms_txt:` key in `_config.yml` it writes no files and adds no tags. Add the key (an empty `llms_txt: {}` is enough) to turn it on, and set `enabled: false` to switch it off again.
31
31
 
32
32
  ```yaml
33
33
  llms_txt:
@@ -36,8 +36,8 @@ llms_txt:
36
36
  intro: |
37
37
  Jason Chance is a DDA director and web developer writing about public finance,
38
38
  local government technology, and downtown revitalization.
39
- link_tag: true # inject <link rel="ai" href="/llms.txt"> into every HTML page (default: true)
40
- full: false # also generate /llms-full.txt with full stripped-HTML content (default: false)
39
+ link_tag: true # add <link rel="describedby" href="/llms.txt"> to every HTML page (default: true)
40
+ full: false # also write /llms-full.txt with the full text of each entry (default: false)
41
41
  sections:
42
42
  - title: "Blog Posts"
43
43
  collection: posts
@@ -54,64 +54,71 @@ llms_txt:
54
54
 
55
55
  | Key | Default | Description |
56
56
  |-----|---------|-------------|
57
+ | `enabled` | `true` | Set to `false` to turn the plugin off while keeping the block |
57
58
  | `title` | site `title` | H1 heading at the top of `llms.txt` |
58
59
  | `tagline` | site `description` | Blockquote line below the title |
59
60
  | `intro` | _(none)_ | Optional paragraph after the tagline |
60
- | `link_tag` | `true` | Inject `<link rel="ai" href="/llms.txt">` into HTML head |
61
- | `full` | `false` | Also generate `/llms-full.txt` with full stripped-HTML content; adds a discovery link in `llms.txt` header |
61
+ | `link_tag` | `true` | Add `<link rel="describedby" href="/llms.txt">` to the `<head>` of every rendered HTML page. Set to `false` to skip it |
62
+ | `full` | `false` | Also write `/llms-full.txt` and link to it from `llms.txt` |
62
63
  | `sections` | `[]` | Array of section definitions (see below) |
63
64
 
64
65
  ### Section options
65
66
 
66
- Each section must have a `title`. Specify one or both of `collection` and `pages`.
67
+ Each section needs a `title`. Give it a `collection`, `pages`, or both.
67
68
 
68
69
  | Key | Description |
69
70
  |-----|-------------|
70
71
  | `collection` | Jekyll collection name (`posts`, `projects`, etc.) |
71
72
  | `limit` | Max number of items from this collection |
72
- | `pages` | Array of page URLs to include |
73
+ | `pages` | Array of URLs. They can match a page or a document in any collection, with or without the trailing slash (`/about` and `/about/` are the same) |
73
74
 
74
- ### Opt-out per document
75
+ ### What gets left out
75
76
 
76
- Add `llms_txt: false` to any post or collection document's frontmatter to exclude it:
77
+ A document or page is skipped when any of these is true:
77
78
 
78
- ```yaml
79
- ---
80
- title: "Internal Draft"
81
- llms_txt: false
82
- ---
83
- ```
79
+ - its front matter has `llms_txt: false`
80
+ - its front matter has `sitemap: false`
81
+ - its `robots` value contains `noindex`
82
+ - it belongs to a collection with `output: false` (those URLs don't exist on the built site)
84
83
 
85
- ### Description used in llms.txt
84
+ ### Titles and descriptions
86
85
 
87
- The plugin looks for a description in this order:
86
+ A title with square brackets is escaped so the Markdown link stays intact. If an entry has no title, the plugin builds one from its slug or URL ("my-first-post" becomes "My First Post").
88
87
 
89
- 1. `description:` frontmatter
90
- 2. `tagline:` frontmatter
91
- 3. Automatically generated excerpt (first paragraph)
88
+ The description comes from the first of these that exists:
92
89
 
93
- Descriptions use the first complete sentence — no hard character truncation.
90
+ 1. `description:` front matter
91
+ 2. `tagline:` front matter
92
+ 3. The first paragraph of the excerpt, cut to its first complete sentence
93
+
94
+ The excerpt is read as plain text, with Liquid tags removed and Markdown stripped. It is never rendered, so a broken tag in an excerpt can't stop the build.
94
95
 
95
96
  ## Output
96
97
 
97
- **`/llms.txt`** — compact reference: title, tagline, intro, and a bulleted list of links with first-sentence descriptions per section. When `full: true`, includes a `[Full content version](/llms-full.txt)` link in the header so LLM crawlers can discover the full file.
98
+ **`/llms.txt`** is the compact index: title, tagline, intro, and a bulleted list of links with a one-sentence description for each section. When `full: true`, the header also links to `llms-full.txt`.
98
99
 
99
- **`/llms-full.txt`** — full content file (when `full: true`). Each entry uses `### [Title](url)` headings, a `> description` blockquote, the complete stripped-HTML article text, and `---` separators between articles — making article boundaries unambiguous for LLM parsers.
100
+ **`/llms-full.txt`** (when `full: true`) holds the full text of every listed entry. Each one has a `### [Title](url)` heading, a `> description` blockquote, the body, and a `---` separator.
100
101
 
101
- ## Discovery
102
+ The body is the page's own content after Jekyll has run Liquid on it (`{% include %}`, `{% cite %}` and `{{ }}` are resolved), before Markdown conversion and before your layout, so navigation and footers stay out. The plugin doesn't run Liquid itself. A small pass-through converter records what Jekyll's single Liquid render produced, so stateful tags (numbered citations, counters, once-per-page scripts) behave exactly as they do without the plugin. The result is plain Markdown:
102
103
 
103
- AI crawlers discover `llms.txt` by checking `<your-site>/llms.txt` directly, the same way they check `robots.txt` or `sitemap.xml`. Additional discovery signals:
104
+ - headings stay as `##` lines, with paragraphs and lists separated by blank lines
105
+ - fenced code blocks (and `{% highlight %}` blocks) come out as fenced blocks
106
+ - links are `[text](absolute-url)`, with relative links resolved against your `url` and `baseurl`
107
+ - HTML tags are removed and entities are decoded
108
+
109
+ If nothing was captured for an entry (for example a `.txt` page, which Jekyll doesn't convert), the plugin logs a warning and leaves that entry's body out. A Liquid error in a page fails the build the way it does without the plugin.
110
+
111
+ ## Discovery
104
112
 
105
- - The optional `<link rel="ai" href="/llms.txt">` injected into every HTML page's `<head>` (`link_tag: true`, on by default)
106
- - The `[Full content version]` link in the `llms.txt` header points crawlers to `llms-full.txt`
113
+ The llmstxt.org spec says a page can point to the `llms.txt` that covers it with `rel="describedby"`, as an HTML `<link>` or an HTTP `Link:` header. With `link_tag: true` the plugin adds the `<link>` to the final HTML of every page and document, layout-based or not, with the href following your `baseurl`. If you'd rather send the HTTP header from your server or CDN, set `link_tag: false`.
107
114
 
108
- You can also submit your site to the [llmstxt.org directory](https://directory.llmstxt.cloud/) for broader discovery.
115
+ Crawlers also check `<your-site>/llms.txt` directly, and the header link in `llms.txt` points them to `llms-full.txt`.
109
116
 
110
117
  ## Compatibility
111
118
 
112
- - Jekyll 3.7 – 4.x
113
- - Ruby 2.7+
114
- - Works with GitHub Pages via the `remote_theme` workflow (plugin must be listed in `plugins:`)
119
+ - Jekyll 4.2 to 4.x (the capture uses the `post_convert` hook)
120
+ - Ruby 3.0 or newer (CI runs 3.1, 3.2 and 3.3)
121
+ - GitHub Pages works through the `remote_theme` workflow (list the plugin in `plugins:`)
115
122
 
116
123
  ## Contributing
117
124
 
@@ -0,0 +1,184 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cgi"
4
+ require "uri"
5
+
6
+ module Jekyll
7
+ module LlmsTxt
8
+ # Turns Liquid-resolved page source (Markdown, HTML, or a mix of both)
9
+ # into clean Markdown-ish plain text for llms-full.txt.
10
+ #
11
+ # Fenced code blocks and inline code are kept verbatim. Block-level HTML is
12
+ # mapped back to Markdown (headings, paragraphs, lists, links, <pre> blocks),
13
+ # any other tag is dropped, and entities are decoded. No dependencies beyond
14
+ # the Ruby standard library.
15
+ module Text
16
+ BLOCK = "\u0002"
17
+ INLINE = "\u0003"
18
+ TAG = %r{</?[a-zA-Z][a-zA-Z0-9:-]*(?:\s[^<>]*)?/?>}.freeze
19
+ ENTITIES = {
20
+ "&nbsp;" => " ", "&ndash;" => "–", "&mdash;" => "—",
21
+ "&hellip;" => "…", "&lsquo;" => "‘", "&rsquo;" => "’",
22
+ "&ldquo;" => "“", "&rdquo;" => "”", "&copy;" => "©",
23
+ "&apos;" => "'"
24
+ }.freeze
25
+
26
+ class << self
27
+ # source - String, after Liquid has run.
28
+ # html - true when the source is HTML rather than Markdown.
29
+ # resolver - optional callable that turns a relative href into an
30
+ # absolute URL.
31
+ def to_text(source, html: false, resolver: nil)
32
+ store = []
33
+ text = source.to_s.gsub("\r\n", "\n").delete(BLOCK + INLINE)
34
+
35
+ text = stash_fences(text, store) unless html
36
+ text = stash_pre_blocks(text, store)
37
+ text = text.gsub(/[ \t]*\n[ \t]*/, " ") if html
38
+ text = stash_inline_code(text, store)
39
+ text = convert_html(text)
40
+ text = decode_entities(text)
41
+ text = clean_markdown(text, resolver) unless html
42
+ text = absolutize_links(text, resolver) if resolver
43
+ text = tidy_whitespace(text, html)
44
+ restore(text, store)
45
+ end
46
+
47
+ # Plain one-line text for descriptions: no Markdown or HTML syntax.
48
+ def plain(text)
49
+ t = to_text(text, html: false)
50
+ t = t.gsub(/!\[[^\]]*\]\([^)]*\)/, "")
51
+ .gsub(/\[([^\]]*)\]\([^)]*\)/, '\1')
52
+ .gsub(/^\s{0,3}\[[^\]]+\]:.*$/, "")
53
+ .gsub(/[*_`~]+/, "")
54
+ t.gsub(/\s+/, " ").strip
55
+ end
56
+
57
+ private
58
+
59
+ def stash(store, value, kind = BLOCK)
60
+ store << value
61
+ "#{kind}#{store.length - 1}#{kind}"
62
+ end
63
+
64
+ def stash_fences(text, store)
65
+ out = []
66
+ fence = nil
67
+ buf = []
68
+ text.each_line do |line|
69
+ if fence
70
+ buf << line
71
+ closer = /\A[ \t]{0,3}#{Regexp.escape(fence[0])}{#{fence.length},}[ \t]*\n?\z/
72
+ if closer.match?(line)
73
+ out << stash(store, buf.join.chomp) << "\n"
74
+ fence = nil
75
+ buf = []
76
+ end
77
+ elsif (m = line.match(/\A[ \t]{0,3}(`{3,}|~{3,})/))
78
+ fence = m[1]
79
+ buf = [line]
80
+ else
81
+ out << line
82
+ end
83
+ end
84
+ out << stash(store, buf.join.chomp) unless buf.empty?
85
+ out.join
86
+ end
87
+
88
+ def stash_pre_blocks(text, store)
89
+ text.gsub(%r{<pre\b([^>]*)>(.*?)</pre>}mi) do
90
+ attrs = Regexp.last_match(1)
91
+ inner = Regexp.last_match(2)
92
+ lang = code_language(attrs) || code_language(inner[/<code\b([^>]*)>/i, 1].to_s)
93
+ code = CGI.unescapeHTML(inner.gsub(TAG, "")).gsub(/\A\n+|\s+\z/, "")
94
+ stash(store, "```#{lang}\n#{code}\n```")
95
+ end
96
+ end
97
+
98
+ def code_language(attrs)
99
+ attrs[/language-([\w+#.-]+)/, 1] || attrs[/data-lang\s*=\s*["']([\w+#.-]+)["']/, 1]
100
+ end
101
+
102
+ def stash_inline_code(text, store)
103
+ text.gsub(/(?<!`)(`+)(?!`)([^\n]+?)(?<!`)\1(?!`)/) do
104
+ stash(store, Regexp.last_match(0), INLINE)
105
+ end
106
+ end
107
+
108
+ def convert_html(text)
109
+ return text unless text.include?("<")
110
+
111
+ t = text.gsub(/<!--.*?-->/m, "")
112
+ .gsub(%r{<(script|style|noscript)\b.*?</\1>}mi, "")
113
+ t = t.gsub(%r{<a\b([^>]*)>(.*?)</a>}mi) { link_from_tag(Regexp.last_match(1), Regexp.last_match(2)) }
114
+ t = t.gsub(/<img\b[^>]*>/i) { image_from_tag(Regexp.last_match(0)) }
115
+ t = t.gsub(%r{<h([1-6])\b[^>]*>(.*?)</h\1>}mi) do
116
+ "\n\n#{'#' * Regexp.last_match(1).to_i} #{inline(Regexp.last_match(2))}\n\n"
117
+ end
118
+ t = t.gsub(/<li\b[^>]*>/i, "\n- ")
119
+ .gsub(%r{</li>}i, "")
120
+ .gsub(/<br\s*\/?>/i, "\n")
121
+ .gsub(%r{</t[dh]>}i, " | ")
122
+ .gsub(%r{</?(?:p|div|section|article|aside|main|header|footer|nav|ul|ol|dl|dt|dd|blockquote|table|thead|tbody|tr|figure|figcaption|details|summary|hr)\b[^>]*>}i, "\n\n")
123
+ t = t.gsub(%r{<(https?://[^>\s]+)>}, '[\1](\1)')
124
+ t.gsub(TAG, "")
125
+ end
126
+
127
+ def link_from_tag(attrs, inner)
128
+ href = attr(attrs, "href")
129
+ label = inline(inner)
130
+ return label if href.nil? || href.empty?
131
+ return "" if label.empty?
132
+
133
+ "[#{label}](#{href})"
134
+ end
135
+
136
+ def image_from_tag(tag)
137
+ src = attr(tag, "src")
138
+ return "" if src.nil? || src.empty?
139
+
140
+ "![#{attr(tag, 'alt')}](#{src})"
141
+ end
142
+
143
+ def attr(attrs, name)
144
+ attrs[/\b#{name}\s*=\s*(?:"([^"]*)"|'([^']*)')/i, 1] ||
145
+ attrs[/\b#{name}\s*=\s*(?:"([^"]*)"|'([^']*)')/i, 2]
146
+ end
147
+
148
+ def inline(html)
149
+ html.gsub(TAG, "").gsub(/\s+/, " ").strip
150
+ end
151
+
152
+ def decode_entities(text)
153
+ t = text.gsub(/&[a-z]+;/i) { |e| ENTITIES.fetch(e.downcase, e) }
154
+ CGI.unescapeHTML(t)
155
+ end
156
+
157
+ def clean_markdown(text, _resolver)
158
+ text.gsub(/^[ \t]*\{:[^}\n]*\}[ \t]*\n?/, "")
159
+ .gsub(/\{:[^}\n]*\}/, "")
160
+ end
161
+
162
+ def absolutize_links(text, resolver)
163
+ t = text.gsub(/(!?\[[^\]\n]*\])\(\s*<?([^)\s>]+)>?((?:\s+"[^"]*")?)\s*\)/) do
164
+ "#{Regexp.last_match(1)}(#{resolver.call(Regexp.last_match(2))}#{Regexp.last_match(3)})"
165
+ end
166
+ t.gsub(/^([ \t]{0,3}\[[^\]\n]+\]:[ \t]*)(\S+)/) do
167
+ "#{Regexp.last_match(1)}#{resolver.call(Regexp.last_match(2))}"
168
+ end
169
+ end
170
+
171
+ def tidy_whitespace(text, html)
172
+ lines = text.split("\n", -1).map { |l| html ? l.gsub(/[ \t]+/, " ").strip : l.rstrip }
173
+ lines.join("\n").gsub(/\n{3,}/, "\n\n")
174
+ end
175
+
176
+ def restore(text, store)
177
+ t = text.gsub(/\n*#{BLOCK}(\d+)#{BLOCK}\n*/) { "\n\n#{store[Regexp.last_match(1).to_i]}\n\n" }
178
+ t = t.gsub(/#{INLINE}(\d+)#{INLINE}/) { store[Regexp.last_match(1).to_i] }
179
+ t.strip
180
+ end
181
+ end
182
+ end
183
+ end
184
+ end
@@ -1,36 +1,169 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "jekyll"
4
+ require "jekyll/llms_txt/text"
4
5
 
5
6
  module Jekyll
7
+ # Per-build state shared between the generator and the render/write hooks.
8
+ module LlmsTxt
9
+ @states = {}.compare_by_identity
10
+
11
+ class << self
12
+ # The site's llms_txt settings, or nil when the plugin is off.
13
+ # The plugin is opt-in: with no `llms_txt` key nothing is emitted.
14
+ def config_for(site)
15
+ raw = site.config["llms_txt"]
16
+ return nil if raw.nil? || raw == false
17
+
18
+ cfg = raw == true ? {} : raw
19
+ return nil unless cfg.is_a?(Hash)
20
+ return nil if cfg["enabled"] == false
21
+
22
+ cfg
23
+ end
24
+
25
+ def state_for(site)
26
+ @states[site]
27
+ end
28
+
29
+ def set_state(site, state)
30
+ @states[site] = state
31
+ end
32
+
33
+ def clear_state(site)
34
+ @states.delete(site)
35
+ end
36
+
37
+ # Stack of items being rendered, innermost last. Documents push in
38
+ # :pre_render and pop in :post_convert, so a nested render of another
39
+ # document cannot overwrite the outer one's capture.
40
+ def capture_stack
41
+ @capture_stack ||= []
42
+ end
43
+
44
+ # Called by the pass-through converter with Jekyll's own Liquid-resolved
45
+ # source. Keeps the last value seen for the innermost item; the item's
46
+ # own convert call is always the last one before its :post_convert.
47
+ def record(content)
48
+ frame = capture_stack.last
49
+ frame[:content] = content if frame && frame[:wanted]
50
+ end
51
+
52
+ def warn(message)
53
+ Jekyll.logger.warn("LlmsTxt:", message)
54
+ end
55
+ end
56
+ end
57
+
6
58
  class LlmsTxtGenerator < Generator
7
59
  safe true
8
60
  priority :low
9
61
 
10
62
  def generate(site)
11
63
  @site = site
12
- @config = site.config["llms_txt"] || {}
13
- return unless @config["enabled"] != false
64
+ @config = LlmsTxt.config_for(site)
65
+ if @config.nil?
66
+ LlmsTxt.clear_state(site)
67
+ return
68
+ end
69
+
70
+ LlmsTxt.capture_stack.clear
71
+ resolved = resolve_sections
72
+ state = {
73
+ generator: self,
74
+ resolved: resolved,
75
+ llms_txt: build_llms_txt(resolved),
76
+ full: @config["full"] ? true : false,
77
+ bodies: {}.compare_by_identity,
78
+ wanted: {}.compare_by_identity
79
+ }
80
+ if state[:full]
81
+ resolved.each { |_, items| items.each { |item| state[:wanted][item[:source]] = true if item[:source] } }
82
+ end
83
+ LlmsTxt.set_state(site, state)
84
+ end
14
85
 
15
- # Store content on site object so the post_write hook can access it
16
- site.data["__llms_txt_content"] = build_llms_txt
86
+ # Builds llms-full.txt from the bodies the pre_render hook collected.
87
+ def build_llms_full_txt(resolved, bodies)
88
+ lines = header_lines
17
89
 
18
- if @config["full"]
19
- site.data["__llms_full_txt_content"] = build_llms_full_txt
90
+ resolved.each do |section, items|
91
+ next if items.empty?
92
+
93
+ lines << ""
94
+ lines << "## #{section["title"]}"
95
+ lines << ""
96
+ items.each do |item|
97
+ lines << format_item_full(item, bodies[item[:source]])
98
+ end
20
99
  end
21
100
 
22
- inject_link_tag(site) if @config["link_tag"] != false
101
+ lines.join("\n") + "\n"
102
+ end
103
+
104
+ # Cleans the Liquid-resolved source Jekyll's own render handed to the
105
+ # pass-through converter into Markdown-ish text. No Liquid is evaluated
106
+ # here. Returns nil (after a warning) when nothing was captured.
107
+ def clean_body(item, source)
108
+ if source.nil?
109
+ LlmsTxt.warn("no rendered content captured for #{item_label(item)}; its body is left out of llms-full.txt")
110
+ return nil
111
+ end
112
+
113
+ page_url = item.url
114
+ LlmsTxt::Text.to_text(
115
+ source,
116
+ html: !markdown?(item),
117
+ resolver: ->(href) { absolutize(href, page_url) }
118
+ )
119
+ rescue StandardError => e
120
+ LlmsTxt.warn("skipped the body of #{item_label(item)} in llms-full.txt: #{e.class}: #{e.message.lines.first.to_s.strip}")
121
+ nil
23
122
  end
24
123
 
25
124
  private
26
125
 
126
+ def site_origin
127
+ @site.config["url"].to_s.chomp("/")
128
+ end
129
+
130
+ def site_baseurl
131
+ base = @site.config["baseurl"].to_s.chomp("/")
132
+ base.empty? || base.start_with?("/") ? base : "/#{base}"
133
+ end
134
+
27
135
  def site_base_url
28
136
  url = @site.config["url"].to_s.chomp("/")
29
137
  baseurl = @site.config["baseurl"].to_s.chomp("/")
30
138
  "#{url}#{baseurl}"
31
139
  end
32
140
 
33
- def build_llms_txt
141
+ def absolutize(href, page_url)
142
+ return href if href.empty? || href.start_with?("#", "//") || href.match?(/\A[a-z][a-z0-9+.\-]*:/i)
143
+
144
+ if href.start_with?("/")
145
+ base = site_baseurl
146
+ path = base.empty? || href == base || href.start_with?("#{base}/") ? href : "#{base}#{href}"
147
+ "#{site_origin}#{path}"
148
+ else
149
+ URI.join("#{site_origin}#{site_baseurl}#{page_url}", href).to_s
150
+ end
151
+ rescue URI::Error
152
+ href
153
+ end
154
+
155
+ def markdown?(item)
156
+ conv = item.site.find_converter_instance(Jekyll::Converters::Markdown)
157
+ conv.matches(item.extname)
158
+ rescue StandardError
159
+ item.extname.to_s.match?(/\A\.(md|markdown|mkd|mkdn)\z/i)
160
+ end
161
+
162
+ def item_label(item)
163
+ item.respond_to?(:relative_path) ? item.relative_path : item.url
164
+ end
165
+
166
+ def header_lines
34
167
  lines = []
35
168
 
36
169
  title = @config["title"] || @site.config["title"] || "Site"
@@ -45,51 +178,29 @@ module Jekyll
45
178
  lines << intro.strip
46
179
  end
47
180
 
48
- # Link to full version if enabled — lets crawlers discover llms-full.txt
49
- if @config["full"]
50
- lines << ""
51
- lines << "[Full content version](#{site_base_url}/llms-full.txt)"
52
- end
53
-
54
- sections = @config["sections"] || []
55
- sections.each do |section|
56
- items = collect_section_items(section)
57
- next if items.empty?
58
-
59
- lines << ""
60
- lines << "## #{section["title"]}"
61
- items.each do |item|
62
- lines << format_item(item)
63
- end
64
- end
65
-
66
- lines.join("\n") + "\n"
181
+ lines
67
182
  end
68
183
 
69
- def build_llms_full_txt
70
- lines = []
71
-
72
- title = @config["title"] || @site.config["title"] || "Site"
73
- lines << "# #{title}"
184
+ def resolve_sections
185
+ (@config["sections"] || []).map { |section| [section, collect_section_items(section)] }
186
+ end
74
187
 
75
- tagline = @config["tagline"] || @site.config["description"]
76
- lines << "\n> #{tagline}" if tagline && !tagline.empty?
188
+ def build_llms_txt(resolved = resolve_sections)
189
+ lines = header_lines
77
190
 
78
- intro = @config["intro"]
79
- if intro && !intro.empty?
191
+ # Link to full version if enabled, so crawlers can discover llms-full.txt
192
+ if @config["full"]
80
193
  lines << ""
81
- lines << intro.strip
194
+ lines << "[Full content version](#{site_base_url}/llms-full.txt)"
82
195
  end
83
196
 
84
- sections = @config["sections"] || []
85
- sections.each do |section|
86
- items = collect_section_items(section)
197
+ resolved.each do |section, items|
87
198
  next if items.empty?
88
199
 
89
200
  lines << ""
90
201
  lines << "## #{section["title"]}"
91
202
  items.each do |item|
92
- lines << format_item_full(item)
203
+ lines << format_item(item)
93
204
  end
94
205
  end
95
206
 
@@ -119,7 +230,7 @@ module Jekyll
119
230
  []
120
231
  end
121
232
 
122
- docs = docs.reject { |d| d.data["llms_txt"] == false }
233
+ docs = docs.reject { |d| excluded?(d) }
123
234
  docs = docs.sort_by { |d| d.data["date"] || Time.now }.reverse
124
235
  docs = docs.first(limit) if limit
125
236
 
@@ -127,109 +238,219 @@ module Jekyll
127
238
  end
128
239
 
129
240
  def items_from_pages(page_urls)
130
- page_urls.filter_map do |url|
131
- page = @site.pages.find { |p| p.url == url || p.url == "#{url}index.html" }
132
- next if page.nil?
133
- next if page.data["llms_txt"] == false
241
+ candidates = @site.pages.to_a
242
+ candidates += @site.documents.to_a if @site.respond_to?(:documents)
243
+
244
+ Array(page_urls).filter_map do |url|
245
+ wanted = normalize_url(url)
246
+ found = candidates.find { |c| normalize_url(c.url) == wanted && !excluded?(c) }
247
+ if found.nil?
248
+ LlmsTxt.warn("no page or document found for #{url} (or it is excluded)")
249
+ next
250
+ end
134
251
 
135
- {
136
- title: page.data["title"] || page.url,
137
- url: "#{site_base_url}#{page.url}",
138
- description: page.data["description"] || page.data["excerpt"],
139
- content: page.content
140
- }
252
+ doc_to_item(found)
141
253
  end
142
254
  end
143
255
 
144
- def doc_to_item(doc)
145
- raw_desc = doc.data["description"] ||
146
- doc.data["tagline"] ||
147
- (doc.data["excerpt"]&.output ? strip_html(doc.data["excerpt"].output) : nil) ||
148
- (doc.excerpt ? strip_html(doc.excerpt.output) : nil)
149
-
150
- description = if raw_desc
151
- cleaned = raw_desc.strip.gsub(/\s+/, " ")
152
- # Use first sentence rather than a hard char truncation
153
- first_sentence = cleaned.match(/\A.+?[.!?](?:\s|$)/)
154
- first_sentence ? first_sentence[0].strip : cleaned
155
- end
256
+ # Treats /about, /about/ and /about/index.html as the same URL.
257
+ def normalize_url(url)
258
+ path = url.to_s.sub(/[?#].*\z/, "")
259
+ path = "/#{path.sub(%r{\A/+}, "")}"
260
+ path = path.sub(%r{/index\.html?\z}i, "/")
261
+ path == "/" ? path : path.chomp("/")
262
+ end
263
+
264
+ def excluded?(doc)
265
+ data = doc.data
266
+ return true if data["llms_txt"] == false
267
+ return true if data["sitemap"] == false
268
+
269
+ robots = data["robots"]
270
+ robots = robots.join(",") if robots.is_a?(Array)
271
+ return true if robots.to_s.match?(/noindex/i)
156
272
 
273
+ # Collections with `output: false` have no pages, so the URLs would 404.
274
+ if doc.respond_to?(:collection) && doc.collection && !doc.collection.write?
275
+ return true
276
+ end
277
+
278
+ false
279
+ end
280
+
281
+ def doc_to_item(doc)
157
282
  {
158
- title: doc.data["title"],
283
+ title: title_for(doc),
159
284
  url: "#{site_base_url}#{doc.url}",
160
- description: description,
161
- content: doc.content
285
+ description: description_for(doc),
286
+ content: doc.content,
287
+ source: doc
162
288
  }
163
289
  end
164
290
 
291
+ def title_for(doc)
292
+ title = doc.data["title"].to_s.strip
293
+ title.empty? ? derived_title(doc) : title
294
+ end
295
+
296
+ # Used when a document has no title: slug, file name or URL segment.
297
+ def derived_title(doc)
298
+ slug = doc.data["slug"].to_s
299
+ slug = nil if slug.empty?
300
+ slug ||= begin
301
+ segments = doc.url.to_s.sub(/[?#].*\z/, "").split("/").reject(&:empty?)
302
+ segments.pop while segments.last.to_s.match?(/\Aindex(\.html?)?\z/i)
303
+ segments.last.to_s.sub(/\.[a-z0-9]+\z/i, "")
304
+ end
305
+ return (@config["title"] || @site.config["title"] || "Home").to_s if slug.empty?
306
+
307
+ slug.split(/[-_\s]+/).reject(&:empty?).map { |w| w[0].upcase + w[1..] }.join(" ")
308
+ end
309
+
310
+ def description_for(doc)
311
+ raw = doc.data["description"] || doc.data["tagline"] || excerpt_text(doc)
312
+ return nil unless raw
313
+
314
+ cleaned = raw.to_s.strip.gsub(/\s+/, " ")
315
+ return nil if cleaned.empty?
316
+
317
+ # Use first sentence rather than a hard char truncation
318
+ first_sentence = cleaned.match(/\A.+?[.!?](?:\s|$)/)
319
+ first_sentence ? first_sentence[0].strip : cleaned
320
+ end
321
+
322
+ # Plain text from the excerpt's source. It never renders the excerpt, so a
323
+ # Liquid error in it cannot abort the build; Liquid tags are stripped.
324
+ def excerpt_text(doc)
325
+ excerpt = doc.data["excerpt"]
326
+ excerpt = doc.excerpt if excerpt.nil? && doc.respond_to?(:excerpt)
327
+ return nil if excerpt.nil?
328
+
329
+ source = excerpt.respond_to?(:content) ? excerpt.content : excerpt
330
+ source = source.to_s.gsub(/\{%.*?%\}|\{\{.*?\}\}/m, "")
331
+ paragraph = source.split(/\n\s*\n/).map(&:strip).find do |p|
332
+ !p.empty? && !p.start_with?("#", "{:") && !p.match?(/\A\[[^\]]+\]:/)
333
+ end
334
+ paragraph ? LlmsTxt::Text.plain(paragraph) : nil
335
+ rescue StandardError => e
336
+ LlmsTxt.warn("could not build a description from the excerpt of #{doc.url}: #{e.message.lines.first.to_s.strip}")
337
+ nil
338
+ end
339
+
340
+ def escape_link_text(text)
341
+ text.to_s.gsub(/\s*\n\s*/, " ").gsub(/[\[\]]/) { |m| "\\#{m}" }
342
+ end
343
+
344
+ def escape_url(url)
345
+ url.to_s.gsub(" ", "%20").gsub("(", "%28").gsub(")", "%29")
346
+ end
347
+
165
348
  def format_item(item)
166
- line = "- [#{item[:title]}](#{item[:url]})"
349
+ line = "- [#{escape_link_text(item[:title])}](#{escape_url(item[:url])})"
167
350
  desc = item[:description]
168
351
  line += ": #{desc}" if desc && !desc.empty?
169
352
  line
170
353
  end
171
354
 
172
- def format_item_full(item)
355
+ def format_item_full(item, body = nil)
173
356
  lines = []
174
- lines << "### [#{item[:title]}](#{item[:url]})"
357
+ lines << "### [#{escape_link_text(item[:title])}](#{escape_url(item[:url])})"
175
358
  desc = item[:description]
176
359
  lines << "" << "> #{desc}" if desc && !desc.empty?
177
- if item[:content] && !item[:content].empty?
178
- stripped = strip_html(item[:content]).strip.gsub(/\s+/, " ")
179
- lines << "" << stripped
180
- end
360
+ lines << "" << body if body && !body.empty?
181
361
  lines << "" << "---"
182
362
  lines.join("\n")
183
363
  end
364
+ end
184
365
 
185
- def strip_html(html)
186
- return "" unless html
366
+ # Pass-through converter. Jekyll runs every matching converter, in priority
367
+ # order, on the content after Liquid and before layouts. This one runs first,
368
+ # records what it is given for the item being rendered, and returns it
369
+ # unchanged, so llms-full.txt reuses Jekyll's single Liquid render. It
370
+ # returns nil from #output_ext, which Jekyll drops, so no page's output
371
+ # extension or permalink changes. It only matches Markdown and HTML sources.
372
+ module Converters
373
+ class LlmsTxtCapture < Converter
374
+ safe true
375
+ priority :highest
376
+
377
+ def matches(ext)
378
+ e = ext.to_s.downcase
379
+ return true if [".html", ".htm"].include?(e)
380
+
381
+ @markdown_exts ||= @config["markdown_ext"].to_s.split(",").map { |x| ".#{x.strip.downcase}" }
382
+ @markdown_exts.include?(e)
383
+ end
187
384
 
188
- html.gsub(/<script[^>]*>.*?<\/script>/mi, "")
189
- .gsub(/<style[^>]*>.*?<\/style>/mi, "")
190
- .gsub(/<[^>]+>/, " ")
191
- .gsub(/&nbsp;/, " ")
192
- .gsub(/&amp;/, "&")
193
- .gsub(/&lt;/, "<")
194
- .gsub(/&gt;/, ">")
195
- .gsub(/&quot;/, '"')
196
- .gsub(/&#39;/, "'")
197
- .gsub(/\s+/, " ")
198
- .strip
199
- end
385
+ def output_ext(_ext)
386
+ nil
387
+ end
200
388
 
201
- def write_file(filename, content)
202
- dest = @site.in_dest_dir(filename)
203
- FileUtils.mkdir_p(File.dirname(dest))
204
- File.write(dest, content)
389
+ def convert(content)
390
+ LlmsTxt.record(content)
391
+ content
392
+ end
205
393
  end
394
+ end
206
395
 
207
- def inject_link_tag(site)
208
- llms_url = "#{site_base_url}/llms.txt"
209
- site.pages.each do |page|
210
- next unless page.output_ext == ".html"
396
+ Hooks.register [:pages, :documents], :pre_render do |item, _payload|
397
+ state = LlmsTxt.state_for(item.site)
398
+ next unless state
211
399
 
212
- page.content = page.content.to_s.sub(
213
- %r{</head>}i,
214
- %(<link rel="ai" href="#{llms_url}" />\n</head>)
215
- )
216
- end
217
- end
400
+ # A document in a collection named "pages" fires the hook twice (as :pages
401
+ # and as :documents), so don't push the same item twice in a row.
402
+ next if LlmsTxt.capture_stack.last && LlmsTxt.capture_stack.last[:item].equal?(item)
403
+
404
+ LlmsTxt.capture_stack.push(item: item, wanted: state[:wanted][item] ? true : false, content: nil)
218
405
  end
219
- end
220
406
 
221
- Jekyll::Hooks.register :site, :post_write do |site|
222
- content = site.data.delete("__llms_txt_content")
223
- if content
224
- dest = site.in_dest_dir("llms.txt")
225
- FileUtils.mkdir_p(File.dirname(dest))
226
- File.write(dest, content)
407
+ Hooks.register [:pages, :documents], :post_convert do |item|
408
+ state = LlmsTxt.state_for(item.site)
409
+ next unless state
410
+
411
+ stack = LlmsTxt.capture_stack
412
+ idx = stack.rindex { |f| f[:item].equal?(item) }
413
+ next if idx.nil?
414
+
415
+ frame = stack[idx]
416
+ stack.slice!(idx..-1)
417
+ next unless frame[:wanted]
418
+
419
+ body = state[:generator].clean_body(item, frame[:content])
420
+ state[:bodies][item] = body if body
227
421
  end
228
422
 
229
- full_content = site.data.delete("__llms_full_txt_content")
230
- if full_content
231
- dest = site.in_dest_dir("llms-full.txt")
232
- FileUtils.mkdir_p(File.dirname(dest))
233
- File.write(dest, full_content)
423
+ # Point crawlers at llms.txt from every rendered HTML page, as the llmstxt.org
424
+ # spec recommends: <link rel="describedby" href="/llms.txt">.
425
+ Hooks.register [:pages, :documents], :post_render do |item|
426
+ cfg = LlmsTxt.config_for(item.site)
427
+ next if cfg.nil? || cfg["link_tag"] == false
428
+ next unless item.output_ext == ".html"
429
+
430
+ output = item.output.to_s
431
+ next unless output.match?(%r{</head>}i)
432
+ next if output.match?(/rel=["']describedby["'][^>]*llms\.txt/i)
433
+
434
+ base = item.site.config["baseurl"].to_s.chomp("/")
435
+ base = "/#{base}" unless base.empty? || base.start_with?("/")
436
+ tag = %(<link rel="describedby" href="#{base}/llms.txt" />)
437
+ item.output = output.sub(%r{</head>}i) { "#{tag}\n</head>" }
438
+ end
439
+
440
+ Hooks.register :site, :post_write do |site|
441
+ state = LlmsTxt.state_for(site)
442
+ LlmsTxt.clear_state(site)
443
+ next unless state
444
+
445
+ files = { "llms.txt" => state[:llms_txt] }
446
+ if state[:full]
447
+ files["llms-full.txt"] = state[:generator].build_llms_full_txt(state[:resolved], state[:bodies])
448
+ end
449
+
450
+ files.each do |name, content|
451
+ dest = site.in_dest_dir(name)
452
+ FileUtils.mkdir_p(File.dirname(dest))
453
+ File.write(dest, content)
454
+ end
234
455
  end
235
456
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module JekyllLlmsGenerator
4
- VERSION = "0.3.1"
4
+ VERSION = "0.4.0"
5
5
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jekyll-llms-generator
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.1
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jason Chance
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-08-21 00:00:00.000000000 Z
10
+ date: 2026-11-29 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: jekyll
@@ -15,7 +15,7 @@ dependencies:
15
15
  requirements:
16
16
  - - ">="
17
17
  - !ruby/object:Gem::Version
18
- version: '3.7'
18
+ version: '4.2'
19
19
  - - "<"
20
20
  - !ruby/object:Gem::Version
21
21
  version: '5.0'
@@ -25,7 +25,7 @@ dependencies:
25
25
  requirements:
26
26
  - - ">="
27
27
  - !ruby/object:Gem::Version
28
- version: '3.7'
28
+ version: '4.2'
29
29
  - - "<"
30
30
  - !ruby/object:Gem::Version
31
31
  version: '5.0'
@@ -43,6 +43,7 @@ files:
43
43
  - README.md
44
44
  - lib/jekyll-llms-generator.rb
45
45
  - lib/jekyll-llms-generator/version.rb
46
+ - lib/jekyll/llms_txt/text.rb
46
47
  - lib/jekyll/llms_txt_generator.rb
47
48
  homepage: https://github.com/jchance/jekyll-llms-generator
48
49
  licenses:
@@ -58,7 +59,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
58
59
  requirements:
59
60
  - - ">="
60
61
  - !ruby/object:Gem::Version
61
- version: 2.7.0
62
+ version: '3.0'
62
63
  required_rubygems_version: !ruby/object:Gem::Requirement
63
64
  requirements:
64
65
  - - ">="