jekyll-webmentions-static 0.1.1 → 0.2.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: 6bdd84c741b25702134b381a11ff8b6e5388a8a949f4531e562bedf6d3032872
4
- data.tar.gz: ed687e8bd29cdc3bb11e56f07cdaf11213bfe23266b7b1d657ac6225fd39c2b1
3
+ metadata.gz: 0066c6420ad7e457519675d6f41c57ed5a7a9bdabe4a1b7cba1de3f67049acc1
4
+ data.tar.gz: 1af939392962c441eb56534eed0b5a4a0498e57f41845a23c79bc85eca23c7db
5
5
  SHA512:
6
- metadata.gz: f0fe721abe9b8af701b4b11569c85e72c8f8a47cd8fd15ff678db13381e666afd0d622af9851bf3ea1150b5f16b3742a33fc1fdd733f107d627a8d84737f3cfc
7
- data.tar.gz: 84108908d211adfd0d69c3a04ed5c0855a52959ce548fe82f10327fe8cef3a1d57c63d948ede793bd9fe8a95a67dff9f445060675d79035cfae712a5ac4a8e49
6
+ metadata.gz: 9be1d37e0c04b8d8816a861b1307839a911ec1fa4b2060d7d3a976683bb6cadeab021977816b2ede55051452d060db4d5a5e00009d52290be0f07b2e22ce643a
7
+ data.tar.gz: ebc5928740ca4aae03fd90cec5cf06aa98ecb0975ea7b613012f2cbbca84977e2e651afb8bc135c3a01226b637308200b9ae9c8105718fe84411348c04c4f0e8
data/README.md CHANGED
@@ -11,11 +11,13 @@ Fetch and render [Webmention.io](https://webmention.io) mentions as static HTML
11
11
 
12
12
  During `jekyll build`, the plugin:
13
13
 
14
- 1. Fetches all webmentions for your domain from the Webmention.io API.
14
+ 1. Fetches all webmentions for your domain from the Webmention.io API, 100 at a time, paging until it has them all.
15
15
  2. Groups them by target URL and stores them in `site.data["webmentions"]`.
16
- 3. Injects matching mentions into each post's `page.webmentions` array.
16
+ 3. Matches each mention to a page (ignoring `http` vs `https`, `www.`, trailing slashes and `baseurl`) and sets `page.webmentions` on every post, collection document and page that has output.
17
17
  4. Caches the API response locally so repeated builds don't hammer the API.
18
18
 
19
+ If Webmention.io is down or slow, the build carries on. The plugin falls back to the last cache file, even a stale one, and logs that it did.
20
+
19
21
  ---
20
22
 
21
23
  ## Installation
@@ -62,7 +64,9 @@ webmentions:
62
64
  export WEBMENTION_TOKEN=your-token-here
63
65
  ```
64
66
 
65
- The environment variable always takes precedence over the config file value. This keeps secrets out of version control.
67
+ The environment variable always takes precedence over the config file value. This keeps secrets out of version control. If the token comes from `_config.yml`, the plugin logs a warning (once per build).
68
+
69
+ The token is sent in an `Authorization: Bearer` header and is never written to the build log or the cache file.
66
70
 
67
71
  ### Add the `rel="webmention"` link to your `<head>`
68
72
 
@@ -85,7 +89,9 @@ Place `{% webmentions %}` anywhere in a post or page layout to render a minimal,
85
89
  {% webmentions %}
86
90
  ```
87
91
 
88
- This renders likes, reposts, and bookmarks as counts, and replies as individual cards with author name, avatar, and content.
92
+ This renders likes, reposts, and bookmarks as counts, replies as individual cards with author name, avatar, and content, and plain `mention-of` links as a short list of the pages that mention yours (the first 20, then "and N more"). If a page has nothing to show, the tag renders nothing at all.
93
+
94
+ Every link and image URL must be `http` or `https`. Anything else (`javascript:`, `data:` and so on) is dropped, and the author's name is shown as plain text. Outbound links get `rel="nofollow ugc noopener"`.
89
95
 
90
96
  ### Option 2 — Manual template with `page.webmentions`
91
97
 
@@ -94,11 +100,11 @@ For full control over markup, iterate over `page.webmentions` directly:
94
100
  ```liquid
95
101
  {% if page.webmentions %}
96
102
  <section class="webmentions">
97
- {% assign likes = page.webmentions | where: "type", "like-of" %}
98
- {% assign replies = page.webmentions | where: "type", "in-reply-to" %}
103
+ {% assign likes = page.webmentions | where: "wm-property", "like-of" %}
104
+ {% assign replies = page.webmentions | where: "wm-property", "in-reply-to" %}
99
105
 
100
106
  {% if likes.size > 0 %}
101
- <p>{{ likes.size }} like{{ likes.size | plural: "", "s" }}</p>
107
+ <p>{{ likes.size }} like{% if likes.size != 1 %}s{% endif %}</p>
102
108
  {% endif %}
103
109
 
104
110
  {% for mention in replies %}
@@ -122,11 +128,15 @@ The full hash is available at `site.data.webmentions`:
122
128
  {% assign mentions = site.data.webmentions[page.url | prepend: site.url] %}
123
129
  ```
124
130
 
131
+ The keys are the target URLs exactly as Webmention.io reports them, so this lookup only works when they match your page URL character for character. `page.webmentions` is more forgiving, because the plugin normalizes both sides before matching.
132
+
125
133
  ---
126
134
 
127
135
  ## Caching
128
136
 
129
- The plugin writes fetched data to `_webmentions_cache.json` in your site source directory. Subsequent builds within the TTL window (default: 1 hour) read from this file instead of calling the API.
137
+ The plugin writes fetched data to `_webmentions_cache.json` in your site source directory, along with the domain it was fetched for. Subsequent builds within the TTL window (default: 1 hour) read from this file instead of calling the API. If you change `url` in `_config.yml`, the old cache is ignored.
138
+
139
+ If a fetch fails (network error, timeout, HTTP error or a bad response), the plugin uses the cache even when it's older than the TTL. Requests time out after 10 seconds. Cache files written by 0.1.x are in an older format and are refetched once.
130
140
 
131
141
  **Add the cache file to your `.gitignore`:**
132
142
 
@@ -169,13 +179,16 @@ Adjust the cron interval to taste — daily (`0 0 * * *`) is reasonable for most
169
179
 
170
180
  ## Webmention types
171
181
 
172
- | `type` | Meaning |
182
+ Webmention.io gives every entry `type: "entry"`. The kind of mention is in `wm-property`:
183
+
184
+ | `wm-property` | Meaning |
173
185
  |-----------------|----------------------------------|
174
186
  | `like-of` | Someone liked your post |
175
187
  | `repost-of` | Someone reposted / boosted it |
176
188
  | `in-reply-to` | A reply with content |
177
189
  | `bookmark-of` | Someone bookmarked it |
178
190
  | `mention-of` | A generic link mention |
191
+ | `rsvp` | An RSVP (available in `page.webmentions`, not rendered by the tag) |
179
192
 
180
193
  ---
181
194
 
@@ -193,6 +206,12 @@ The `{% webmentions %}` tag outputs unstyled semantic HTML. All elements use BEM
193
206
  .webmentions__reposts { }
194
207
  .webmentions__bookmarks { }
195
208
 
209
+ /* Plain "mentioned on" link list */
210
+ .webmentions__mentions { }
211
+ .webmentions__mentions-heading { }
212
+ .webmentions__mentions-list { }
213
+ .webmentions__mentions-more { }
214
+
196
215
  /* Replies section */
197
216
  .webmentions__replies { }
198
217
  .webmentions__replies-heading { }
@@ -201,7 +220,7 @@ The `{% webmentions %}` tag outputs unstyled semantic HTML. All elements use BEM
201
220
  .webmention__reply { }
202
221
  .webmention__author { }
203
222
  .webmention__avatar { } /* circular avatar img */
204
- .webmention__author-name { } /* linked name */
223
+ .webmention__author-name { } /* name, linked when the URL is safe */
205
224
  .webmention__date { }
206
225
  .webmention__content { }
207
226
  ```
@@ -212,7 +231,7 @@ The count pills include a `title` attribute (e.g. `title="2 likes"`) for native
212
231
 
213
232
  ## Requirements
214
233
 
215
- - Ruby >= 2.7
234
+ - Ruby >= 3.0
216
235
  - Jekyll >= 4.0
217
236
  - No additional gems required — uses Ruby's built-in `net/http`
218
237
 
@@ -1,27 +1,49 @@
1
1
  require "jekyll"
2
2
  require_relative "../jekyll-webmentions-static/fetcher"
3
+ require_relative "../jekyll-webmentions-static/url_helpers"
3
4
 
4
5
  module Jekyll
6
+ module WebmentionsStatic
7
+ @config_token_warned = false
8
+
9
+ class << self
10
+ def warn_config_token_once
11
+ return if @config_token_warned
12
+
13
+ @config_token_warned = true
14
+ Jekyll.logger.warn "Webmentions:", "Using the token from _config.yml. Set the WEBMENTION_TOKEN " \
15
+ "environment variable instead so the token stays out of version control."
16
+ end
17
+
18
+ def reset_token_warning!
19
+ @config_token_warned = false
20
+ end
21
+ end
22
+ end
23
+
5
24
  class WebmentionsGenerator < Jekyll::Generator
6
25
  safe true
7
26
  priority :low
8
27
 
9
28
  def generate(site)
10
- token = resolve_token(site)
29
+ token, from_env = resolve_token(site)
11
30
 
12
- if token.nil? || token.strip.empty?
31
+ if token.nil? || token.empty?
13
32
  Jekyll.logger.info "Webmentions:", "No token configured — skipping"
14
33
  return
15
34
  end
16
35
 
17
- domain = extract_domain(site.config["url"])
36
+ Jekyll::WebmentionsStatic.warn_config_token_once unless from_env
37
+
38
+ domain = Jekyll::WebmentionsStatic::UrlHelpers.host_of(site.config["url"])
18
39
 
19
- if domain.nil? || domain.empty?
40
+ if domain.nil?
20
41
  Jekyll.logger.warn "Webmentions:", "site.url not set — skipping"
21
42
  return
22
43
  end
23
44
 
24
- cfg = site.config.fetch("webmentions", {})
45
+ cfg = site.config["webmentions"]
46
+ cfg = {} unless cfg.is_a?(Hash)
25
47
  cache = cfg.fetch("cache", true)
26
48
  cache_ttl = cfg.fetch("cache_ttl", Jekyll::WebmentionsStatic::Fetcher::DEFAULT_TTL)
27
49
 
@@ -37,7 +59,7 @@ module Jekyll
37
59
 
38
60
  site.data["webmentions"] = grouped
39
61
 
40
- inject_into_posts(site, grouped)
62
+ inject_mentions(site, grouped)
41
63
 
42
64
  total = grouped.values.sum(&:length)
43
65
  Jekyll.logger.info "Webmentions:", "Loaded #{total} mention(s) across #{grouped.keys.length} URL(s)"
@@ -45,29 +67,41 @@ module Jekyll
45
67
 
46
68
  private
47
69
 
70
+ # Returns [token, from_env].
48
71
  def resolve_token(site)
49
- env_token = ENV["WEBMENTION_TOKEN"]
50
- return env_token unless env_token.nil? || env_token.strip.empty?
72
+ env_token = ENV["WEBMENTION_TOKEN"].to_s.strip
73
+ return [env_token, true] unless env_token.empty?
51
74
 
52
- site.config.dig("webmentions", "token")
75
+ cfg = site.config["webmentions"]
76
+ cfg_token = cfg.is_a?(Hash) ? cfg["token"].to_s.strip : ""
77
+ [cfg_token, false]
53
78
  end
54
79
 
55
- def extract_domain(url)
56
- return nil if url.nil? || url.strip.empty?
57
-
58
- url.strip
59
- .sub(%r{\Ahttps?://}, "")
60
- .sub(%r{/+\z}, "")
80
+ # Adds page.webmentions to every document (posts and other collections)
81
+ # and page that has output and whose URL matches a mention target.
82
+ def inject_mentions(site, grouped)
83
+ helpers = Jekyll::WebmentionsStatic::UrlHelpers
84
+ index = Hash.new { |h, k| h[k] = [] }
85
+ grouped.each { |target, mentions| index[helpers.normalize(target)].concat(mentions) }
86
+
87
+ site_url = site.config["url"].to_s.sub(%r{/+\z}, "")
88
+ baseurl = site.config["baseurl"].to_s.strip.gsub(%r{\A/+|/+\z}, "")
89
+ baseurl = baseurl.empty? ? "" : "/#{baseurl}"
90
+
91
+ targets = Array(site.documents).select { |d| document_written?(d) } + Array(site.pages)
92
+ targets.each do |item|
93
+ path = item.url.to_s
94
+ next if path.empty?
95
+
96
+ # Jekyll's url omits baseurl, but accept either form.
97
+ keys = ["#{site_url}#{baseurl}#{path}", "#{site_url}#{path}"].map { |u| helpers.normalize(u) }.uniq
98
+ mentions = keys.flat_map { |k| index.key?(k) ? index[k] : [] }
99
+ item.data["webmentions"] = mentions unless mentions.empty?
100
+ end
61
101
  end
62
102
 
63
- def inject_into_posts(site, grouped)
64
- base_url = site.config["url"].to_s.sub(%r{/+\z}, "")
65
-
66
- site.posts.docs.each do |post|
67
- full_url = base_url + post.url
68
- mentions = grouped[full_url]
69
- post.data["webmentions"] = mentions if mentions
70
- end
103
+ def document_written?(doc)
104
+ doc.respond_to?(:write?) ? doc.write? : true
71
105
  end
72
106
  end
73
107
  end
@@ -1,4 +1,6 @@
1
1
  require "jekyll"
2
+ require "cgi"
3
+ require_relative "../jekyll-webmentions-static/url_helpers"
2
4
 
3
5
  module Jekyll
4
6
  class WebmentionsTag < Liquid::Tag
@@ -7,16 +9,23 @@ module Jekyll
7
9
  ICON_REPOST = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z"/></svg>'.freeze
8
10
  ICON_BOOKMARK = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M17 3H7c-1.1 0-2 .9-2 2v16l7-3 7 3V5c0-1.1-.9-2-2-2z"/></svg>'.freeze
9
11
 
12
+ MAX_LISTED_MENTIONS = 20
13
+ REL = "nofollow ugc noopener".freeze
14
+
10
15
  def render(context)
11
- page = context["page"]
12
- mentions = page["webmentions"]
16
+ page = context["page"]
17
+ mentions = page && page["webmentions"]
18
+
19
+ return "" unless mentions.respond_to?(:select) && !mentions.empty?
13
20
 
14
- return "" if mentions.nil? || mentions.empty?
21
+ mentions = mentions.select { |m| m.respond_to?(:key?) }
22
+ likes = of_kind(mentions, "like-of")
23
+ reposts = of_kind(mentions, "repost-of")
24
+ replies = of_kind(mentions, "in-reply-to")
25
+ bookmarks = of_kind(mentions, "bookmark-of")
26
+ links = of_kind(mentions, "mention-of")
15
27
 
16
- likes = mentions.select { |m| m["type"] == "like-of" }
17
- reposts = mentions.select { |m| m["type"] == "repost-of" }
18
- replies = mentions.select { |m| m["type"] == "in-reply-to" }
19
- bookmarks = mentions.select { |m| m["type"] == "bookmark-of" }
28
+ return "" if [likes, reposts, replies, bookmarks, links].all?(&:empty?)
20
29
 
21
30
  html = []
22
31
  html << '<section class="webmentions" aria-label="Webmentions">'
@@ -29,33 +38,23 @@ module Jekyll
29
38
  html << " </div>"
30
39
  end
31
40
 
41
+ if links.any?
42
+ html << ' <div class="webmentions__mentions">'
43
+ html << ' <h3 class="webmentions__mentions-heading">Mentioned on</h3>'
44
+ html << " <ul class=\"webmentions__mentions-list\">"
45
+ links.first(MAX_LISTED_MENTIONS).each do |m|
46
+ html << " <li>#{link_to(m["url"], link_label(m))}</li>"
47
+ end
48
+ html << " </ul>"
49
+ extra = links.length - MAX_LISTED_MENTIONS
50
+ html << " <p class=\"webmentions__mentions-more\">and #{extra} more</p>" if extra.positive?
51
+ html << " </div>"
52
+ end
53
+
32
54
  if replies.any?
33
55
  html << ' <div class="webmentions__replies">'
34
56
  html << " <h3 class=\"webmentions__replies-heading\">Replies</h3>"
35
- replies.each do |reply|
36
- author = reply["author"] || {}
37
- name = CGI.escapeHTML(author["name"].to_s.then { |n| n.empty? ? "Anonymous" : n })
38
- photo = author["photo"]
39
- url = CGI.escapeHTML(reply["url"].to_s)
40
- text = reply.dig("content", "text").to_s
41
- content = CGI.escapeHTML(text.length > 300 ? "#{text[0, 300]}…" : text)
42
- date = format_date(reply["published"])
43
-
44
- html << ' <article class="webmention__reply">'
45
- html << ' <header class="webmention__author">'
46
- if photo
47
- html << " <img src=\"#{CGI.escapeHTML(photo)}\" alt=\"#{name}\" class=\"webmention__avatar\" width=\"40\" height=\"40\" loading=\"lazy\">"
48
- end
49
- if url.empty?
50
- html << " <span class=\"webmention__author-name\">#{name}</span>"
51
- else
52
- html << " <a href=\"#{url}\" class=\"webmention__author-name\" rel=\"nofollow noopener noreferrer\" target=\"_blank\">#{name}</a>"
53
- end
54
- html << " <time class=\"webmention__date\" datetime=\"#{CGI.escapeHTML(reply["published"].to_s)}\">#{date}</time>" if date
55
- html << " </header>"
56
- html << " <p class=\"webmention__content\">#{content}</p>" unless content.empty?
57
- html << " </article>"
58
- end
57
+ replies.each { |reply| html << render_reply(reply) }
59
58
  html << " </div>"
60
59
  end
61
60
 
@@ -65,10 +64,94 @@ module Jekyll
65
64
 
66
65
  private
67
66
 
67
+ # The kind of mention. webmention.io's jf2 output gives every entry
68
+ # type "entry" and puts the kind in "wm-property"; older data carried it
69
+ # in "type".
70
+ def mention_kind(mention)
71
+ prop = mention["wm-property"].to_s
72
+ return prop unless prop.empty?
73
+
74
+ type = mention["type"].to_s
75
+ type == "entry" ? "" : type
76
+ end
77
+
78
+ def of_kind(mentions, kind)
79
+ mentions.select { |m| mention_kind(m) == kind }
80
+ end
81
+
82
+ def h(value)
83
+ CGI.escapeHTML(value.to_s)
84
+ end
85
+
86
+ def safe_url(value)
87
+ Jekyll::WebmentionsStatic::UrlHelpers.safe_http_url(value)
88
+ end
89
+
90
+ def host_of(value)
91
+ Jekyll::WebmentionsStatic::UrlHelpers.host_of(safe_url(value))
92
+ end
93
+
94
+ def link_to(url, label, css = nil)
95
+ href = safe_url(url)
96
+ return h(label) unless href
97
+
98
+ klass = css ? " class=\"#{css}\"" : ""
99
+ "<a href=\"#{h(href)}\"#{klass} rel=\"#{REL}\" target=\"_blank\">#{h(label)}</a>"
100
+ end
101
+
102
+ def blank_str?(value)
103
+ value.to_s.strip.empty?
104
+ end
105
+
106
+ def author_of(mention)
107
+ mention["author"].is_a?(Hash) ? mention["author"] : {}
108
+ end
109
+
110
+ # Author name, or failing that the host of their site, or of the
111
+ # mentioning page.
112
+ def author_name(mention)
113
+ author = author_of(mention)
114
+ return author["name"].to_s.strip unless blank_str?(author["name"])
115
+
116
+ host_of(author["url"]) || host_of(mention["url"]) || "Anonymous"
117
+ end
118
+
119
+ def link_label(mention)
120
+ return mention["name"].to_s.strip unless blank_str?(mention["name"])
121
+
122
+ host_of(mention["url"]) || author_name(mention)
123
+ end
124
+
125
+ def render_reply(reply)
126
+ author = author_of(reply)
127
+ name = author_name(reply)
128
+ photo = safe_url(author["photo"])
129
+ href = reply["url"] if safe_url(reply["url"])
130
+ href ||= author["url"]
131
+ content = reply["content"].is_a?(Hash) ? reply["content"]["text"].to_s : ""
132
+ content = "#{content[0, 300]}…" if content.length > 300
133
+ date = format_date(reply["published"])
134
+
135
+ html = []
136
+ html << ' <article class="webmention__reply">'
137
+ html << ' <header class="webmention__author">'
138
+ html << " <img src=\"#{h(photo)}\" alt=\"#{h(name)}\" class=\"webmention__avatar\" width=\"40\" height=\"40\" loading=\"lazy\">" if photo
139
+ if safe_url(href)
140
+ html << " #{link_to(href, name, "webmention__author-name")}"
141
+ else
142
+ html << " <span class=\"webmention__author-name\">#{h(name)}</span>"
143
+ end
144
+ html << " <time class=\"webmention__date\" datetime=\"#{h(reply["published"])}\">#{h(date)}</time>" if date
145
+ html << " </header>"
146
+ html << " <p class=\"webmention__content\">#{h(content)}</p>" unless content.strip.empty?
147
+ html << " </article>"
148
+ html.join("\n")
149
+ end
150
+
68
151
  def format_date(iso_str)
69
- return nil if iso_str.nil? || iso_str.strip.empty?
152
+ return nil if iso_str.nil? || iso_str.to_s.strip.empty?
70
153
 
71
- Time.parse(iso_str).strftime("%B %-d, %Y")
154
+ Time.parse(iso_str.to_s).strftime("%B %-d, %Y")
72
155
  rescue ArgumentError
73
156
  nil
74
157
  end
@@ -1,13 +1,20 @@
1
1
  require "net/http"
2
+ require "openssl"
2
3
  require "uri"
3
4
  require "json"
4
5
  require "time"
6
+ require_relative "version"
5
7
 
6
8
  module Jekyll
7
9
  module WebmentionsStatic
8
10
  class Fetcher
9
- ENDPOINT = "https://webmention.io/api/mentions.jf2"
11
+ ENDPOINT = "https://webmention.io/api/mentions.jf2".freeze
10
12
  DEFAULT_TTL = 3600
13
+ PER_PAGE = 100
14
+ MAX_PAGES = 100 # safety cap: 10,000 mentions
15
+ TIMEOUT = 10 # seconds, for both connect and read
16
+
17
+ class FetchError < StandardError; end
11
18
 
12
19
  def initialize(token:, domain:, site_source:, cache: true, cache_ttl: DEFAULT_TTL)
13
20
  @token = token
@@ -19,75 +26,142 @@ module Jekyll
19
26
  end
20
27
 
21
28
  # Returns a hash keyed by wm-target URL → Array of mention hashes.
29
+ # Never raises: on any failure it falls back to the cache (even a stale
30
+ # one) and then to an empty result.
22
31
  def fetch_and_group
23
- raw = load_from_cache || fetch_from_api
24
- group_by_target(raw)
32
+ items = load_fresh_cache || fetch_from_api || load_stale_cache || []
33
+ group_by_target(items)
34
+ rescue StandardError => e
35
+ Jekyll.logger.warn "Webmentions:", "Unexpected error (#{e.class}): #{e.message} — skipping"
36
+ {}
25
37
  end
26
38
 
27
39
  private
28
40
 
29
- def cache_valid?
41
+ # -- cache ------------------------------------------------------------
42
+
43
+ def cache_fresh?
30
44
  return false unless @cache && File.exist?(@cache_path)
31
45
 
32
- age = Time.now - File.mtime(@cache_path)
33
- age < @cache_ttl
46
+ Time.now - File.mtime(@cache_path) < @cache_ttl
34
47
  end
35
48
 
36
- def load_from_cache
37
- return nil unless cache_valid?
49
+ def load_fresh_cache
50
+ return nil unless cache_fresh?
38
51
 
39
- Jekyll.logger.info "Webmentions:", "Using cached data (#{@cache_path})"
40
- JSON.parse(File.read(@cache_path))
41
- rescue JSON::ParserError => e
42
- Jekyll.logger.warn "Webmentions:", "Cache parse error: #{e.message} — refetching"
43
- nil
52
+ items = read_cache
53
+ Jekyll.logger.info "Webmentions:", "Using cached data (#{@cache_path})" if items
54
+ items
44
55
  end
45
56
 
46
- def fetch_from_api
47
- uri = URI(ENDPOINT)
48
- uri.query = URI.encode_www_form(
49
- "token" => @token,
50
- "domain" => @domain,
51
- "per-page" => 500
52
- )
53
-
54
- Jekyll.logger.info "Webmentions:", "Fetching from #{uri}"
57
+ def load_stale_cache
58
+ return nil unless @cache
55
59
 
56
- response = Net::HTTP.get_response(uri)
60
+ items = read_cache
61
+ Jekyll.logger.warn "Webmentions:", "Using stale cache (#{@cache_path}) because the fetch failed" if items
62
+ items
63
+ end
57
64
 
58
- unless response.is_a?(Net::HTTPSuccess)
59
- Jekyll.logger.warn "Webmentions:", "HTTP #{response.code} — skipping"
60
- return []
61
- end
65
+ # Returns the cached items, or nil when there is no usable cache. A cache
66
+ # written for another domain (or in the old bare-array format) is ignored.
67
+ def read_cache
68
+ return nil unless @cache && File.exist?(@cache_path)
62
69
 
63
- data = JSON.parse(response.body)
64
- items = data["items"] || []
70
+ data = JSON.parse(File.read(@cache_path, encoding: "UTF-8"))
71
+ return nil unless data.is_a?(Hash) && data["domain"] == @domain && data["items"].is_a?(Array)
65
72
 
66
- write_cache(items)
67
- items
68
- rescue SocketError, Errno::ECONNREFUSED, Errno::ETIMEDOUT, Net::OpenTimeout,
69
- Net::ReadTimeout, OpenSSL::SSL::SSLError => e
70
- Jekyll.logger.warn "Webmentions:", "Network error: #{e.message} — skipping"
71
- []
72
- rescue JSON::ParserError => e
73
- Jekyll.logger.warn "Webmentions:", "JSON parse error: #{e.message} — skipping"
74
- []
73
+ data["items"]
74
+ rescue JSON::ParserError, SystemCallError => e
75
+ Jekyll.logger.warn "Webmentions:", "Ignoring unreadable cache: #{e.message}"
76
+ nil
75
77
  end
76
78
 
77
79
  def write_cache(items)
78
80
  return unless @cache
79
81
 
80
- File.write(@cache_path, JSON.generate(items))
82
+ File.write(@cache_path, JSON.generate("domain" => @domain, "fetched_at" => Time.now.utc.iso8601, "items" => items))
81
83
  Jekyll.logger.info "Webmentions:", "Cache written to #{@cache_path}"
82
- rescue Errno::EACCES, Errno::EROFS => e
84
+ rescue SystemCallError => e
83
85
  Jekyll.logger.warn "Webmentions:", "Could not write cache: #{e.message}"
84
86
  end
85
87
 
88
+ # -- API --------------------------------------------------------------
89
+
90
+ # Returns all items, or nil if anything went wrong (so a partial result
91
+ # never replaces a good cache).
92
+ def fetch_from_api
93
+ Jekyll.logger.info "Webmentions:", "Fetching mentions for #{@domain} from webmention.io"
94
+
95
+ items = []
96
+ MAX_PAGES.times do |page|
97
+ children, total_pages = fetch_page(page)
98
+ items.concat(children)
99
+
100
+ break if children.empty?
101
+ if total_pages
102
+ break if page + 1 >= total_pages
103
+ elsif children.length < PER_PAGE
104
+ break
105
+ end
106
+
107
+ if page + 1 >= MAX_PAGES
108
+ Jekyll.logger.warn "Webmentions:", "Stopped at the #{MAX_PAGES}-page limit; results are truncated"
109
+ end
110
+ end
111
+
112
+ write_cache(items)
113
+ items
114
+ rescue FetchError, JSON::ParserError, SystemCallError, SocketError, IOError, Timeout::Error,
115
+ OpenSSL::SSL::SSLError, Net::ProtocolError, URI::InvalidURIError => e
116
+ Jekyll.logger.warn "Webmentions:", "#{e.class}: #{e.message} — skipping"
117
+ nil
118
+ rescue StandardError => e
119
+ Jekyll.logger.warn "Webmentions:", "Unexpected #{e.class}: #{e.message} — skipping"
120
+ nil
121
+ end
122
+
123
+ def fetch_page(page)
124
+ uri = URI(ENDPOINT)
125
+ uri.query = URI.encode_www_form("domain" => @domain, "per-page" => PER_PAGE, "page" => page)
126
+
127
+ request = Net::HTTP::Get.new(uri)
128
+ request["Authorization"] = "Bearer #{@token}"
129
+ request["Accept"] = "application/json"
130
+ request["User-Agent"] = "jekyll-webmentions-static/#{VERSION}"
131
+
132
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: true,
133
+ open_timeout: TIMEOUT, read_timeout: TIMEOUT) do |http|
134
+ http.request(request)
135
+ end
136
+
137
+ raise FetchError, "HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
138
+
139
+ parse_feed(JSON.parse(response.body.to_s))
140
+ end
141
+
142
+ # jf2 feeds are {"type":"feed","children":[...],"paging":{...}}. "items"
143
+ # is accepted as a fallback for the older JSON-shaped responses.
144
+ def parse_feed(data)
145
+ raise FetchError, "unexpected response shape" unless data.is_a?(Hash)
146
+
147
+ children = data["children"] || data["items"] || []
148
+ raise FetchError, "unexpected response shape" unless children.is_a?(Array)
149
+
150
+ total_pages = data.dig("paging", "total-pages") if data["paging"].is_a?(Hash)
151
+ total_pages = nil unless total_pages.is_a?(Integer) && total_pages.positive?
152
+
153
+ [children.select { |c| c.is_a?(Hash) }, total_pages]
154
+ end
155
+
156
+ # -- grouping ---------------------------------------------------------
157
+
86
158
  def group_by_target(items)
87
159
  grouped = {}
88
160
  items.each do |item|
161
+ next unless item.is_a?(Hash)
162
+
89
163
  target = item["wm-target"]
90
- next if target.nil? || target.strip.empty?
164
+ next if target.nil? || target.to_s.strip.empty?
91
165
 
92
166
  (grouped[target] ||= []) << item
93
167
  end
@@ -0,0 +1,60 @@
1
+ require "uri"
2
+
3
+ module Jekyll
4
+ module WebmentionsStatic
5
+ # URL helpers shared by the generator and the Liquid tag.
6
+ module UrlHelpers
7
+ module_function
8
+
9
+ # Returns the URL string only when it is an absolute http(s) URL with a
10
+ # host; otherwise nil. Everything rendered into an href or src goes
11
+ # through this, because HTML-escaping alone does not stop `javascript:`.
12
+ def safe_http_url(value)
13
+ str = value.to_s.strip
14
+ return nil if str.empty?
15
+
16
+ uri = URI.parse(str)
17
+ return nil unless %w[http https].include?(uri.scheme.to_s.downcase)
18
+ return nil if uri.host.to_s.empty?
19
+
20
+ str
21
+ rescue URI::InvalidURIError
22
+ nil
23
+ end
24
+
25
+ # Host of a URL or bare domain ("https://www.example.com/blog" and
26
+ # "example.com/blog" both give "www.example.com"). nil when blank.
27
+ def host_of(value)
28
+ str = value.to_s.strip
29
+ return nil if str.empty?
30
+
31
+ str = "https://#{str}" unless str.match?(%r{\A[a-z][a-z0-9+.-]*://}i)
32
+ host = URI.parse(str).host.to_s.downcase
33
+ host.empty? ? nil : host
34
+ rescue URI::InvalidURIError
35
+ nil
36
+ end
37
+
38
+ # A comparison key that ignores scheme, "www.", a trailing slash, a
39
+ # trailing "index.html" and the fragment, so that
40
+ # "http://www.example.com/post/" matches "https://example.com/post".
41
+ def normalize(value)
42
+ str = value.to_s.strip
43
+ return nil if str.empty?
44
+
45
+ uri = URI.parse(str.match?(%r{\A[a-z][a-z0-9+.-]*://}i) ? str : "https://#{str}")
46
+ host = uri.host.to_s.downcase.sub(/\Awww\./, "")
47
+ return str.downcase.sub(%r{/+\z}, "") if host.empty?
48
+
49
+ default = (uri.scheme == "http" && uri.port == 80) || (uri.scheme == "https" && uri.port == 443)
50
+ host += ":#{uri.port}" if uri.port && !default
51
+ path = uri.path.to_s.sub(%r{/index\.html?\z}i, "").sub(%r{/+\z}, "")
52
+ key = "#{host}#{path}"
53
+ key += "?#{uri.query}" if uri.query
54
+ key
55
+ rescue URI::InvalidURIError
56
+ str.downcase.sub(%r{\A[a-z][a-z0-9+.-]*://}, "").sub(%r{/+\z}, "")
57
+ end
58
+ end
59
+ end
60
+ end
@@ -1,5 +1,5 @@
1
1
  module Jekyll
2
2
  module WebmentionsStatic
3
- VERSION = "0.1.1"
3
+ VERSION = "0.2.0"
4
4
  end
5
5
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jekyll-webmentions-static
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 0.2.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
@@ -25,7 +25,7 @@ dependencies:
25
25
  version: '4.0'
26
26
  description: |
27
27
  jekyll-webmentions-static fetches Webmention.io mentions during Jekyll build
28
- and injects them as static data into site.data["webmentions"] keyed by post URL.
28
+ and injects them as static data into site.data["webmentions"] and into page.webmentions.
29
29
  No JavaScript, no runtime API calls — pure static HTML.
30
30
  email:
31
31
  - jason@jasonchance.com
@@ -37,6 +37,7 @@ files:
37
37
  - README.md
38
38
  - lib/jekyll-webmentions-static.rb
39
39
  - lib/jekyll-webmentions-static/fetcher.rb
40
+ - lib/jekyll-webmentions-static/url_helpers.rb
40
41
  - lib/jekyll-webmentions-static/version.rb
41
42
  - lib/jekyll/webmentions_generator.rb
42
43
  - lib/jekyll/webmentions_tag.rb
@@ -45,7 +46,7 @@ licenses:
45
46
  - MIT
46
47
  metadata:
47
48
  source_code_uri: https://github.com/jchance/jekyll-webmentions-static
48
- changelog_uri: https://github.com/jchance/jekyll-webmentions-static/blob/main/CHANGELOG.md
49
+ changelog_uri: https://github.com/jchance/jekyll-webmentions-static/blob/master/CHANGELOG.md
49
50
  bug_tracker_uri: https://github.com/jchance/jekyll-webmentions-static/issues
50
51
  rubygems_mfa_required: 'true'
51
52
  rdoc_options: []
@@ -55,7 +56,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
55
56
  requirements:
56
57
  - - ">="
57
58
  - !ruby/object:Gem::Version
58
- version: '2.7'
59
+ version: '3.0'
59
60
  required_rubygems_version: !ruby/object:Gem::Requirement
60
61
  requirements:
61
62
  - - ">="