Skip to content

A local-first personal finance app

[AI] docs: fix broken blog links and add enforce-doc-links remark plugin (#8180)

Stephen Brown II123cf1e25aa0
diff --git a/.github/actions/docs-spelling/allow/keywords.txt b/.github/actions/docs-spelling/allow/keywords.txt
index ca423913ac..2c1f592088 100644
--- a/.github/actions/docs-spelling/allow/keywords.txt
+++ b/.github/actions/docs-spelling/allow/keywords.txt
@@ -139,6 +139,7 @@ Upstash
useb
usernames
valign
+vfile
Venmo
Weblate
winsvg
diff --git a/packages/docs/docs/experimental/budget-automation.md b/packages/docs/docs/experimental/budget-automation.md
index fd9a4dd00f..3d1dca9598 100644
--- a/packages/docs/docs/experimental/budget-automation.md
+++ b/packages/docs/docs/experimental/budget-automation.md
@@ -21,7 +21,7 @@ Here are a few examples of what you can do, all with a single click!
- Budget 10% of your income for savings or charity
- Budget the average you spend over the last 6 months
- Save up for a big purchase many months or years in the future, and let Actual dynamically figure out how much to budget every month
-- And much more! Check out this [blog entry from 2023!](../../../blog/2023-12-15-automate-your-budget-with-goal-templates) Although it was written in the early days of note templates, it's still pertinent today!
+- And much more! Check out this [blog entry from 2023!](../../blog/2023-12-15-automate-your-budget-with-goal-templates) Although it was written in the early days of note templates, it's still pertinent today!
---
@@ -121,7 +121,7 @@ For weeks, the number of weeks in a month is based on the weekday of your start
:::tip
You can give different priorities to multiple _Fixed amount_ automations in the same category and they will be respected when the budget fills.
-This [blog post using note templates](../../../blog/2024-03-25-goal-templates-with-a-twist) from 2024 goes into this in more detail.
+This [blog post using note templates](../../blog/2024-03-25-goal-templates-with-a-twist) from 2024 goes into this in more detail.
:::
### Save by Date {#save-by-date}
diff --git a/packages/docs/docs/getting-started/envelope-budgeting.md b/packages/docs/docs/getting-started/envelope-budgeting.md
index f4541454f0..6517bb3b93 100644
--- a/packages/docs/docs/getting-started/envelope-budgeting.md
+++ b/packages/docs/docs/getting-started/envelope-budgeting.md
@@ -77,7 +77,7 @@ buffer. Instead of aiming to save the full $ 3,000 in one go, begin by setting a
For example, if you can set aside $ 200 each month, gradually build your buffer over several months. As you save
more, you'll start to pay some of next month's bills with this reserve.
-You can also read about this strategy in [one of our blog posts](../../../blog/2023-12-15-automate-your-budget-with-goal-templates).
+You can also read about this strategy in [one of our blog posts](../../blog/2023-12-15-automate-your-budget-with-goal-templates).
### Pay-Yourself-First Strategy
diff --git a/packages/docs/docusaurus.config.js b/packages/docs/docusaurus.config.js
index 48e2b41f70..83beb266bd 100644
--- a/packages/docs/docusaurus.config.js
+++ b/packages/docs/docusaurus.config.js
@@ -5,7 +5,10 @@ const { themes } = require('prism-react-renderer');
const defaultOptions = {
editUrl: 'https://github.com/actualbudget/actual/tree/master/packages/docs',
- beforeDefaultRemarkPlugins: [require('./src/remark/mentions')],
+ beforeDefaultRemarkPlugins: [
+ require('./src/remark/mentions'),
+ require('./src/remark/enforce-doc-links'),
+ ],
};
/** @type {import('@docusaurus/types').Config} */
@@ -33,7 +36,7 @@ module.exports = {
markdown: {
mermaid: true,
hooks: {
- onBrokenMarkdownLinks: 'warn',
+ onBrokenMarkdownLinks: 'throw',
},
},
diff --git a/packages/docs/scripts/generate-upcoming-release-notes.mjs b/packages/docs/scripts/generate-upcoming-release-notes.mjs
index 7818fcb268..adc910b7a8 100644
--- a/packages/docs/scripts/generate-upcoming-release-notes.mjs
+++ b/packages/docs/scripts/generate-upcoming-release-notes.mjs
@@ -28,7 +28,7 @@ const intro = `:::info
These changes have been merged but are **not yet part of a stable release**. They
ship in the nightly builds — try them via the \`nightly\` Docker image tag, or the
hosted demo at [nightly.actualbudget.org](https://nightly.actualbudget.org).
-For changes in stable releases, see the [Release Notes](/docs/releases).
+For changes in stable releases, see the [Release Notes](./releases.md).
:::`;
@@ -52,7 +52,7 @@ const { notesByCategory, files } = await parseReleaseNotes(
const body =
files.length === 0
- ? `There are no unreleased changes right now — everything has shipped in a stable [release](/docs/releases).`
+ ? `There are no unreleased changes right now — everything has shipped in a stable [release](./releases.md).`
: formatNotes(notesByCategory);
await fs.writeFile(outputPath, `${header}\n\n${body}\n`);
diff --git a/packages/docs/src/remark/enforce-doc-links.js b/packages/docs/src/remark/enforce-doc-links.js
new file mode 100644
index 0000000000..da66dca508
--- /dev/null
+++ b/packages/docs/src/remark/enforce-doc-links.js
@@ -0,0 +1,254 @@
+'use strict';
+
+const path = require('path');
+const fs = require('fs');
+
+const IMG_EXTENSIONS = new Set([
+ '.png',
+ '.jpg',
+ '.jpeg',
+ '.webp',
+ '.svg',
+ '.gif',
+ '.ico',
+ '.avif',
+]);
+const DOC_EXTENSIONS = new Set(['.md', '.mdx']);
+
+// ---------------------------------------------------------------------------
+// Slug cache: maps blog/docs slug strings -> absolute file paths.
+// Built once per process from frontmatter, keyed by docs-root path.
+// ---------------------------------------------------------------------------
+
+/** @type {Map<string, Map<string, string>>} docsRoot -> (slug -> absFilePath) */
+const slugCacheByRoot = new Map();
+
+/**
+ * Parse the `slug:` value from a YAML front matter block.
+ * Handles quoted and unquoted values; returns null if not found.
+ */
+function parseFrontmatterSlug(content) {
+ const fm = content.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---/);
+ if (!fm) return null;
+ const match = fm[1].match(/^slug:[ \t]+(['"]?)(.+?)\1[ \t]*$/m);
+ return match ? match[2].trim() : null;
+}
+
+/**
+ * Walk a directory (non-recursive) and return absolute paths of .md/.mdx files.
+ */
+function listMarkdownFiles(dir) {
+ try {
+ return fs
+ .readdirSync(dir)
+ .filter(f => /\.(md|mdx)$/.test(f))
+ .map(f => path.join(dir, f));
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Find the docs-site root (the directory containing both `docs/` and `blog/`
+ * sub-directories) by walking up from any file inside it.
+ */
+function findDocsRoot(filePath) {
+ let dir = path.dirname(filePath);
+ while (true) {
+ const parent = path.dirname(dir);
+ if (
+ fs.existsSync(path.join(dir, 'blog')) &&
+ fs.existsSync(path.join(dir, 'docs')) &&
+ fs.existsSync(path.join(dir, 'docusaurus.config.js'))
+ ) {
+ return dir;
+ }
+ if (parent === dir) return null; // filesystem root
+ dir = parent;
+ }
+}
+
+/**
+ * Return (or build) the slug -> absFilePath map for the given docs root.
+ * Scans `blog/` and `docs/` (recursively) for any file that declares a `slug:`
+ * in its front matter.
+ */
+function getSlugCache(docsRoot) {
+ if (slugCacheByRoot.has(docsRoot)) return slugCacheByRoot.get(docsRoot);
+
+ const cache = new Map();
+
+ const blogFiles = listMarkdownFiles(path.join(docsRoot, 'blog'));
+ for (const f of blogFiles) {
+ try {
+ const slug = parseFrontmatterSlug(fs.readFileSync(f, 'utf8'));
+ if (slug) cache.set(slug, f);
+ } catch {}
+ }
+
+ slugCacheByRoot.set(docsRoot, cache);
+ return cache;
+}
+
+// ---------------------------------------------------------------------------
+// AST walker
+// ---------------------------------------------------------------------------
+
+function visitLinks(node, fn) {
+ if (!node) return;
+ if (node.type === 'link' || node.type === 'definition') fn(node);
+ if (node.children) {
+ for (const child of node.children) visitLinks(child, fn);
+ }
+}
+
+/** True when the file lives under the docs/ content tree (not blog/ or src/). */
+function isDocsFile(filePath) {
+ return /[/\\]packages[/\\]docs[/\\]docs[/\\]/.test(filePath);
+}
+
+/** True when the file lives under the blog/ directory. */
+function isBlogFile(filePath) {
+ return /[/\\]packages[/\\]docs[/\\]blog[/\\]/.test(filePath);
+}
+
+// ---------------------------------------------------------------------------
+// Plugin
+// ---------------------------------------------------------------------------
+
+/**
+ * Remark plugin that enforces link hygiene in docs/ pages:
+ *
+ * Covers both docs/ pages and blog/ posts:
+ *
+ * 1. No absolute internal links (/docs/..., /blog/...) — use relative .md paths.
+ * 2. Relative links to other .md/.mdx files must include the extension.
+ * 3. Relative links that use a Docusaurus slug instead of the real filename
+ * are caught via frontmatter scanning and reported with the correct path.
+ *
+ * Links from blog/ posts that target docs/ content cannot use file paths
+ * (Docusaurus constraint) and are left as URL references — those are validated
+ * by onBrokenLinks: 'throw' at the rendered-URL level.
+ *
+ * Links that genuinely can't be resolved to a local file (e.g. to src/pages/)
+ * are similarly left to the rendered-URL checker.
+ */
+function remarkEnforceDocLinks() {
+ return function transformer(ast, vfile) {
+ const filePath = vfile.path || (vfile.history && vfile.history[0]);
+ const inDocs = filePath && isDocsFile(filePath);
+ const inBlog = filePath && isBlogFile(filePath);
+ if (!inDocs && !inBlog) return;
+
+ const fileDir = path.dirname(filePath);
+ const docsRoot = findDocsRoot(filePath);
+ const slugCache = docsRoot ? getSlugCache(docsRoot) : null;
+ // Absolute paths of the content trees, used for cross-plugin boundary checks.
+ const docsContentDir = docsRoot ? path.join(docsRoot, 'docs') : null;
+ const blogDir = docsRoot ? path.join(docsRoot, 'blog') : null;
+
+ const errors = [];
+
+ visitLinks(ast, node => {
+ const url = node.url;
+ if (!url) return;
+
+ if (/^(https?:|mailto:|data:)/.test(url)) return;
+ if (url.startsWith('#')) return;
+
+ const [base] = url.split('#');
+ const ext = path.extname(base);
+ if (IMG_EXTENSIONS.has(ext)) return;
+
+ // Rule 1: absolute internal links (docs/ only).
+ // Blog posts appear in multiple URL contexts (post page, list pages,
+ // tag pages) so relative URLs would resolve differently per context.
+ // Blog→docs links must therefore use absolute URLs — don't flag them.
+ if (inDocs && url.startsWith('/') && !url.startsWith('/img/')) {
+ const pos = nodePos(node);
+ errors.push(
+ `${pos}: absolute link "${url}" — use a relative .md path instead`,
+ );
+ return;
+ }
+
+ if (!base) return; // anchor-only after stripping
+ if (DOC_EXTENSIONS.has(ext)) return; // already correct
+
+ const resolved = path.resolve(fileDir, base);
+
+ // Blog posts cannot use file-path references into docs/ (Docusaurus constraint).
+ // Those links are URL references; leave them to onBrokenLinks validation.
+ if (inBlog && docsContentDir && resolved.startsWith(docsContentDir))
+ return;
+
+ // Rule 2a: resolves to a .md/.mdx file directly (just missing the extension)
+ for (const docExt of ['.md', '.mdx']) {
+ if (fs.existsSync(resolved + docExt)) {
+ const pos = nodePos(node);
+ errors.push(
+ `${pos}: link "${url}" is missing its extension — use "${base + docExt}"`,
+ );
+ return;
+ }
+ }
+
+ // Rule 2b: resolves to a directory that has an index file
+ for (const docExt of ['.md', '.mdx']) {
+ const indexFile = path.join(resolved, 'index' + docExt);
+ if (fs.existsSync(indexFile)) {
+ const pos = nodePos(node);
+ const suggestion = path.posix.join(
+ base.replace(/\\/g, '/'),
+ 'index' + docExt,
+ );
+ errors.push(
+ `${pos}: link "${url}" points to a directory — use "${suggestion}" instead`,
+ );
+ return;
+ }
+ }
+
+ // Rule 3: slug-style link that matches a known frontmatter slug.
+ // Skip for docs→blog cross-plugin links: Docusaurus cannot resolve .md
+ // file paths across plugins, so URL-slug style is the required format there.
+ if (slugCache) {
+ const slug = path.basename(base);
+ const match = slugCache.get(slug);
+ if (match) {
+ const matchInBlog = blogDir && match.startsWith(blogDir);
+ if (inDocs && matchInBlog) {
+ // Cross-plugin: docs→blog must use URL-slug style. OK.
+ } else {
+ const relCorrect = toRelative(fileDir, match);
+ const pos = nodePos(node);
+ errors.push(
+ `${pos}: link "${url}" uses a Docusaurus slug instead of the file path — use "${relCorrect}"`,
+ );
+ return;
+ }
+ }
+ }
+
+ // Can't resolve to a local file — URL reference to src/pages/ etc. OK.
+ });
+
+ if (errors.length > 0) {
+ const rel = path.relative(process.cwd(), filePath);
+ throw new Error(`Doc link errors in ${rel}:\n ${errors.join('\n ')}`);
+ }
+ };
+}
+
+function nodePos(node) {
+ return node.position
+ ? `${node.position.start.line}:${node.position.start.column}`
+ : '?';
+}
+
+/** Relative path from fromDir to toFile, always using forward slashes. */
+function toRelative(fromDir, toFile) {
+ return path.relative(fromDir, toFile).replace(/\\/g, '/');
+}
+
+module.exports = remarkEnforceDocLinks;