From 9616e529c7853fe42aae3fc1fc415632e89a4e06 Mon Sep 17 00:00:00 2001 From: Alex Smith Date: Tue, 28 Jul 2026 20:59:46 -0400 Subject: [PATCH 1/2] chore(docs): flatten MDX tab JSX out of the generated LLM artifacts docusaurus-plugin-llms reads source markdown and exposes no transform hook, so / JSX lands verbatim in llms.txt, llms-full.txt and every per-page .md twin. Today that already leaks 112 tab tags from the skills pages; #402 would spread it across ~18 more. Add scripts/flatten-llms-tabs.mjs, chained onto the docs build. It can't be a Docusaurus plugin: core runs every plugin's postBuild under Promise.all, so a sibling would race the llms plugin. Two transforms, because there are two kinds of tabs: - collapses to a single fenced pnpm block, matching the default tab, so what an agent copies out of llms.txt is what a reader sees. - Generic linearizes to #### headings, keeping every TabItem body. Keeping only the first would have deleted the skills pages' complementary ProfileCard.tsx / _profilecard.scss / Usage tabs. Both run only outside code, fenced and inline. That is load-bearing, not defensive: bestax-bulma has its own Tabs component, and ` usages preserved, api/components/tabs.md byte identical, and idempotent on a second run. --- docs/CLAUDE.md | 8 ++ docs/package.json | 3 +- docs/scripts/flatten-llms-tabs.mjs | 162 ++++++++++++++++++++++ docs/scripts/flatten-llms-tabs.test.mjs | 170 ++++++++++++++++++++++++ 4 files changed, 342 insertions(+), 1 deletion(-) create mode 100644 docs/scripts/flatten-llms-tabs.mjs create mode 100644 docs/scripts/flatten-llms-tabs.test.mjs diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md index 77d87164b..cd63c62f8 100644 --- a/docs/CLAUDE.md +++ b/docs/CLAUDE.md @@ -24,6 +24,14 @@ The build runs `docusaurus-plugin-llms` (configured in `docusaurus.config.js`), - `/llms.txt` (curated index) and `/llms-full.txt` (full concatenation) - a per-page `.md` twin for every doc page (so `llms.txt` links resolve) +The plugin reads **source** markdown and has no transform hook, so MDX tab JSX would land +verbatim in those artifacts. `scripts/flatten-llms-tabs.mjs` runs after `docusaurus build` +(chained in the `build` script — it can't be a plugin, since core runs every `postBuild` under +`Promise.all`) and flattens it: `` collapses to the pnpm +command, `` linearizes to `####` headings keeping every `TabItem` body. It never touches +code — fenced _or_ inline — because `docs/api/components/tabs.md` documents bestax-bulma's own +``/``. Covered by `scripts/flatten-llms-tabs.test.mjs` (`pnpm test`). + Consequences: moving/renaming/deleting a doc page changes the published LLM index that AI agents consume — treat URL changes like API changes. The canonical AI entrypoint is the LLMs guide (`docs/guides/llms/` → https://bestax.io/docs/guides/llms) — don't add new competing diff --git a/docs/package.json b/docs/package.json index b08dd6ff7..0b8e9deb0 100644 --- a/docs/package.json +++ b/docs/package.json @@ -6,7 +6,8 @@ "docusaurus": "docusaurus", "docs": "docusaurus start", "start": "docusaurus start", - "build": "docusaurus build", + "build": "docusaurus build && node scripts/flatten-llms-tabs.mjs", + "test": "node --test \"scripts/*.test.mjs\"", "swizzle": "docusaurus swizzle", "deploy": "docusaurus deploy", "clear": "docusaurus clear", diff --git a/docs/scripts/flatten-llms-tabs.mjs b/docs/scripts/flatten-llms-tabs.mjs new file mode 100644 index 000000000..67802567e --- /dev/null +++ b/docs/scripts/flatten-llms-tabs.mjs @@ -0,0 +1,162 @@ +#!/usr/bin/env node +/** + * Flatten MDX tab JSX in the generated LLM artifacts. + * + * `docusaurus-plugin-llms` reads the *source* markdown, not the rendered HTML, + * and its only cleanup (`cleanMarkdownContent`) strips a fixed allowlist of + * plain HTML tags. `` / `` are not in that list and its options + * expose no transform hook, so tab JSX lands verbatim in llms.txt, + * llms-full.txt and every per-page .md twin. + * + * This runs after `docusaurus build` and rewrites those artifacts only — the + * HTML site is untouched. It cannot be a Docusaurus plugin: core runs every + * plugin's `postBuild` under `Promise.all`, so a sibling plugin would race + * docusaurus-plugin-llms nondeterministically. + * + * Two transforms, because there are two kinds of tabs: + * + * 1. `` — four *equivalent* commands. + * Collapse to a single fenced pnpm block. What an agent copies out of + * llms.txt has to match what a reader sees on the default tab, and pnpm is + * the default tab. + * + * 2. `` / `` — *complementary* content (the skills + * pages tab between ProfileCard.tsx, _profilecard.scss and Usage). Keep + * every body and promote the label to a heading. Keeping only the first + * tab here would silently delete documentation. + * + * Both transforms run only outside code — see `outsideCode` for why that is not + * optional. + */ +import { readFile, writeFile, readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +/** Heading level that a flattened `` is promoted to. */ +const TAB_HEADING = '####'; + +/** Sentinel wrapping masked code so a placeholder can never occur in prose. */ +const NUL = String.fromCharCode(0); + +/** + * `command` is authored in pnpm's verb vocabulary (`add`, `create`, `dlx`), so + * this is a passthrough. The npm/yarn/bun translations live in the React + * component; duplicating them here would be a second source of truth. + */ +const toPnpm = command => `pnpm ${command}`.replace(/\s+/g, ' ').trim(); + +/** + * Quoted `command` only. A braced template — command={`add foo`} — is not + * supported on purpose: its backticks are indistinguishable from an inline code + * span, and code masking has to run first (see `outsideCode`), so the attribute + * would be masked before this ever saw it. Author the prop as a plain string. + */ +function flattenPackageManagerTabs(src) { + return src.replace( + /]*?\bcommand=(?:"([^"]*)"|'([^']*)')[^>]*?\/>/g, + (_match, dq, sq) => '```bash\n' + toPnpm((dq ?? sq).trim()) + '\n```' + ); +} + +function attrLabel(attrs) { + for (const key of ['label', 'value']) { + const m = attrs.match(new RegExp(`\\b${key}=(?:"([^"]*)"|'([^']*)')`)); + if (m) return m[1] ?? m[2] ?? ''; + } + return ''; +} + +function flattenGenericTabs(src) { + // `])`, never ``, which + // is bestax-bulma's own Tabs component as documented in docs/api/components. + return src.replace(/])[^>]*>([\s\S]*?)<\/Tabs>/g, (_m, inner) => { + const items = [ + ...inner.matchAll(/]*)>([\s\S]*?)<\/TabItem>/g), + ]; + if (items.length === 0) return inner.trim(); + return items + .map(([, attrs, body]) => { + const label = attrLabel(attrs); + const text = body.trim(); + return label ? `${TAB_HEADING} ${label}\n\n${text}` : text; + }) + .join('\n\n'); + }); +} + +/** + * Apply `fn` only outside code — fenced blocks *and* inline spans. + * + * Both exclusions are load-bearing: `docs/api/components/tabs.md` documents + * bestax-bulma's own `` / `` inside tsx fences, and the + * migration guides mention the Tabs component inline in prose. Neither is a + * Docusaurus theme tab and neither may be rewritten. + * + * Mask rather than split: a `` block *wraps* fenced code, so the document + * has to stay contiguous for `…` to match across it. + */ +function outsideCode(src, fn) { + const held = []; + const hold = chunk => { + held.push(chunk); + return NUL + (held.length - 1) + NUL; + }; + + const masked = src + .replace(/^```[\s\S]*?^```$/gm, hold) // fenced blocks + .replace(/(`+)(?:(?!\1)[^\n])*?\1/g, hold); // inline spans, single line only + + const restore = new RegExp(NUL + '(\\d+)' + NUL, 'g'); + return fn(masked).replace(restore, (_m, i) => held[Number(i)]); +} + +/** Rewrite one artifact's contents. Idempotent. */ +export function transform(src) { + return outsideCode(src, chunk => + flattenGenericTabs(flattenPackageManagerTabs(chunk)) + ) + .replace(/^\s*import\s+(?:Tabs|TabItem|PackageManagerTabs)\b.*$/gm, '') + .replace(/\n{3,}/g, '\n\n'); +} + +/** True when a file is one of the artifacts this script owns. */ +export function isLlmArtifact(file) { + const base = path.basename(file); + if (base.endsWith('.md')) return true; + return base.endsWith('.txt') && base.startsWith('llms'); +} + +async function* walk(dir) { + for (const entry of await readdir(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) yield* walk(full); + else yield full; + } +} + +async function main(buildDir) { + let changed = 0; + for await (const file of walk(buildDir)) { + if (!isLlmArtifact(file)) continue; + const before = await readFile(file, 'utf8'); + if (!/ { + console.error(`flatten-llms-tabs: ${error.message}`); + process.exitCode = 1; + }); +} diff --git a/docs/scripts/flatten-llms-tabs.test.mjs b/docs/scripts/flatten-llms-tabs.test.mjs new file mode 100644 index 000000000..63c4d4540 --- /dev/null +++ b/docs/scripts/flatten-llms-tabs.test.mjs @@ -0,0 +1,170 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { transform, isLlmArtifact } from './flatten-llms-tabs.mjs'; + +const fence = (lang, body) => '```' + lang + '\n' + body + '\n```'; + +test('PackageManagerTabs collapses to a single pnpm block', () => { + const out = transform( + '' + ); + assert.equal(out.trim(), fence('bash', 'pnpm add @allxsmith/bestax-bulma')); +}); + +test('PackageManagerTabs passes the pnpm verb vocabulary through', () => { + for (const [command, expected] of [ + ['create bestax@latest my-app', 'pnpm create bestax@latest my-app'], + [ + 'dlx create-next-app@latest my-app', + 'pnpm dlx create-next-app@latest my-app', + ], + ['add -D typescript', 'pnpm add -D typescript'], + ['install', 'pnpm install'], + ]) { + const out = transform(``); + assert.equal(out.trim(), fence('bash', expected)); + } +}); + +test('PackageManagerTabs accepts a single-quoted command', () => { + assert.match( + transform(""), + /pnpm add foo/ + ); +}); + +test('a braced-template command is left alone, by design', () => { + // Its backticks are indistinguishable from an inline code span, and masking + // has to run first. Authors use a plain string; this asserts we fail loudly + // (untouched JSX in the artifact) rather than silently mangling it. + const src = ''; + assert.equal(transform(src), src); +}); + +test('generic Tabs keep every body and promote labels to headings', () => { + const src = [ + '', + '', + '', + fence('tsx', 'const x = 1;'), + '', + '', + '', + '', + fence('tsx', 'const y = 2;'), + '', + '', + '', + ].join('\n'); + + const out = transform(src); + + // Complementary content — dropping non-first tabs would delete documentation. + assert.match(out, /^#### ProfileCard\.tsx$/m); + assert.match(out, /^#### Usage$/m); + assert.match(out, /const x = 1;/); + assert.match(out, /const y = 2;/); + assert.doesNotMatch(out, / { + const src = '\n\n\nbody\n\n\n'; + assert.match(transform(src), /^#### scss$/m); +}); + +test("bestax-bulma's own Tabs component survives inside fences", () => { + // Regression: `', + ' Home', + '', + ].join('\n') + ), + ].join('\n'); + + assert.equal(transform(src), src); +}); + +test('Tabs mentioned in inline code spans in prose survive', () => { + const src = + 'You can use helper props with `` and its subcomponents.\n\n' + + 'The legacy `` API is preserved, and `` now provides context.'; + + assert.equal(transform(src), src); +}); + +test('a fenced Tabs example is not flattened by a later real Tabs block', () => { + const src = [ + fence('mdx', '\nx\n'), + '', + '', + 'real body', + '', + ].join('\n'); + + const out = transform(src); + + assert.match( + out, + /```mdx\n\nx<\/TabItem>\n<\/Tabs>\n```/ + ); + assert.match(out, /^#### Real$/m); + assert.match(out, /real body/); +}); + +test('orphaned tab imports are dropped', () => { + const src = [ + "import Tabs from '@theme/Tabs';", + "import TabItem from '@theme/TabItem';", + "import PackageManagerTabs from '@site/src/components/PackageManagerTabs';", + "import { ExampleMeta } from '@site/src/components/SkillExamples';", + '', + '# Title', + ].join('\n'); + + const out = transform(src); + + assert.doesNotMatch(out, /@theme\/Tabs|@theme\/TabItem|PackageManagerTabs/); + // Unrelated imports are left alone — the llms plugin owns that stripping. + assert.match(out, /ExampleMeta/); +}); + +test('transform is idempotent', () => { + const src = [ + '', + '', + '', + '', + '', + fence('ts', 'const a = 1;'), + '', + '', + '', + '', + 'Prose about `` stays put.', + ].join('\n'); + + const once = transform(src); + assert.equal(transform(once), once); +}); + +test('content is never lost to placeholder collisions', () => { + // Masked code is NUL-delimited, so digit runs in prose cannot be mistaken + // for a placeholder on restore. + const src = 'Release 5 8 0 shipped.\n\n' + fence('bash', 'pnpm add foo'); + assert.equal(transform(src), src); +}); + +test('isLlmArtifact selects .md twins and llms*.txt only', () => { + assert.equal(isLlmArtifact('build/docs/guides/intro.md'), true); + assert.equal(isLlmArtifact('build/llms.txt'), true); + assert.equal(isLlmArtifact('build/llms-full.txt'), true); + assert.equal(isLlmArtifact('build/robots.txt'), false); + assert.equal(isLlmArtifact('build/assets/js/main.js'), false); + assert.equal(isLlmArtifact('build/index.html'), false); +}); From 867b0e24836367cc51f84d3962bb1d69fcadc474 Mon Sep 17 00:00:00 2001 From: Alex Smith Date: Wed, 29 Jul 2026 07:22:32 -0400 Subject: [PATCH 2/2] =?UTF-8?q?chore(docs):=20address=20review=20=E2=80=94?= =?UTF-8?q?=20CommonMark=20fence=20scanner,=20cleanup=20inside=20mask?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from the CodeRabbit review of #408: 1. Masking only recognised exact triple-backtick fences. Tilde fences and longer fences went unprotected. Replaced the regex with a line-based CommonMark scanner: either fence character, length >= 3, closing fence the same character and at least as long, up to 3 leading spaces, and a backtick info string may not contain backticks. An unterminated fence now runs to end of document and is masked rather than rewritten. Reproduced for tilde fences, which the old code mutated. The longer fence case in docs/api/helpers/theme.md and tutorial-basics did not reproduce as an observable defect, but the scanner removes the class. Multiline inline spans are still matched single-line on purpose: an unpaired backtick in prose would otherwise swallow the document. 2. Import removal and blank-line collapsing ran after held code was restored, so they reached into fenced examples — stripping `import Tabs …` demo lines and collapsing deliberate blank lines in code blocks. Both reproduced; both now run inside the mask. 3. The main() prefilter skipped artifacts carrying only tab imports, which transform() would still have cleaned. Shared as NEEDS_FLATTENING so the predicate and the transform agree. 21 tests, up from 13. Output over the current build/ is byte-identical to the pre-fix run — 0 theme tabs outside code, 19 preserved, api/components/tabs.md unchanged, idempotent — so this closes latent edge cases without moving real-world output. --- docs/scripts/flatten-llms-tabs.mjs | 91 +++++++++++++++++++++-- docs/scripts/flatten-llms-tabs.test.mjs | 97 ++++++++++++++++++++++++- 2 files changed, 179 insertions(+), 9 deletions(-) diff --git a/docs/scripts/flatten-llms-tabs.mjs b/docs/scripts/flatten-llms-tabs.mjs index 67802567e..c4d96ca36 100644 --- a/docs/scripts/flatten-llms-tabs.mjs +++ b/docs/scripts/flatten-llms-tabs.mjs @@ -95,6 +95,66 @@ function flattenGenericTabs(src) { * Mask rather than split: a `` block *wraps* fenced code, so the document * has to stay contiguous for `…` to match across it. */ +/** + * Mask fenced code blocks, per CommonMark rather than by regex. + * + * A regex can't do this: fences are variable-length and come in two characters, + * and the closing fence only has to be *at least* as long as the opening one. + * `docs/api/helpers/theme.md` and `docs/tutorial-basics/markdown-features.mdx` + * both wrap ``` examples in ```` fences, so mis-pairing is not hypothetical. + */ +function maskFences(src, hold) { + const out = []; + let open = null; + let buf = []; + + for (const line of src.split('\n')) { + const fence = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/); + + if (!open) { + // A backtick fence's info string may not itself contain a backtick. + const validOpen = + fence && !(fence[1][0] === '`' && fence[2].includes('`')); + if (validOpen) { + open = { char: fence[1][0], len: fence[1].length }; + buf = [line]; + } else { + out.push(line); + } + continue; + } + + buf.push(line); + const close = line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/); + if (close && close[1][0] === open.char && close[1].length >= open.len) { + out.push(hold(buf.join('\n'))); + open = null; + buf = []; + } + } + + // An unterminated fence runs to end of document (CommonMark). Mask it: never + // mutate content we can't confidently parse. + if (open) out.push(hold(buf.join('\n'))); + + return out.join('\n'); +} + +/** + * Apply `fn` only outside code — fenced blocks *and* inline spans. + * + * Both exclusions are load-bearing: `docs/api/components/tabs.md` documents + * bestax-bulma's own `` / `` inside tsx fences, and the + * migration guides mention the Tabs component inline in prose. Neither is a + * Docusaurus theme tab and neither may be rewritten. + * + * Mask rather than split: a `` block *wraps* fenced code, so the document + * has to stay contiguous for `…` to match across it. + * + * Inline spans are matched single-line only. CommonMark allows one to wrap, but + * an unpaired backtick in prose would then swallow the rest of the document — + * the failure mode of guessing wrong here is much worse than the miss. + */ function outsideCode(src, fn) { const held = []; const hold = chunk => { @@ -102,23 +162,38 @@ function outsideCode(src, fn) { return NUL + (held.length - 1) + NUL; }; - const masked = src - .replace(/^```[\s\S]*?^```$/gm, hold) // fenced blocks - .replace(/(`+)(?:(?!\1)[^\n])*?\1/g, hold); // inline spans, single line only + const masked = maskFences(src, hold).replace( + /(`+)(?:(?!\1)[^\n])*?\1/g, + hold + ); const restore = new RegExp(NUL + '(\\d+)' + NUL, 'g'); return fn(masked).replace(restore, (_m, i) => held[Number(i)]); } -/** Rewrite one artifact's contents. Idempotent. */ +/** + * Rewrite one artifact's contents. Idempotent. + * + * Every rewrite happens inside `outsideCode` — including the import and blank + * line cleanup. Running those after restoration would reach into fenced code and + * strip `import Tabs …` lines out of examples, or collapse deliberate blank + * lines in a code block. + */ export function transform(src) { return outsideCode(src, chunk => flattenGenericTabs(flattenPackageManagerTabs(chunk)) - ) - .replace(/^\s*import\s+(?:Tabs|TabItem|PackageManagerTabs)\b.*$/gm, '') - .replace(/\n{3,}/g, '\n\n'); + .replace(/^[ \t]*import\s+(?:Tabs|TabItem|PackageManagerTabs)\b.*$/gm, '') + .replace(/\n{3,}/g, '\n\n') + ); } +/** + * Cheap prefilter for `main`. Matches the imports too — `transform` strips + * orphaned tab imports, so an artifact carrying only those still has work to do. + */ +export const NEEDS_FLATTENING = + / '```' + lang + '\n' + body + '\n```'; @@ -160,6 +164,97 @@ test('content is never lost to placeholder collisions', () => { assert.equal(transform(src), src); }); +test('a longer fence wrapping shorter fences is masked as one block', () => { + // Real shape: docs/api/helpers/theme.md and tutorial-basics/markdown-features + // wrap ``` examples in ```` fences. Mis-pairing here shifts every mask + // boundary after it in llms-full.txt. + const src = [ + '````md', + '```tsx', + '', + 'not a real tab', + '', + '```', + '````', + '', + '', + 'real body', + '', + ].join('\n'); + + const out = transform(src); + + assert.match(out, /````md\n```tsx\n\n/); + assert.match(out, /^#### Real$/m); + assert.doesNotMatch(out, /#### Nope/); +}); + +test('tilde fences are masked', () => { + const src = [ + '~~~tsx', + '', + 'y', + '', + '~~~', + ].join('\n'); + assert.equal(transform(src), src); +}); + +test('a tilde fence is not closed by a backtick fence', () => { + const src = [ + '~~~md', + '```', + 'still inside the tilde fence', + '```', + '~~~', + ].join('\n'); + assert.equal(transform(src), src); +}); + +test('an indented fence (up to 3 spaces) still opens a block', () => { + const src = [' ```tsx', ' x', ' ```'].join('\n'); + assert.equal(transform(src), src); +}); + +test('imports inside a fenced example are preserved', () => { + // Regression: the cleanup used to run after code was restored, so a fenced + // example demonstrating the import lost the line. + const src = [ + 'Import it first:', + '', + fence( + 'tsx', + "import Tabs from '@theme/Tabs';\n\nexport default function Demo() {}" + ), + ].join('\n'); + + assert.equal(transform(src), src); +}); + +test('deliberate blank lines inside a fence are preserved', () => { + const src = [ + '', + '', + fence('ts', 'const a = 1;\n\n\nconst b = 2;'), + ].join('\n'); + + const out = transform(src); + + assert.match(out, /const a = 1;\n\n\nconst b = 2;/); + assert.match(out, /pnpm add foo/); +}); + +test('an unterminated fence is masked rather than rewritten', () => { + const src = ['```tsx', '', 'y'].join('\n'); + assert.equal(transform(src), src); +}); + +test('NEEDS_FLATTENING matches import-only artifacts', () => { + assert.equal(NEEDS_FLATTENING.test("import Tabs from '@theme/Tabs';"), true); + assert.equal(NEEDS_FLATTENING.test(''), true); + assert.equal(NEEDS_FLATTENING.test('# Just a heading'), false); +}); + test('isLlmArtifact selects .md twins and llms*.txt only', () => { assert.equal(isLlmArtifact('build/docs/guides/intro.md'), true); assert.equal(isLlmArtifact('build/llms.txt'), true);