@opentf/afw-docs 0.30.0 → 0.32.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Open Tech Foundation and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,165 @@
1
+ <div align="center">
2
+
3
+ # @opentf/afw-docs
4
+
5
+ ***Documentation and blog sites built as ordinary AFW apps***
6
+
7
+ [Docs](https://afw.opentechf.org/packages/afw-docs) | [API](https://afw.opentechf.org/api/afw-docs) | [Changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw-docs/CHANGELOG.md) | [GitHub](https://github.com/Open-Tech-Foundation/afw)
8
+
9
+ </div>
10
+
11
+ <div align="right">
12
+
13
+ *An [Open Tech Foundation](https://opentechf.org/) project*
14
+
15
+ </div>
16
+
17
+ > Write pages as MDX in `app/`. The theme supplies the navbar, sidebar, table of
18
+ > contents, breadcrumbs, search and prev/next links, and generates the navigation
19
+ > from your folders at build time. The [AFW website](https://afw.opentechf.org) is
20
+ > built with it.
21
+
22
+ ```jsx
23
+ // app/docs/layout.jsx
24
+ import { DocsLayout } from "@opentf/afw-docs";
25
+ import config from "../../afw.config.js";
26
+
27
+ export default function Layout(props) {
28
+ return <DocsLayout config={config.docs}>{props.children}</DocsLayout>;
29
+ }
30
+ ```
31
+
32
+ ```mdx
33
+ ---
34
+ title: Reactivity
35
+ description: Signal-based state.
36
+ ---
37
+
38
+ import { Callout } from "@opentf/afw-docs";
39
+
40
+ # Reactivity
41
+
42
+ <Callout type="tip">Mix components into Markdown freely.</Callout>
43
+ ```
44
+
45
+ Every folder under `app/` with a layout like this becomes its own section with its
46
+ own sidebar: `app/docs` serves `/docs` and `app/api` serves `/api`.
47
+
48
+ > [!NOTE]
49
+ > **Alpha.** Components, options and class names can change between minor
50
+ > versions; see the [changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw-docs/CHANGELOG.md).
51
+
52
+ ## Why afw-docs
53
+
54
+ | Need | How afw-docs meets it |
55
+ | --- | --- |
56
+ | 🧭 **Navigation from folders** | The sidebar, breadcrumbs and prev/next are generated from `app/`; `_meta.js` sets order and labels |
57
+ | 🔎 **Search without a service** | A static index built from the prerendered HTML by `afwc`, queried in the browser |
58
+ | ✍️ **MDX with components** | Callouts, tabs, steps, cards and code blocks with copy buttons, highlighted at build time |
59
+ | 📰 **Blog included** | Post lists, banners, reading time and RSS/Atom feeds |
60
+ | 🕒 **Last updated and edit links** | Dates from git history or frontmatter, linked to the source file |
61
+ | 🌗 **Themeable** | Light and dark modes driven by `--afw-*` CSS variables, in an overridable cascade layer |
62
+ | 🤖 **LLM-ready** | `llms.txt` and `llms-full.txt` generated at build |
63
+
64
+ ## Install
65
+
66
+ ```sh
67
+ pnpm add @opentf/afw-docs @opentf/afw
68
+ pnpm add -D @opentf/esdev-plugin-afw @opentf/afw-cli
69
+ ```
70
+
71
+ `esdev create my-docs --template=docs` generates a complete site. To add the theme
72
+ to an existing project, import its stylesheet and register the build plugins:
73
+
74
+ ```css
75
+ /* app/global.css */
76
+ @import "@opentf/afw-docs/theme";
77
+ ```
78
+
79
+ ```json
80
+ {
81
+ "plugins": [
82
+ { "module": "@opentf/esdev-plugin-afw", "options": { "mode": "ssg" } },
83
+ { "module": "@opentf/afw-docs/build", "export": "docsNavPlugin", "options": { "appDir": "app" } },
84
+ { "module": "@opentf/afw-docs/build", "export": "lastUpdatedPlugin", "options": { "appDir": "app" } },
85
+ { "module": "@opentf/afw-docs/build", "export": "blogPostsPlugin", "options": { "appDir": "app", "contentDir": "blog" } }
86
+ ]
87
+ }
88
+ ```
89
+
90
+ `appDir` is resolved from the directory esdev runs in.
91
+
92
+ ### With Vite
93
+
94
+ In the Vite + Node workflow, add `@opentf/afw-docs/vite` next to the AFW Vite plugin.
95
+ It reads the same `afw.config.js`, serves the generated navigation, post list and
96
+ last-updated map, and after the prerender writes the search index, the blog's RSS and
97
+ Atom feeds, and `llms.txt`:
98
+
99
+ ```sh
100
+ pnpm add @opentf/afw-docs @opentf/afw
101
+ pnpm add -D vite @opentf/vite-plugin-afw
102
+ ```
103
+
104
+ ```js
105
+ // vite.config.js
106
+ import afw from "@opentf/vite-plugin-afw";
107
+ import afwDocs from "@opentf/afw-docs/vite";
108
+
109
+ export default { plugins: [afw({ mode: "ssg" }), afwDocs()] };
110
+ ```
111
+
112
+ `vite build` writes the static site to `dist/`; `vite preview` serves it.
113
+
114
+ ## Configure
115
+
116
+ ```js
117
+ // afw.config.js
118
+ import { defineDocsConfig } from "@opentf/afw-docs/config";
119
+
120
+ export default defineDocsConfig({
121
+ site: { url: "https://docs.example.com" },
122
+ docs: {
123
+ title: "My Project",
124
+ github: "https://github.com/me/my-project",
125
+ repoUrl: "https://github.com/me/my-project",
126
+ nav: [
127
+ { label: "Docs", href: "/docs" },
128
+ { label: "Blog", href: "/blog" },
129
+ ],
130
+ lastUpdated: true,
131
+ },
132
+ });
133
+ ```
134
+
135
+ ## Components
136
+
137
+ | Group | Components |
138
+ | --- | --- |
139
+ | **Layouts** | `DocsLayout`, `BlogLayout` |
140
+ | **Shell** | `Navbar`, `NavbarLink`, `Sidebar`, `SidebarToggle`, `Toc`, `Breadcrumbs`, `Pagination`, `Footer`, `LastUpdated`, `ThemeToggle`, `Search`, `SearchTrigger` |
141
+ | **Content** | `Callout`, `Tabs`, `Steps`, `CodeBlock`, `Table`, `Cards`, `Card`, `Tooltip`, `NavIcon` |
142
+ | **Blog** | `PostList`, `PostCard`, `PostBanner`, `PostMeta`, `ReadingTime` |
143
+
144
+ ## Entry points
145
+
146
+ | Import | Contents |
147
+ | --- | --- |
148
+ | `@opentf/afw-docs` | Every component above, plus `createSearch` |
149
+ | `@opentf/afw-docs/theme` | The default light/dark stylesheet |
150
+ | `@opentf/afw-docs/config` | `defineDocsConfig` and the config types |
151
+ | `@opentf/afw-docs/build` | `docsNavPlugin`, `blogPostsPlugin`, `lastUpdatedPlugin`, feed and `llms.txt` renderers (esdev) |
152
+ | `@opentf/afw-docs/vite` | `afwDocs()`: the same generators as one Vite plugin |
153
+ | `@opentf/afw-docs/nav`, `/posts`, `/updated` | Generated navigation, post list and last-updated map |
154
+ | `@opentf/afw-docs/search` | Browser search: `createSearch`, `tokenize`, `excerptParts` |
155
+
156
+ ## Styling
157
+
158
+ The theme's own elements use `afwd-*` classes (`.afwd-sidebar`, `.afwd-callout-tip`),
159
+ and its colours come from `--afw-*` variables that switch on `[data-theme='dark']`.
160
+ All theme rules sit in the `afw-docs` cascade layer, so any rule in your own
161
+ stylesheet overrides them without raising specificity.
162
+
163
+ ## License
164
+
165
+ MIT — see [LICENSE](https://github.com/Open-Tech-Foundation/afw/blob/main/LICENSE).
@@ -4,15 +4,16 @@
4
4
  // module `@opentf/afw-docs/posts` to the ordered post list. A pure build-time
5
5
  // consumer of the file tree — no compiler stage, no runtime cost.
6
6
  //
7
- // Post shape: `{ slug, path, title, description?, date?, author?, tags?, readingTime,
8
- // order? }`. Sorted newest-first by `date`; a numeric `order` (frontmatter) overrides.
7
+ // Post shape: `{ slug, path, title, description?, date?, updated?, author?, tags?,
8
+ // readingTime, order? }`. Sorted newest-first by `date`; a numeric `order` (frontmatter)
9
+ // overrides. Drafts and future-dated posts are left out except under `esdev start`
10
+ // (see publish.js).
9
11
 
10
- import { join } from "runtime:path";
11
-
12
- import { exists, readEntries, readNames, readText } from "./host.js";
12
+ import { exists, join, readEntries, readNames, readText } from "./host.js";
13
13
 
14
14
  import { readFrontmatter } from "./frontmatter.js";
15
15
  import { readingTime } from "./reading-time.js";
16
+ import { frontmatterUpdated, isUnpublished, showsUnpublished } from "./publish.js";
16
17
 
17
18
  const VIRTUAL_ID = "@opentf/afw-docs/posts";
18
19
  // No NUL sentinel: the bundler marks a module virtual explicitly, and a `\0` in
@@ -25,10 +26,10 @@ const PAGE_RE = /^page\.(mdx|md)$/;
25
26
  * @param {string} opts.appDir Absolute path to the project's `app/` directory.
26
27
  * @param {string} [opts.contentDir] Blog content folder under app/ (default "blog").
27
28
  * @param {Set<string>} [opts.exclude] Folder names to skip.
29
+ * @param {boolean} [opts.drafts] List drafts and scheduled posts (default: only under
30
+ * `esdev start`).
28
31
  */
29
- export function blogPostsPlugin({ appDir, contentDir = "blog", exclude = new Set() } = {}) {
30
- const root = join(appDir, contentDir);
31
- const base = "/" + contentDir;
32
+ export function blogPostsPlugin({ appDir, contentDir = "blog", exclude = new Set(), drafts } = {}) {
32
33
  return {
33
34
  name: "afw-blog-posts",
34
35
  resolve: {
@@ -37,21 +38,30 @@ export function blogPostsPlugin({ appDir, contentDir = "blog", exclude = new Set
37
38
  },
38
39
  load: {
39
40
  filter: { id: RESOLVED_ID },
40
- async handler(id) {
41
+ async handler(id, ctx) {
41
42
  if (id !== RESOLVED_ID) return null;
42
- const watch = [];
43
- const posts = (await exists(root)) ? await collectPosts(root, base, exclude, watch) : [];
43
+ const { code, files } = await blogPostsModule({ appDir, contentDir, exclude, drafts: showsUnpublished(drafts, ctx) });
44
44
  // The post list is generated from these files, which nothing imports —
45
45
  // declaring them is what rebuilds the chunk when a post's frontmatter changes.
46
- return {
47
- code: `export const posts = ${JSON.stringify(posts)};\nexport default posts;\n`,
48
- dependsOn: watch,
49
- };
46
+ return { code, dependsOn: files };
50
47
  },
51
48
  },
52
49
  };
53
50
  }
54
51
 
52
+ /**
53
+ * The `@opentf/afw-docs/posts` module source and the post files it lists — the
54
+ * toolchain-neutral half of `blogPostsPlugin`, shared with the Vite plugin.
55
+ *
56
+ * @returns {Promise<{ code: string, files: string[] }>}
57
+ */
58
+ export async function blogPostsModule({ appDir, contentDir = "blog", exclude = new Set(), drafts = false } = {}) {
59
+ const root = join(appDir, contentDir);
60
+ const watch = [];
61
+ const posts = (await exists(root)) ? await collectPosts(root, "/" + contentDir, exclude, watch, drafts) : [];
62
+ return { code: `export const posts = ${JSON.stringify(posts)};\nexport default posts;\n`, files: watch };
63
+ }
64
+
55
65
  /**
56
66
  * Scan the blog content folder and return the ordered post list — the same array the
57
67
  * `blogPostsPlugin` virtual module exposes, but callable directly (used by the feed
@@ -61,16 +71,18 @@ export function blogPostsPlugin({ appDir, contentDir = "blog", exclude = new Set
61
71
  * @param {string} opts.appDir
62
72
  * @param {string} [opts.contentDir]
63
73
  * @param {Set<string>} [opts.exclude]
74
+ * @param {boolean} [opts.drafts] Include drafts and scheduled posts (default false: this
75
+ * feeds production output).
64
76
  */
65
- export async function loadPosts({ appDir, contentDir = "blog", exclude = new Set() } = {}) {
77
+ export async function loadPosts({ appDir, contentDir = "blog", exclude = new Set(), drafts = false } = {}) {
66
78
  const root = join(appDir, contentDir);
67
79
  if (!(await exists(root))) return [];
68
- return collectPosts(root, "/" + contentDir, exclude, []);
80
+ return collectPosts(root, "/" + contentDir, exclude, [], drafts);
69
81
  }
70
82
 
71
83
  // Automatic post metadata describes concrete folders; generated parameters are
72
84
  // unavailable during this scan and must not become card or feed URLs.
73
- async function collectPosts(root, base, exclude, watch) {
85
+ async function collectPosts(root, base, exclude, watch, drafts) {
74
86
  const posts = [];
75
87
  for (const entry of await readEntries(root)) {
76
88
  if (
@@ -90,6 +102,7 @@ async function collectPosts(root, base, exclude, watch) {
90
102
  watch.push(file);
91
103
  const source = await readText(file);
92
104
  const fm = await readFrontmatter(file);
105
+ if (!drafts && isUnpublished(fm)) continue;
93
106
  posts.push(
94
107
  clean({
95
108
  slug: entry.name,
@@ -97,6 +110,10 @@ async function collectPosts(root, base, exclude, watch) {
97
110
  title: fm.title ?? humanize(entry.name),
98
111
  description: fm.description,
99
112
  date: fm.date != null ? String(fm.date) : undefined,
113
+ // Frontmatter only, never git: a bulk commit (a rename, a reformat) touches
114
+ // every post without changing what any of them says.
115
+ updated: frontmatterUpdated(fm),
116
+ draft: drafts && isUnpublished(fm) ? true : undefined,
100
117
  // Cover image (frontmatter `cover`) — shown on the post banner and the card.
101
118
  cover: fm.cover,
102
119
  author: fm.author,
@@ -10,10 +10,9 @@
10
10
  // Tree node shape: `{ title, path?, order?, items?: Node[] }`. A node with `path`
11
11
  // is a link; a node with `items` is a (possibly also linked) group.
12
12
 
13
- import { join, toFileURL } from "runtime:path";
14
-
15
- import { exists, readEntries, readNames, readText } from "./host.js";
13
+ import { exists, join, readEntries, readNames, readText, toFileUrl } from "./host.js";
16
14
  import { readFrontmatter } from "./frontmatter.js";
15
+ import { isUnpublished, showsUnpublished } from "./publish.js";
17
16
 
18
17
  const VIRTUAL_ID = "@opentf/afw-docs/nav";
19
18
  // No NUL sentinel: the bundler marks a module virtual explicitly, and a `\0` in
@@ -42,8 +41,9 @@ function navDirectory(entry, exclude) {
42
41
  * @param {(file: string) => Promise<any>} [opts.importModule] How to read a `_meta.js`.
43
42
  * The dev server passes a loader that re-evaluates the file after an edit; a plain
44
43
  * `import()` cannot, because the runtime caches ESM by path for the process's life.
44
+ * @param {boolean} [opts.drafts] List draft pages (default: only under `esdev start`).
45
45
  */
46
- export function docsNavPlugin({ appDir, exclude = new Set(), importModule } = {}) {
46
+ export function docsNavPlugin({ appDir, exclude = new Set(), importModule, drafts } = {}) {
47
47
  return {
48
48
  name: "afw-docs-nav",
49
49
  resolve: {
@@ -52,24 +52,35 @@ export function docsNavPlugin({ appDir, exclude = new Set(), importModule } = {}
52
52
  },
53
53
  load: {
54
54
  filter: { id: RESOLVED_ID },
55
- async handler(id) {
55
+ async handler(id, hookCtx) {
56
56
  if (id !== RESOLVED_ID) return null;
57
- const ctx = { watch: [], importModule };
58
- const out = {};
59
- for (const entry of await readEntries(appDir)) {
60
- if (!navDirectory(entry, exclude)) continue;
61
- const base = "/" + entry.name;
62
- out[base] = await buildSection(join(appDir, entry.name), base, ctx, true, exclude);
63
- }
57
+ const { code, files } = await docsNavModule({ appDir, exclude, importModule, drafts: showsUnpublished(drafts, hookCtx) });
64
58
  // The files this tree was generated from. They are not imports, so nothing else
65
59
  // ties them to this module — declaring them is what makes the dev server rebuild the
66
60
  // chunk holding the sidebar when a page's frontmatter or a `_meta.*` changes.
67
- return { code: `export default ${JSON.stringify(out)};\n`, dependsOn: ctx.watch };
61
+ return { code, dependsOn: files };
68
62
  },
69
63
  },
70
64
  };
71
65
  }
72
66
 
67
+ /**
68
+ * The `@opentf/afw-docs/nav` module source and the files it was generated from — the
69
+ * toolchain-neutral half of `docsNavPlugin`, shared with the Vite plugin.
70
+ *
71
+ * @returns {Promise<{ code: string, files: string[] }>}
72
+ */
73
+ export async function docsNavModule({ appDir, exclude = new Set(), importModule, drafts = false } = {}) {
74
+ const ctx = { watch: [], importModule, drafts };
75
+ const out = {};
76
+ for (const entry of await readEntries(appDir)) {
77
+ if (!navDirectory(entry, exclude)) continue;
78
+ const base = "/" + entry.name;
79
+ out[base] = await buildSection(join(appDir, entry.name), base, ctx, true, exclude);
80
+ }
81
+ return { code: `export default ${JSON.stringify(out)};\n`, files: ctx.watch };
82
+ }
83
+
73
84
  /** Load a folder's `_meta` (ordering + labels). Supports `.js`/`.mjs`/`.json`. */
74
85
  async function loadMeta(dir, ctx) {
75
86
  for (const name of ["_meta.js", "_meta.mjs", "_meta.json"]) {
@@ -81,7 +92,7 @@ async function loadMeta(dir, ctx) {
81
92
  // A query string does not bust the ESM cache (it is keyed by path and ignores
82
93
  // `?t=`), so a host that needs live `_meta` edits supplies a loader that can
83
94
  // re-read the file; without one this is a plain, once-per-process import.
84
- const mod = await (ctx.importModule?.(p) ?? import(toFileURL(p).href));
95
+ const mod = await (ctx.importModule?.(p) ?? import(toFileUrl(p)));
85
96
  return mod.default ?? mod;
86
97
  } catch (e) {
87
98
  console.warn(`⚠ [@opentf/afw-docs] could not load ${p}: ${e?.message ?? e}`);
@@ -177,13 +188,15 @@ async function buildNode(dir, route, key, parentMeta, ctx, exclude) {
177
188
  if (MD_RE.test(pf)) fm = await readFrontmatter(pf);
178
189
  }
179
190
  const children = await buildSection(dir, route, ctx, false, exclude);
191
+ // An unpublished page is left out of the production nav; its children still show.
192
+ const page = pf && (ctx.drafts || !isUnpublished(fm)) ? pf : null;
180
193
  // A directory that has neither a page nor children contributes nothing.
181
- if (!pf && children.length === 0) return null;
194
+ if (!page && children.length === 0) return null;
182
195
 
183
196
  const title = metaLabel(parentMeta, key) ?? fm.sidebar_label ?? fm.title ?? humanize(key);
184
197
  return clean({
185
198
  title,
186
- path: pf ? route : undefined,
199
+ path: page ? route : undefined,
187
200
  order: fm.order,
188
201
  items: children.length ? children : undefined,
189
202
  });
package/build/feed.js CHANGED
@@ -32,6 +32,32 @@ function iso8601(date) {
32
32
  return Number.isNaN(d.getTime()) ? null : d.toISOString();
33
33
  }
34
34
 
35
+ /**
36
+ * A post's body for a feed, from its prerendered page: the inner HTML of the page's
37
+ * `<article class="afwd-prose">`, with what only a live page needs removed (hydration
38
+ * comments, scripts, `<template>`s, the copy buttons on code blocks) and root-relative
39
+ * `src`/`href` made absolute, since a feed reader has no base URL. A `cover` leads the
40
+ * body as an image. Returns "" when the page has no prose article.
41
+ */
42
+ export function postContentHtml(pageHtml, baseUrl, cover) {
43
+ const m = String(pageHtml).match(/<article class="afwd-prose">([\s\S]*)<\/article>/);
44
+ if (!m) return "";
45
+ const body = m[1]
46
+ .replace(/<!--[\s\S]*?-->/g, "")
47
+ .replace(/<script\b[\s\S]*?<\/script>/gi, "")
48
+ .replace(/<template\b[\s\S]*?<\/template>/gi, "")
49
+ .replace(/<button\b[\s\S]*?<\/button>/gi, "")
50
+ .replace(/\s(src|href)="\/(?!\/)/g, (_, attr) => ` ${attr}="${baseUrl.replace(/\/+$/, "")}/`)
51
+ .trim();
52
+ const image = cover ? `<p><img src="${esc(abs(baseUrl, cover))}" alt=""></p>` : "";
53
+ return image + body;
54
+ }
55
+
56
+ /** CDATA section around `s`, splitting any `]]>` inside it. */
57
+ function cdata(s) {
58
+ return `<![CDATA[${String(s).replace(/]]>/g, "]]]]><![CDATA[>")}]]>`;
59
+ }
60
+
35
61
  /** Newest valid publication instant, independent of post display order. */
36
62
  function newestPostDate(posts) {
37
63
  let newest = -Infinity;
@@ -73,6 +99,8 @@ export function renderBlogFeed({ posts = [], baseUrl, feedPath = "/blog/rss.xml"
73
99
  if (pubDate) parts.push(` <pubDate>${pubDate}</pubDate>`);
74
100
  if (p.author) parts.push(` <dc:creator>${esc(p.author)}</dc:creator>`);
75
101
  if (p.description) parts.push(` <description>${esc(p.description)}</description>`);
102
+ // The full post (`postContentHtml`), so a reader can show it without a click-through.
103
+ if (p.content) parts.push(` <content:encoded>${cdata(p.content)}</content:encoded>`);
76
104
  for (const tag of p.tags || []) parts.push(` <category>${esc(tag)}</category>`);
77
105
  return ` <item>\n${parts.join("\n")}\n </item>`;
78
106
  })
@@ -80,7 +108,7 @@ export function renderBlogFeed({ posts = [], baseUrl, feedPath = "/blog/rss.xml"
80
108
 
81
109
  return (
82
110
  `<?xml version="1.0" encoding="UTF-8"?>\n` +
83
- `<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">\n` +
111
+ `<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">\n` +
84
112
  ` <channel>\n` +
85
113
  ` <title>${esc(title)}</title>\n` +
86
114
  ` <link>${esc(link)}</link>\n` +
@@ -121,11 +149,12 @@ export function renderAtomFeed({ posts = [], baseUrl, feedPath = "/blog/atom.xml
121
149
  ` <title>${esc(p.title)}</title>`,
122
150
  ` <link href="${esc(url)}"/>`,
123
151
  ` <id>${esc(url)}</id>`,
124
- ` <updated>${published || updated}</updated>`,
152
+ ` <updated>${iso8601(p.updated) || published || updated}</updated>`,
125
153
  ];
126
154
  if (published) parts.push(` <published>${published}</published>`);
127
155
  parts.push(` <author><name>${esc(p.author || fallbackAuthor)}</name></author>`);
128
156
  if (p.description) parts.push(` <summary>${esc(p.description)}</summary>`);
157
+ if (p.content) parts.push(` <content type="html">${esc(p.content)}</content>`);
129
158
  for (const tag of p.tags || []) parts.push(` <category term="${esc(tag)}"/>`);
130
159
  return ` <entry>\n${parts.join("\n")}\n </entry>`;
131
160
  })
@@ -0,0 +1,164 @@
1
+ // The steps a docs or blog site runs after its pages are prerendered: the AFW Search
2
+ // index, RSS and Atom feeds (advertised from every page), and `llms.txt`. Shared by
3
+ // both workflows through the installed host (host.js). Each step reads the project's
4
+ // afw.config (`docs`, `blog`, `site.url`) and honours a hand-written file in
5
+ // `public/`.
6
+
7
+ import { exists, join, readEntries, readText, writeText } from "./host.js";
8
+ import { loadPosts } from "./blog-posts-plugin.js";
9
+ import { postContentHtml, renderAtomFeed, renderBlogFeed } from "./feed.js";
10
+ import { readFrontmatter } from "./frontmatter.js";
11
+ import { renderLlmsFullTxt, renderLlmsTxt } from "./llms.js";
12
+ import { isUnpublished } from "./publish.js";
13
+ import { indexWithAfwSearch } from "./search.js";
14
+
15
+ /** Whether "last updated" tracking is enabled anywhere (`docs`/`blog` `lastUpdated`). */
16
+ export function wantsLastUpdated(config) {
17
+ return Boolean(config?.docs?.lastUpdated || config?.blog?.lastUpdated);
18
+ }
19
+
20
+ /** The blog's content folder under `app/`, or undefined without a blog. */
21
+ export function blogDir(config) {
22
+ return config?.blog ? config.blog.dir ?? "blog" : undefined;
23
+ }
24
+
25
+ /**
26
+ * The warning for a `docs.search.provider` other than `"afw"`, or null. A retired value
27
+ * would otherwise turn search off without a word.
28
+ */
29
+ export function searchProviderWarning(config) {
30
+ const provider = config?.docs?.search?.provider;
31
+ if (provider == null || provider === "afw") return null;
32
+ return `⚠ docs.search.provider ${JSON.stringify(provider)} is not supported; use "afw" or remove it. Search is disabled for this build.`;
33
+ }
34
+
35
+ /** Index the prerendered site when static search is on. Errors fail the build. */
36
+ export async function runDocsSearchIndex(config, siteDir, afwc) {
37
+ if (config?.docs?.search?.provider !== "afw") return null;
38
+ return indexWithAfwSearch({ siteDir, afwc });
39
+ }
40
+
41
+ /**
42
+ * Write `<blog>/rss.xml` and `<blog>/atom.xml` with each post's full content, read back
43
+ * from its prerendered page, and link them from every page's `<head>`. Needs the site
44
+ * URL. Returns `{ paths, urls, count }`, or null when skipped.
45
+ */
46
+ export async function runBlogFeed({ root, appDir, config, siteDir, baseUrl, exclude = new Set() }) {
47
+ const blog = config?.blog;
48
+ if (!blog) return null;
49
+ if (!baseUrl) {
50
+ console.warn("⚠ blog feeds skipped: no site URL (set site.url in afw.config)");
51
+ return null;
52
+ }
53
+ const contentDir = blog.dir ?? "blog";
54
+ const posts = await loadPosts({ appDir, contentDir, exclude });
55
+ for (const post of posts) {
56
+ const page = join(siteDir, post.path.replace(/^\/+/, ""), "index.html");
57
+ if (await exists(page)) post.content = postContentHtml(await readText(page), baseUrl, post.cover);
58
+ }
59
+ const title = blog.title || (config?.docs?.title ? `${config.docs.title} Blog` : "Blog");
60
+ const channel = {
61
+ title,
62
+ description: blog.description || title,
63
+ link: `/${contentDir}`,
64
+ language: blog.language || config?.i18n?.defaultLocale || "en",
65
+ };
66
+ const feeds = [
67
+ { file: "rss.xml", path: `/${contentDir}/rss.xml`, render: renderBlogFeed },
68
+ { file: "atom.xml", path: `/${contentDir}/atom.xml`, render: renderAtomFeed },
69
+ ];
70
+ const written = [];
71
+ for (const feed of feeds) {
72
+ if (await exists(join(root, "public", contentDir, feed.file))) continue; // honour an override
73
+ await writeText(join(siteDir, contentDir, feed.file), feed.render({ posts, baseUrl, feedPath: feed.path, channel }));
74
+ written.push(feed.path);
75
+ }
76
+ if (!written.length) return null;
77
+ await injectFeedLinks(siteDir, title, contentDir);
78
+ const origin = baseUrl.replace(/\/+$/, "");
79
+ return { paths: written, urls: written.map((path) => origin + path), count: posts.length };
80
+ }
81
+
82
+ /**
83
+ * Advertise the feeds from every prerendered page: RSS and Atom `<link rel="alternate">`
84
+ * in each `<head>`. A page that already declares a feed is left alone.
85
+ */
86
+ async function injectFeedLinks(siteDir, title, contentDir) {
87
+ const t = String(title).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
88
+ const links =
89
+ `<link rel="alternate" type="application/rss+xml" title="${t}" href="/${contentDir}/rss.xml">\n` +
90
+ `<link rel="alternate" type="application/atom+xml" title="${t}" href="/${contentDir}/atom.xml">\n`;
91
+ const walk = async (dir) => {
92
+ for (const entry of await readEntries(dir)) {
93
+ const full = join(dir, entry.name);
94
+ if (entry.isDir) await walk(full);
95
+ else if (entry.name.endsWith(".html")) {
96
+ const html = await readText(full);
97
+ if (/type="application\/(rss|atom)\+xml"/.test(html) || !/<\/head>/i.test(html)) continue;
98
+ await writeText(full, html.replace(/<\/head>/i, () => `${links}</head>`));
99
+ }
100
+ }
101
+ };
102
+ await walk(siteDir);
103
+ }
104
+
105
+ /** The app's published page, layout and 404 files (what `llms.txt` summarizes). */
106
+ export async function publishedPages(appDir, exclude = new Set()) {
107
+ const out = [];
108
+ const walk = async (dir) => {
109
+ for (const entry of await readEntries(dir)) {
110
+ if (entry.isDir) {
111
+ if (!exclude.has(entry.name) && !entry.name.startsWith(".") && entry.name !== "node_modules") await walk(join(dir, entry.name));
112
+ continue;
113
+ }
114
+ if (!/^(page|layout|404)\.(mdx|md|[jt]sx)$/.test(entry.name)) continue;
115
+ const file = join(dir, entry.name);
116
+ if (/\.(mdx|md)$/.test(entry.name) && isUnpublished(await readFrontmatter(file))) continue;
117
+ out.push(file);
118
+ }
119
+ };
120
+ await walk(appDir);
121
+ return out.sort();
122
+ }
123
+
124
+ /**
125
+ * Write `/llms.txt` and `/llms-full.txt` for a docs or blog site. A file in `public/`
126
+ * overrides each one. `siteDescription` summarizes the site (from its own metadata).
127
+ */
128
+ export async function runLlmsFiles({ root, appDir, pages, config, siteDir, baseUrl, siteDescription = "" }) {
129
+ if (!config?.docs && !config?.blog) return null;
130
+ const outputs = [
131
+ { file: "llms.txt", render: renderLlmsTxt },
132
+ { file: "llms-full.txt", render: renderLlmsFullTxt },
133
+ ];
134
+ const written = [];
135
+ for (const out of outputs) {
136
+ if (await exists(join(root, "public", out.file))) continue;
137
+ await writeText(join(siteDir, out.file), await out.render({ appDir, pages, baseUrl, config, siteDescription }));
138
+ written.push(`/${out.file}`);
139
+ }
140
+ return written.length ? { paths: written } : null;
141
+ }
142
+
143
+ /**
144
+ * Every finishing step, in order, for a prerendered site in `siteDir`. Returns what
145
+ * each step produced (null for a skipped step).
146
+ */
147
+ export async function finishSite({ root, appDir, config, siteDir, baseUrl = "", exclude = new Set(), siteDescription = "", afwc }) {
148
+ const warning = searchProviderWarning(config);
149
+ if (warning) console.warn(warning);
150
+ // A failed search index fails the build; feeds and llms.txt warn and carry on.
151
+ const search = await runDocsSearchIndex(config, siteDir, afwc);
152
+ const optional = async (label, step) => {
153
+ try {
154
+ return await step();
155
+ } catch (e) {
156
+ console.warn(`⚠ ${label} skipped: ${e?.message ?? e}`);
157
+ return null;
158
+ }
159
+ };
160
+ const feeds = await optional("blog feeds", () => runBlogFeed({ root, appDir, config, siteDir, baseUrl, exclude }));
161
+ const llms = await optional("llms.txt", async () =>
162
+ runLlmsFiles({ root, appDir, pages: await publishedPages(appDir, exclude), config, siteDir, baseUrl, siteDescription }));
163
+ return { search, feeds, llms };
164
+ }