@writedocs/generator 0.21.0 → 0.22.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/astro.config.mjs CHANGED
@@ -36,12 +36,14 @@ import { iconDataFromFile } from './src/lib/icon-data-dev.js';
36
36
  import { canonicalPath } from './src/lib/canonical-path.js';
37
37
  import { withBase, withoutBase } from './src/lib/base-path.js';
38
38
  import { folderAddresses } from './src/lib/folder-redirects.js';
39
+ import { pageTags, TAGS_PATH } from './src/lib/tags.js';
39
40
  import { report } from './packages/components/src/lib/cli-report.js';
40
41
  import { publishProjectFiles, generatedRobotsTxt } from './src/lib/project-files-integration.js';
41
42
  import { frontmatterNoindex, canonicalIsElsewhere } from './src/lib/seo-tags.js';
42
43
  import { readMovedApiPages } from './src/lib/moved-api-pages.js';
43
44
  import { rehypeImageLoading } from './src/lib/rehype-image-loading.js';
44
45
  import { rehypeBasePath } from './src/lib/rehype-base-path.js';
46
+ import { rehypeTaskLists } from './src/lib/rehype-task-lists.js';
45
47
  import { gitLastModified, newestDate } from './src/lib/last-modified.js';
46
48
  import { readSpecPaths } from './src/lib/project-files.js';
47
49
  import { protectedPages } from './src/lib/protected-sections.js';
@@ -171,6 +173,8 @@ function collectNoindexIds(rootContentDir) {
171
173
  // redirect-only route [...slug].astro synthesizes (noindex, pointing at
172
174
  // the first page) - which doesn't belong in the sitemap either.
173
175
  let rootIsPage = false;
176
+ // Whether a page has `tags` - see the folders below.
177
+ let hasTags = false;
174
178
  const pageIds = [];
175
179
  // When each page last changed, for <lastmod> - see lib/last-modified.js.
176
180
  const fileDates = gitLastModified(rootContentDir);
@@ -186,6 +190,7 @@ function collectNoindexIds(rootContentDir) {
186
190
  const { data } = matter(fs.readFileSync(file, 'utf-8'));
187
191
  const pageId = normalizeEntryId(data?.slug ?? relativeId.replace(/\.mdx?$/i, '').replace(/\/index$/, ''));
188
192
  if (pageId === 'index') rootIsPage = true;
193
+ if (pageTags(data?.tags).length > 0) hasTags = true;
189
194
  pageIds.push(pageId);
190
195
  const changed = fileDates?.get(relativeId.split(path.sep).join('/'));
191
196
  if (changed) lastModifiedById.set(pageId, changed);
@@ -218,7 +223,12 @@ function collectNoindexIds(rootContentDir) {
218
223
  if (!rootIsPage) ids.add('index');
219
224
  // Folder addresses with no page of their own redirect to one under them
220
225
  // (lib/folder-redirects.js) - redirects, so not in the sitemap either.
221
- for (const folder of folderAddresses(pageIds)) ids.add(folder);
226
+ // Except /tags/ on a site with tags, where it's the list of tags
227
+ // (lib/tags.js) - [...slug].astro makes no folder redirect there. Read
228
+ // from the frontmatter alone: a site whose only tagged pages are
229
+ // protected or hidden has no list of tags (lib/tag-index.ts), and its
230
+ // /tags/ redirect - if it has pages under tags/ - is then in the sitemap.
231
+ for (const folder of folderAddresses(pageIds)) if (!(hasTags && folder === TAGS_PATH)) ids.add(folder);
222
232
  return ids;
223
233
  }
224
234
 
@@ -528,10 +538,12 @@ export default defineConfig({
528
538
  // neither plugin's output is visible to the other.
529
539
  // rehypeImageLoading: lazy loading and sizes for content images - see
530
540
  // lib/rehype-image-loading.js.
541
+ // rehypeTaskLists: `- [ ] item` boxes a reader can tick - see
542
+ // lib/rehype-task-lists.js.
531
543
  // rehypeBasePath: the basePath in front of the content's own links and
532
544
  // pictures (lib/rehype-base-path.js) - last, since rehypeImageLoading
533
545
  // finds an image's file by the address as written.
534
- rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }], [rehypeBasePath, { base: basePath }]],
546
+ rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }], rehypeTaskLists, [rehypeBasePath, { base: basePath }]],
535
547
  }),
536
548
  shikiConfig: {
537
549
  themes: codeblockTheme,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Static site generator for docs — a writedocs.json + MDX folder in, a static site out.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,8 +1,18 @@
1
- // A string prop rendered with the small subset of inline Markdown Mintlify
2
- // allows in some component props (Tile's `title`, Prompt's `description`,
3
- // Color.Row's `title`): `code`, **bold**, and *italic* / _italic_. The
4
- // input is HTML-escaped first, so this is always safe to hand to set:html -
5
- // nothing in a prop value can produce markup other than these three.
1
+ // A string rendered with the small subset of inline Markdown Mintlify allows
2
+ // in some component props (Tile's `title`, Prompt's `description`,
3
+ // Color.Row's `title`) - and that writedocs allows in a page's frontmatter
4
+ // `title`: `code`, **bold**, and *italic* / _italic_. The input is
5
+ // HTML-escaped first, so this is always safe to hand to set:html - nothing
6
+ // in a value can produce markup other than these three.
7
+ //
8
+ // Emphasis follows CommonMark's flanking rule closely enough for titles: the
9
+ // marker has to touch the text it wraps - `*x*` is italic, `2 * 3 * 4` and
10
+ // `*args and **kwargs` stay as written - and `_` only counts at a word's
11
+ // edge, so `snake_case_name` and `__init__` stay too.
12
+ //
13
+ // inlineMarkdownText() is the same value as plain text - the markers gone,
14
+ // nothing escaped - for wherever no markup can go: a page's <title>, its
15
+ // sidebar entry, search results.
6
16
 
7
17
  function escapeHtml(value) {
8
18
  return value
@@ -13,6 +23,15 @@ function escapeHtml(value) {
13
23
  .replace(/'/g, '&#39;');
14
24
  }
15
25
 
26
+ function unescapeHtml(value) {
27
+ return value
28
+ .replace(/&lt;/g, '<')
29
+ .replace(/&gt;/g, '>')
30
+ .replace(/&quot;/g, '"')
31
+ .replace(/&#39;/g, "'")
32
+ .replace(/&amp;/g, '&');
33
+ }
34
+
16
35
  export function inlineMarkdown(value) {
17
36
  if (!value) return '';
18
37
  // Code spans first, and set aside, so ** or _ inside them stay literal.
@@ -22,8 +41,15 @@ export function inlineMarkdown(value) {
22
41
  return `\u0000${codeSpans.length - 1}\u0000`;
23
42
  });
24
43
  html = html
25
- .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
26
- .replace(/(^|[^\w*])\*([^*]+)\*(?!\w)/g, '$1<em>$2</em>')
27
- .replace(/(^|[^\w])_([^_]+)_(?!\w)/g, '$1<em>$2</em>');
44
+ .replace(/\*\*(?=[^\s*])([^*]*?[^\s*])\*\*/g, '<strong>$1</strong>')
45
+ .replace(/(^|[^\w*])\*(?=[^\s*])([^*]*?[^\s*])\*(?![\w*])/g, '$1<em>$2</em>')
46
+ .replace(/(^|[^\w])_(?=[^\s_])([^_]*?[^\s_])_(?!\w)/g, '$1<em>$2</em>');
28
47
  return html.replace(/\u0000(\d+)\u0000/g, (_, i) => codeSpans[Number(i)]);
29
48
  }
49
+
50
+ /** The same value as plain text: what inlineMarkdown() shows, without the
51
+ * markup. A value with no Markdown in it comes back as it is. */
52
+ export function inlineMarkdownText(value) {
53
+ if (!value) return '';
54
+ return unescapeHtml(inlineMarkdown(value).replace(/<\/?(?:code|strong|em)>/g, ''));
55
+ }
@@ -848,6 +848,7 @@ const fontExtraCss = [fontFaceCss, fontFallbackCss, fontWeightCss].filter(Boolea
848
848
  <script>
849
849
  import { initBanner } from "../scripts/banner";
850
850
  import { initTopbarOffset } from "../scripts/topbar-offset";
851
+ import { initTaskLists } from "../scripts/task-lists";
851
852
 
852
853
  initBanner(document);
853
854
  document.addEventListener("astro:page-load", () => initBanner(document));
@@ -857,6 +858,11 @@ const fontExtraCss = [fontFaceCss, fontFallbackCss, fontWeightCss].filter(Boolea
857
858
  // why that's live-measured rather than a fixed CSS value.
858
859
  initTopbarOffset();
859
860
  document.addEventListener("astro:page-load", () => initTopbarOffset());
861
+
862
+ // Remembers what a reader ticked in the page's task lists - see
863
+ // task-lists.ts. Again after a swap: the new page has its own boxes.
864
+ initTaskLists(document);
865
+ document.addEventListener("astro:page-load", () => initTaskLists(document));
860
866
  </script>
861
867
  {
862
868
  /* writedocs.json's `scripts.body` - see scriptEntrySchema in lib/config.ts.
@@ -297,3 +297,105 @@ pre {
297
297
  scrollbar-color: var(--wd-scrollbar-thumb-near) transparent;
298
298
  }
299
299
  }
300
+
301
+ /* Task lists - `- [ ] item` (lib/rehype-task-lists.js makes the boxes
302
+ tickable, scripts/task-lists.ts remembers them). In a bulleted list a task
303
+ item has no bullet: its box sits where the bullet was, so the text lines
304
+ up with the list's other items. A numbered list keeps its numbers, with
305
+ the box after. The label is the box and the item's text - clicking either
306
+ ticks it. */
307
+ .wd-article ul > li.task-list-item {
308
+ list-style: none;
309
+ }
310
+ .wd-article li.task-list-item input[type="checkbox"] {
311
+ width: 1rem;
312
+ height: 1rem;
313
+ /* A little room after a numbered list's number; a bulleted list's box
314
+ moves into the bullet's place (below). */
315
+ margin: 0 0.4rem 0 0.25rem;
316
+ vertical-align: -0.15em;
317
+ accent-color: var(--wd-primary);
318
+ cursor: pointer;
319
+ }
320
+ .wd-article ul > li.task-list-item > label > input[type="checkbox"],
321
+ .wd-article ul > li.task-list-item > p > label > input[type="checkbox"] {
322
+ margin-left: -1.4rem;
323
+ }
324
+ .wd-article label.wd-task {
325
+ cursor: pointer;
326
+ transition: color 0.15s ease;
327
+ }
328
+ /* A ticked item's text is muted - what's done steps back from what's left.
329
+ Bold and code in it follow (their own color is the heading's); a link
330
+ keeps its color, to still read as one. :has() works without the script,
331
+ for a tick a reader makes or one remembered (task-lists.ts). Dimmed
332
+ from the text's own color toward the page's, not --wd-text-muted: in dark
333
+ mode the body text already is that color. */
334
+ .wd-article label.wd-task:has(> input:checked) {
335
+ color: color-mix(in srgb, currentColor 55%, var(--wd-background));
336
+ }
337
+ .wd-article label.wd-task:has(> input:checked) :is(strong, b, em, code) {
338
+ color: inherit;
339
+ }
340
+
341
+ /* Page tags - frontmatter `tags` (lib/tags.js): the row under a page
342
+ ([...slug].astro) and the list of tags (src/pages/tags/[...tag].astro).
343
+ A tag with a page is a link; one without (lib/tag-index.ts) is the same
344
+ pill, not clickable. */
345
+ .wd-page-tags {
346
+ display: flex;
347
+ flex-wrap: wrap;
348
+ align-items: baseline;
349
+ gap: 0.5rem 0.75rem;
350
+ margin: 2.5rem 0 0;
351
+ }
352
+ .wd-page-tags-label {
353
+ font-size: 0.85rem;
354
+ font-weight: 600;
355
+ color: var(--wd-text-muted);
356
+ }
357
+ .wd-page-tags-list {
358
+ display: flex;
359
+ flex-wrap: wrap;
360
+ gap: 0.4rem;
361
+ margin: 0;
362
+ padding: 0;
363
+ list-style: none;
364
+ }
365
+ .wd-article .wd-page-tags-list > li {
366
+ margin: 0;
367
+ }
368
+ .wd-tag {
369
+ display: inline-flex;
370
+ align-items: center;
371
+ padding: 0.2rem 0.65rem;
372
+ border: 1px solid var(--wd-border);
373
+ border-radius: 999px;
374
+ font-size: 0.82rem;
375
+ line-height: 1.4;
376
+ color: var(--wd-text);
377
+ text-decoration: none;
378
+ background: var(--wd-surface);
379
+ }
380
+ a.wd-tag {
381
+ transition: border-color 0.15s ease, color 0.15s ease;
382
+ }
383
+ /* Not the underline of a link in an article's list ([...slug].astro's
384
+ `.wd-article li a`). */
385
+ .wd-article a.wd-tag {
386
+ text-decoration: none;
387
+ }
388
+ a.wd-tag:hover,
389
+ a.wd-tag:focus-visible {
390
+ border-color: var(--wd-primary);
391
+ color: var(--wd-primary);
392
+ }
393
+
394
+ /* `code` in a page's title (frontmatter `title`'s inline Markdown -
395
+ [...slug].astro): a little smaller than the heading's letters, and a title
396
+ that wraps gives each line its own complete box. */
397
+ .wd-article-header h1 code {
398
+ font-size: 0.88em;
399
+ -webkit-box-decoration-break: clone;
400
+ box-decoration-break: clone;
401
+ }
@@ -3,6 +3,7 @@ import { findNodeAtLocation, parseTree, visit } from "jsonc-parser";
3
3
  import { BASE_PATH_FIELD_PATTERN } from "./base-path.js";
4
4
  import { stripBom } from "./bom.js";
5
5
  import { scalarGroups, scalarPathPrefix, scalarRootPathMessage } from "./scalar-path.js";
6
+ import { inlineMarkdownText } from "../../packages/components/src/lib/inline-markdown.js";
6
7
  const navPageSchema = z.string();
7
8
  const navGroupPagesSchema = z.lazy(
8
9
  () => z.object({
@@ -438,6 +439,17 @@ function mergeSeo(site, page = {}) {
438
439
  };
439
440
  }
440
441
  const MINTLIFY_MODE_ALIASES = { center: "frame", assistant: "default" };
442
+ function withPlainTitles(data) {
443
+ const title = inlineMarkdownText(data.title);
444
+ const sidebarTitle = data.sidebarTitle === void 0 ? void 0 : inlineMarkdownText(data.sidebarTitle);
445
+ if (title === data.title && sidebarTitle === data.sidebarTitle) return data;
446
+ return {
447
+ ...data,
448
+ title,
449
+ ...sidebarTitle === void 0 ? {} : { sidebarTitle },
450
+ ...title === data.title ? {} : { titleMarkdown: data.title }
451
+ };
452
+ }
441
453
  const pageFrontmatterSchema = z.object({
442
454
  title: z.string(),
443
455
  description: z.string().optional(),
@@ -547,6 +559,12 @@ const pageFrontmatterSchema = z.object({
547
559
  url: z.string().optional(),
548
560
  hideFooterPagination: z.boolean().optional(),
549
561
  hideApiMarker: z.boolean().optional(),
562
+ // Docusaurus' page tags: shown at the bottom of the page, each linking to
563
+ // a page listing every page with it (`/tags/<tag>/`; `/tags/` lists them
564
+ // all). A tag is a name, or Docusaurus' `{ label, permalink }` - the
565
+ // permalink sets its address. Not `tag` above, Mintlify's sidebar label.
566
+ // See lib/tags.js and lib/tag-index.ts.
567
+ tags: z.array(z.union([z.string(), z.object({ label: z.string(), permalink: z.string().optional() })])).optional(),
550
568
  // Docusaurus' key: a draft isn't part of the site `writedocs build`
551
569
  // makes - no route, no navigation entry, not in search, the sitemap,
552
570
  // llms.txt or the MCP index (lib/drafts.js). `writedocs dev` and
@@ -581,7 +599,7 @@ const pageFrontmatterSchema = z.object({
581
599
  seo.robots = "noindex, nofollow";
582
600
  changed = true;
583
601
  }
584
- return changed ? { ...data, seo } : data;
602
+ return withPlainTitles(changed ? { ...data, seo } : data);
585
603
  }
586
604
  );
587
605
  const apiSchema = z.object({
@@ -42,6 +42,9 @@ import { stripBom } from './bom.js';
42
42
  // Where a "scalar" OpenAPI group's reference may go, worded as the build
43
43
  // words it - lib/scalar-path.js. Plain JS with no `node:` import too.
44
44
  import { scalarGroups, scalarPathPrefix, scalarRootPathMessage } from './scalar-path.js';
45
+ // A page title's inline Markdown, as plain text - the components package's
46
+ // lib/inline-markdown.js. Plain JS with no import at all.
47
+ import { inlineMarkdownText } from '../../packages/components/src/lib/inline-markdown.js';
45
48
 
46
49
  // ---------------------------------------------------------------------
47
50
  // Pages & groups - the leaf content any container ultimately bottoms out
@@ -829,6 +832,26 @@ export function mergeSeo(site: SeoFields, page: SeoFields = {}): SeoFields {
829
832
 
830
833
  const MINTLIFY_MODE_ALIASES: Record<string, string> = { center: 'frame', assistant: 'default' };
831
834
 
835
+ /** A page's `title` may have inline Markdown - `code`, **bold**, *italic*
836
+ * (lib/inline-markdown.js in the components package). Only the page's <h1>
837
+ * shows it ([...slug].astro, from `titleMarkdown`); everywhere else - the
838
+ * sidebar, <title>, search, breadcrumbs, prev/next, link previews,
839
+ * llms.txt, the tag pages - reads `title`, which is made plain text here,
840
+ * once, so none of them has to. `sidebarTitle` is only ever shown plain,
841
+ * so it's made plain text too. `titleMarkdown` is only there when the
842
+ * title has Markdown in it. */
843
+ function withPlainTitles<T extends { title: string; sidebarTitle?: string }>(data: T): T & { titleMarkdown?: string } {
844
+ const title = inlineMarkdownText(data.title);
845
+ const sidebarTitle = data.sidebarTitle === undefined ? undefined : inlineMarkdownText(data.sidebarTitle);
846
+ if (title === data.title && sidebarTitle === data.sidebarTitle) return data;
847
+ return {
848
+ ...data,
849
+ title,
850
+ ...(sidebarTitle === undefined ? {} : { sidebarTitle }),
851
+ ...(title === data.title ? {} : { titleMarkdown: data.title }),
852
+ };
853
+ }
854
+
832
855
  /** A page's own frontmatter - the `pages` and `generatedDocs` content
833
856
  * collections' schema (content.config.ts), and what `writedocs validate`
834
857
  * checks every page against. */
@@ -943,6 +966,14 @@ export const pageFrontmatterSchema = z.object({
943
966
  url: z.string().optional(),
944
967
  hideFooterPagination: z.boolean().optional(),
945
968
  hideApiMarker: z.boolean().optional(),
969
+ // Docusaurus' page tags: shown at the bottom of the page, each linking to
970
+ // a page listing every page with it (`/tags/<tag>/`; `/tags/` lists them
971
+ // all). A tag is a name, or Docusaurus' `{ label, permalink }` - the
972
+ // permalink sets its address. Not `tag` above, Mintlify's sidebar label.
973
+ // See lib/tags.js and lib/tag-index.ts.
974
+ tags: z
975
+ .array(z.union([z.string(), z.object({ label: z.string(), permalink: z.string().optional() })]))
976
+ .optional(),
946
977
  // Docusaurus' key: a draft isn't part of the site `writedocs build`
947
978
  // makes - no route, no navigation entry, not in search, the sitemap,
948
979
  // llms.txt or the MCP index (lib/drafts.js). `writedocs dev` and
@@ -986,7 +1017,7 @@ export const pageFrontmatterSchema = z.object({
986
1017
  seo.robots = 'noindex, nofollow';
987
1018
  changed = true;
988
1019
  }
989
- return changed ? { ...data, seo } : data;
1020
+ return withPlainTitles(changed ? { ...data, seo } : data);
990
1021
  },
991
1022
  );
992
1023
 
@@ -44,6 +44,7 @@ import { isPublishedFile, readSpecPaths } from './project-files.js';
44
44
  import { projectIgnore } from './project-ignore.js';
45
45
  import { readMovedApiPages } from './moved-api-pages.js';
46
46
  import { consentOptions, CONSENT_SETTINGS_ANCHOR } from './consent.js';
47
+ import { pageTags, tagHref } from './tags.js';
47
48
 
48
49
  // The same github-slugger Astro builds page URLs and heading ids with -
49
50
  // resolved through Astro itself, so the two can't drift apart.
@@ -321,7 +322,14 @@ export async function checkLinks(contentDir, configText) {
321
322
  // With the consent banner on, #cookie-settings opens it from any page.
322
323
  const pageWideAnchors = new Set(consentOptions(config.integrations?.consent) ? [CONSENT_SETTINGS_ANCHOR] : []);
323
324
  if (config.domain) ['/sitemap.xml', '/sitemap-index.xml'].forEach((p) => special.add(p));
324
- const knownUrls = [...pages.keys(), ...generated, ...redirects];
325
+ // The tag pages (lib/tags.js): `/tags/` and one per tag a page has. Every
326
+ // tag counts, though one only on pages behind sign-in or in hidden
327
+ // sections gets no page (lib/tag-index.ts) - this doesn't read the
328
+ // navigation that closely, and a link to it is left alone.
329
+ const tagUrls = new Set();
330
+ for (const page of pages.values()) for (const tag of pageTags(page.scan?.data?.tags)) tagUrls.add(tagHref(tag.slug));
331
+ if (tagUrls.size > 0) tagUrls.add(tagHref());
332
+ const knownUrls = [...pages.keys(), ...generated, ...redirects, ...tagUrls];
325
333
  // Folder addresses with no page of their own redirect to one under them
326
334
  // (lib/folder-redirects.js), so a link to one isn't broken.
327
335
  const folders = new Set(
@@ -430,7 +438,7 @@ export async function checkLinks(contentDir, configText) {
430
438
  return;
431
439
  }
432
440
  // "/" always exists: the home page, or a redirect to the first page.
433
- if (pageKey === '/' || generated.has(pageKey) || redirects.has(pageKey) || folders.has(pageKey) || special.has(pageKey.replace(/\/$/, '') || '/')) return;
441
+ if (pageKey === '/' || generated.has(pageKey) || redirects.has(pageKey) || folders.has(pageKey) || tagUrls.has(pageKey) || special.has(pageKey.replace(/\/$/, '') || '/')) return;
434
442
  if (special.has(pathname)) return;
435
443
  if (drafts.has(pageKey)) {
436
444
  report(`${value} - ${pageKey} is a draft (draft: true in ${drafts.get(pageKey)}), so it isn't published.`);
@@ -26,9 +26,10 @@
26
26
 
27
27
  import { convertReadmeBody, makeLinkRewriter, wrapHtml, README_HTML_CLASS, README_HTML_CSS } from './readme-mdx.js';
28
28
  import { convertRecipe } from './readme-recipes.js';
29
- import { htmlToMdx } from './readme-html.js';
29
+ import { htmlToMdx, scopeCustomCss } from './readme-html.js';
30
30
  import { Notes } from './mintlify-convert.js';
31
31
  import { parseHex, contrastRatio } from './color.js';
32
+ import { posix } from 'node:path';
32
33
 
33
34
  // writedocs' dark background when `styles.background` doesn't set one.
34
35
  const DARK_BACKGROUND = '#0b1120';
@@ -138,28 +139,56 @@ export function convertReadmeSnapshot(snapshot) {
138
139
  };
139
140
  const glossary = new Map((project.glossary ?? []).map((g) => [String(g.term).toLowerCase(), g.definition]));
140
141
  const recipeSlugs = new Set((snapshot.recipes ?? []).map((r) => r.slug));
142
+ // ReadMe's reusable content ("custom blocks", used as `<Duvidas />`): one
143
+ // snippet each, imported by every page that uses it.
144
+ const blocks = new Map();
145
+ for (const page of Object.values(snapshot.pages ?? {})) {
146
+ for (const b of page.customBlocks ?? []) if (/^[A-Z][A-Za-z0-9]*$/.test(b.tag) && !blocks.has(b.tag)) blocks.set(b.tag, b.source);
147
+ }
148
+ const usedBlocks = new Set();
141
149
  const ctxFor = (where) => ({
142
150
  rewriteLink: (url) => rewriteLink(url, where),
143
151
  localImage,
144
152
  glossary,
145
153
  recipes: recipeSlugs,
154
+ components: new Set(blocks.keys()),
146
155
  note: (key, message) => notes.add(key, [where], message),
147
156
  });
157
+ /** The import lines for the custom blocks `body` uses, from page `id`. */
158
+ const blockImports = (id, body) => {
159
+ const lines = [];
160
+ for (const tag of blocks.keys()) {
161
+ if (!new RegExp(`<${tag}[\\s/>]`).test(body)) continue;
162
+ usedBlocks.add(tag);
163
+ let rel = posix.relative(posix.dirname(id), `snippets/${tag}.mdx`);
164
+ if (!rel.startsWith('.')) rel = `./${rel}`;
165
+ lines.push(`import ${tag} from '${rel}';`);
166
+ }
167
+ return lines.join('\n');
168
+ };
148
169
 
149
170
  // The OpenAPI files, by ReadMe's definition uri.
150
171
  const specs = new Map();
151
172
  for (const def of snapshot.openapi ?? []) {
152
- let spec = def.spec;
153
- if (!spec) {
154
- spec = mergeEmbeddedSpecs(Object.values(snapshot.pages ?? {}).filter((p) => p.api?.uri === def.uri).map((p) => p.embeddedSpec));
155
- }
173
+ // The registry's file, with every operation an endpoint page shows that
174
+ // it lacks taken from that page's own embedded spec: the registry can
175
+ // be unreachable, and for an API written page by page in ReadMe's editor
176
+ // it serves the file with no operations at all ("x-readme-fauxas").
177
+ const pages = Object.values(snapshot.pages ?? {}).filter((p) => p.api?.uri === def.uri && p.embeddedSpec);
178
+ const missing = pages.filter((p) => !operation(def.spec, p.api.method, p.api.path));
179
+ const spec = missing.length ? mergeEmbeddedSpecs([def.spec, ...missing.map((p) => p.embeddedSpec)].filter(Boolean)) : def.spec;
156
180
  if (!spec) continue;
181
+ if (def.spec && missing.length) {
182
+ notes.add(`spec-filled:${def.uri}`, [def.filename], `${missing.length} of the operations the pages show weren't in the API definition ReadMe serves - they're taken from the endpoint pages.`);
183
+ }
157
184
  const path = `openapi/${def.filename.replace(/[^\w.-]+/g, '-')}`;
158
185
  specs.set(def.uri, { path, spec });
159
186
  files.push({ path, content: `${JSON.stringify(spec, null, 2)}\n` });
160
187
  }
161
188
 
162
189
  const writePage = (id, fields, body) => {
190
+ const imports = body ? blockImports(id, body) : '';
191
+ if (imports) body = `${imports}\n\n${body}`;
163
192
  files.push({ path: `${id}.mdx`, content: `${frontmatter(fields)}\n${body ? `\n${body}\n` : ''}` });
164
193
  counts.pages++;
165
194
  };
@@ -232,9 +261,11 @@ export function convertReadmeSnapshot(snapshot) {
232
261
  };
233
262
 
234
263
  const tabs = [];
264
+ const tabFor = {}; // section -> its tab
265
+ let notFound = null;
235
266
  const label = (key, fallback) => project.sections?.[key]?.label || fallback;
236
267
  const docsNav = sectionNav('docs');
237
- if (docsNav.length) tabs.push({ tab: label('docs', 'Guides'), pages: docsNav });
268
+ if (docsNav.length) tabs.push((tabFor.docs = { tab: label('docs', 'Guides'), pages: docsNav }));
238
269
  const recipesNav = [];
239
270
  for (const recipe of snapshot.recipes ?? []) {
240
271
  const id = `recipes/${recipe.slug}`;
@@ -243,9 +274,73 @@ export function convertReadmeSnapshot(snapshot) {
243
274
  counts.recipes++;
244
275
  recipesNav.push(id);
245
276
  }
246
- if (recipesNav.length) tabs.push({ tab: label('recipes', 'Recipes'), pages: recipesNav });
277
+ if (recipesNav.length) tabs.push((tabFor.recipes = { tab: label('recipes', 'Recipes'), pages: recipesNav }));
247
278
  const referenceNav = sectionNav('reference');
248
- if (referenceNav.length) tabs.push({ tab: label('reference', 'API Reference'), pages: referenceNav });
279
+ if (referenceNav.length) tabs.push((tabFor.reference = { tab: label('reference', 'API Reference'), pages: referenceNav }));
280
+
281
+ // A page read from its ssr-props outside the sidebars: a custom page or a
282
+ // changelog entry. Its body is Markdown, or HTML for an HTML custom page.
283
+ const standalonePage = (id, fallbackTitle, extra = {}) => {
284
+ const page = snapshot.pages?.[id];
285
+ if (!page) {
286
+ notes.add('unreadable-page', [id], "This page couldn't be read from the site, so it's not in the project.");
287
+ return null;
288
+ }
289
+ const fields = { title: page.title ?? fallbackTitle };
290
+ const description = page.excerpt?.trim() || page.metaDescription?.trim();
291
+ if (description) fields.description = description;
292
+ Object.assign(fields, extra);
293
+ const body = !page.body?.trim()
294
+ ? ''
295
+ : page.contentType === 'html'
296
+ ? wrapHtml(htmlToMdx(page.body, { rewriteUrl: (url, name) => (name === 'src' ? localImage(url) : rewriteLink(url, id)) }))
297
+ : convertReadmeBody(page.body, ctxFor(id));
298
+ writePage(id, fields, body);
299
+ return id;
300
+ };
301
+
302
+ // The changelog: a tab of its own, newest first, as llms.txt lists it.
303
+ const changelogNav = (snapshot.changelog ?? []).map((c) => standalonePage(`changelog/${c.slug}`, c.title)).filter(Boolean);
304
+ if (changelogNav.length) tabs.push((tabFor.changelog = { tab: label('changelog', 'Changelog'), pages: changelogNav }));
305
+
306
+ // Custom pages (/page/...): in no sidebar on ReadMe - linked from the
307
+ // landing page or the header. Hidden pages here, so they're built at the
308
+ // same address without showing up in a sidebar. The one ReadMe shows for
309
+ // a missing address is the 404 page instead.
310
+ const customNav = [];
311
+ for (const c of snapshot.customPages ?? []) {
312
+ if (c.slug === project.notFoundPage) {
313
+ const page = snapshot.pages?.[`page/${c.slug}`];
314
+ notFound = { title: page?.title ?? c.title };
315
+ notes.add('not-found-page', [`page/${c.slug}`], "This custom page was the site's \"page not found\" page: its title is notFound.title. Its content isn't carried over - writedocs' page has a title and a description.");
316
+ continue;
317
+ }
318
+ const id = standalonePage(`page/${c.slug}`, c.title, { hidden: true });
319
+ if (id) customNav.push(id);
320
+ }
321
+ if (customNav.length) {
322
+ if (tabs.length) tabs[0].pages.push(...customNav);
323
+ else tabs.push({ tab: label('docs', 'Guides'), pages: customNav });
324
+ }
325
+
326
+ // Pages found by following links (lib/readme-fetch.js): hidden on ReadMe,
327
+ // so hidden here, in their section's tab - built at the same address,
328
+ // out of the sidebar.
329
+ for (const d of snapshot.discovered ?? []) {
330
+ const [section, ...rest] = d.id.split('/');
331
+ const item =
332
+ section === 'docs' || section === 'reference'
333
+ ? navItem(section, { slug: rest.join('/'), title: d.title, type: d.type, hidden: true, pages: [] })
334
+ : standalonePage(d.id, d.title, { hidden: true });
335
+ if (typeof item !== 'string') continue;
336
+ const tab = tabFor[section] ?? tabs[0];
337
+ if (tab) tab.pages.push(item);
338
+ else tabs.push((tabFor[section] = { tab: label(section, 'Guides'), pages: [item] }));
339
+ }
340
+ if (snapshot.discovered?.length) {
341
+ notes.add('discovered', ['navigation'], `${snapshot.discovered.length} hidden pages - out of ReadMe's sidebars, but linked to from other pages - were found and kept as hidden pages.`);
342
+ }
343
+ for (const r of snapshot.linkRedirects ?? []) pageRedirects.push(r);
249
344
 
250
345
  // The landing page.
251
346
  const landing = (project.landingPage ?? []).filter((s) => s.html || s.title || s.text);
@@ -253,7 +348,7 @@ export function convertReadmeSnapshot(snapshot) {
253
348
  const parts = [];
254
349
  for (const section of landing) {
255
350
  if (section.type === 'html' && section.html) {
256
- parts.push(wrapHtml(htmlToMdx(section.html, { rewriteUrl: (url, name) => (name === 'src' ? localImage(url) : rewriteLink(url, 'index')) })));
351
+ parts.push(wrapHtml(htmlToMdx(section.html, { rewriteUrl: (url, name) => (name === 'src' ? localImage(url) : rewriteLink(url, 'index')) }), 'rm-LandingPage'));
257
352
  } else {
258
353
  if (section.title) parts.push(`## ${section.title}`);
259
354
  if (section.text) parts.push(convertReadmeBody(section.text, ctxFor('index')));
@@ -263,14 +358,26 @@ export function convertReadmeSnapshot(snapshot) {
263
358
  writePage('index', { title: project.name ?? 'Home', mode: 'custom' }, parts.join('\n\n'));
264
359
  }
265
360
 
266
- if (files.some((f) => f.path.endsWith('.mdx') && f.content.includes(`className="${README_HTML_CLASS}"`))) {
267
- files.push({ path: 'readme-html.css', content: README_HTML_CSS });
361
+ for (const tag of usedBlocks) {
362
+ files.push({ path: `snippets/${tag}.mdx`, content: `${convertReadmeBody(blocks.get(tag), ctxFor(`snippets/${tag}`))}\n` });
363
+ }
364
+
365
+ const hasHtml = files.some((f) => f.path.endsWith('.mdx') && f.content.includes(`className="${README_HTML_CLASS}`));
366
+ if (hasHtml) files.push({ path: 'readme-html.css', content: README_HTML_CSS });
367
+ // The project's custom CSS, for its hand-written HTML: scoped to it, so
368
+ // the rules for ReadMe's own page can't reach writedocs'.
369
+ if (project.customCss?.trim() && hasHtml) {
370
+ files.push({
371
+ path: 'readme-custom.css',
372
+ content: `/* Written by writedocs convert --readme: the ReadMe project's custom CSS,\n applied only inside the HTML converted from ReadMe (.${README_HTML_CLASS}). */\n${scopeCustomCss(project.customCss, `.${README_HTML_CLASS}`)}`,
373
+ });
374
+ notes.add('custom-css', ['readme-custom.css'], "The project's custom CSS is in readme-custom.css, applied only inside the HTML converted from ReadMe (the landing page and HTML blocks) - its rules for ReadMe's own header and sidebar don't apply. Review it, and remove what isn't needed.");
268
375
  }
269
376
 
270
- if (project.sections?.changelog?.visible) {
271
- notes.add('changelog', ['changelog'], "The site's changelog isn't converted - add its entries as pages (the Update component suits them).");
377
+ if (project.sections?.changelog?.visible && !changelogNav.length) {
378
+ notes.add('changelog', ['changelog'], "The site's changelog couldn't be read (llms.txt lists no entries) - add its entries as pages (the Update component suits them).");
272
379
  }
273
- if (project.customCss) notes.add('custom-css', ['appearance'], 'The project has custom CSS - not carried over; ReadMe class names mostly have no equivalent. See "Custom CSS and scripts".');
380
+ if (project.customCss?.trim() && !hasHtml) notes.add('custom-css', ['appearance'], 'The project has custom CSS - not carried over: it styles ReadMe\'s own page, and no HTML was converted for it to style. See "Custom CSS and scripts".');
274
381
  if (project.customJs) notes.add('custom-js', ['appearance'], 'The project has custom JavaScript - not carried over.');
275
382
 
276
383
  // writedocs.json.
@@ -295,6 +402,7 @@ export function convertReadmeSnapshot(snapshot) {
295
402
  if (Object.keys(styles).length) config.styles = styles;
296
403
  // index.mdx is the home page whether or not the navigation lists it.
297
404
  config.navigation = tabs.length > 1 ? { tabs } : tabs[0]?.pages ?? [];
405
+ if (notFound) config.notFound = notFound;
298
406
 
299
407
  const redirects = [...pageRedirects];
300
408
  for (const r of project.redirects ?? []) {
@@ -307,7 +415,11 @@ export function convertReadmeSnapshot(snapshot) {
307
415
  }
308
416
  redirects.push({ source: rewriteLink(source), destination: rewriteLink(destination) });
309
417
  }
310
- if (redirects.length) config.redirects = redirects;
418
+ // One redirect per address, and none away from a page the project has.
419
+ const pageAddresses = new Set(files.filter((f) => f.path.endsWith('.mdx')).map((f) => `/${f.path.replace(/\.mdx$/, '')}`));
420
+ const bySource = new Map();
421
+ for (const r of redirects) if (!bySource.has(r.source) && !pageAddresses.has(r.source)) bySource.set(r.source, r);
422
+ if (bySource.size) config.redirects = [...bySource.values()];
311
423
  if (project.variables?.length) {
312
424
  config.variables = Object.fromEntries(project.variables.map((v) => [v.name, String(v.default ?? v.name)]));
313
425
  }