@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.
@@ -58,6 +58,13 @@ export function normalizeBaseUrl(input) {
58
58
 
59
59
  /** The recipes listed in llms.txt: `- [Title](https://site/recipes/slug.md)`. */
60
60
  export function recipesFromLlmsTxt(text, baseUrl) {
61
+ return sectionLinksFromLlmsTxt(text, baseUrl, 'recipes');
62
+ }
63
+
64
+ /** The pages of one section (`recipes`, `page` - custom pages - or
65
+ * `changelog`) that llms.txt lists, in its order: `[{ slug, title }]`.
66
+ * None of the three has a sidebar to read them from. */
67
+ export function sectionLinksFromLlmsTxt(text, baseUrl, section) {
61
68
  const out = [];
62
69
  const seen = new Set();
63
70
  const re = /\[([^\]]+)\]\((\S+?)\)/g;
@@ -71,7 +78,7 @@ export function recipesFromLlmsTxt(text, baseUrl) {
71
78
  }
72
79
  if (url.origin !== new URL(baseUrl).origin) continue;
73
80
  const parts = url.pathname.replace(/\.md$/, '').split('/').filter(Boolean);
74
- if (parts.length !== 2 || parts[0] !== 'recipes') continue;
81
+ if (parts.length !== 2 || parts[0] !== section) continue;
75
82
  const slug = decodeURIComponent(parts[1]);
76
83
  if (seen.has(slug)) continue;
77
84
  seen.add(slug);
@@ -80,6 +87,37 @@ export function recipesFromLlmsTxt(text, baseUrl) {
80
87
  return out;
81
88
  }
82
89
 
90
+ const SCHEME_SECTIONS = { doc: 'docs', ref: 'reference', recipe: 'recipes', recipes: 'recipes', page: 'page', changelog: 'changelog' };
91
+ const SLUG_END = /[.,;:!]+$/;
92
+
93
+ /** The site's own pages a body links to, as ids ("docs/intro") - by ReadMe
94
+ * scheme (`doc:intro`), by path (`/docs/intro`, `/v4.1/docs/intro`), or by
95
+ * the site's full address - wherever they are: Markdown, HTML, the JSON of
96
+ * an old [block:html]. A path inside another site's URL doesn't count. */
97
+ export function internalLinkTargets(body, baseUrl, { fromRoot = false } = {}) {
98
+ const out = new Set();
99
+ const add = (section, raw) => {
100
+ let slug = String(raw).replace(/\.md$/, '').replace(SLUG_END, '');
101
+ try {
102
+ slug = decodeURIComponent(slug);
103
+ } catch {
104
+ // keep it as written
105
+ }
106
+ if (slug) out.add(`${section}/${slug}`);
107
+ };
108
+ const text = String(body ?? '');
109
+ for (const m of text.matchAll(/(?<![\w-])(doc|ref|recipes?|page|changelog):(?!\/\/)([^\s)"'#?\\<>\]/]+)/g)) add(SCHEME_SECTIONS[m[1]], m[2]);
110
+ const host = new URL(baseUrl).host.replace(/[.]/g, '\\.');
111
+ const re = new RegExp(`(?:https?:\\/\\/${host}|(?<![\\w.:/%-]))(?:\\/v\\d+(?:\\.\\d+)*)?\\/(docs|reference|recipes|page|changelog)\\/([^\\s)"'#?\\\\<>\\]/]+)`, 'g');
112
+ for (const m of text.matchAll(re)) add(m[1], m[2]);
113
+ // On a page at the site's root (the landing page), `href="docs/x"` is
114
+ // /docs/x too.
115
+ if (fromRoot) {
116
+ for (const m of text.matchAll(/\bhref=["'](?:\.\/)?(docs|reference|recipes|page|changelog)\/([^"'#?\s/]+)/g)) add(m[1], m[2]);
117
+ }
118
+ return out;
119
+ }
120
+
83
121
  /** Every page in a ReadMe sidebar (categories > pages > child pages), in order. */
84
122
  export function flattenSidebar(categories) {
85
123
  const out = [];
@@ -147,6 +185,8 @@ export function projectFromSsr(ssr) {
147
185
  customCss: a.custom_code?.css ?? null,
148
186
  customJs: a.custom_code?.js ?? null,
149
187
  redirects: Array.isArray(d.redirects) ? d.redirects : [],
188
+ // The custom page shown for an address that doesn't exist, by its slug.
189
+ notFoundPage: typeof d.pages?.not_found === 'string' ? d.pages.not_found.split('/').pop() : null,
150
190
  glossary: Array.isArray(d.glossary) ? d.glossary.map((g) => ({ term: g.term, definition: g.definition })) : [],
151
191
  variables: Array.isArray(d.variable_defaults) ? d.variable_defaults.filter((v) => v.source !== 'security').map((v) => ({ name: v.name, default: v.default ?? '' })) : [],
152
192
  };
@@ -167,6 +207,10 @@ export function pageFromSsr(ssr) {
167
207
  metaDescription: doc.metadata?.description ?? null,
168
208
  keywords: doc.metadata?.keywords ?? null,
169
209
  icon: doc.appearance?.icon?.name ?? null,
210
+ // A custom page's body is Markdown or HTML ("html"); a changelog entry
211
+ // has its date.
212
+ contentType: doc.content?.type ?? null,
213
+ createdAt: doc.created_at ?? null,
170
214
  hidden: ssr?.meta?.hidden ?? false,
171
215
  robots: ssr?.meta?.robots ?? null,
172
216
  link: doc.content?.link?.url ? { url: doc.content.link.url, newTab: Boolean(doc.content.link.new_tab) } : null,
@@ -174,6 +218,11 @@ export function pageFromSsr(ssr) {
174
218
  // The one-operation spec ReadMe embeds in an endpoint page - the
175
219
  // fallback when the registry can't be read.
176
220
  embeddedSpec: doc.api?.schema ?? null,
221
+ // ReadMe's reusable content ("custom blocks") the page uses, with their
222
+ // source - `<Duvidas />` in the body is one of these.
223
+ customBlocks: (ssr?.customBlocks ?? [])
224
+ .filter((b) => typeof b?.tag === 'string' && typeof b?.source === 'string')
225
+ .map((b) => ({ tag: b.tag, source: b.source })),
177
226
  registryId: typeof ssr?.oasPublicUrl === 'string' && ssr.oasPublicUrl.includes('#') ? ssr.oasPublicUrl.split('#').pop() : null,
178
227
  apiDefinitions: (ssr?.apiDefinitions ?? []).map((d) => ({ filename: d.filename, uri: d.uri })),
179
228
  };
@@ -192,6 +241,8 @@ async function mapLimit(items, limit, fn) {
192
241
  return out;
193
242
  }
194
243
 
244
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
245
+
195
246
  /**
196
247
  * Reads the site at `baseUrl` into a snapshot.
197
248
  *
@@ -200,15 +251,28 @@ async function mapLimit(items, limit, fn) {
200
251
  * @param {typeof fetch} [options.fetchImpl]
201
252
  * @param {number} [options.concurrency] pages fetched at once (default 4)
202
253
  * @param {(event: {done: number, total: number}) => void} [options.onProgress]
254
+ * @param {number} [options.retryDelay] the first wait after a 429/503, in ms (default 1000)
203
255
  */
204
- export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, concurrency = 4, onProgress } = {}) {
256
+ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, concurrency = 4, onProgress, retryDelay = 1000 } = {}) {
205
257
  const base = normalizeBaseUrl(baseUrl);
206
258
  const headers = { 'user-agent': USER_AGENT };
207
259
  const problems = [];
208
260
 
261
+ // ReadMe rate-limits (429) a few hundred requests in a row. A 429 or a
262
+ // 503 is waited out - its Retry-After, or 2, 4, ... 64 seconds - and not
263
+ // taken for a missing page. The wait pauses every request, not just the
264
+ // one that got it: workers that kept going would keep the limit from
265
+ // clearing.
266
+ let pausedUntil = 0;
209
267
  const get = async (url, { redirect = 'follow' } = {}) => {
210
- const res = await fetchImpl(url, { headers, redirect });
211
- return res;
268
+ for (let attempt = 0; ; attempt++) {
269
+ while (Date.now() < pausedUntil) await sleep(pausedUntil - Date.now());
270
+ const res = await fetchImpl(url, { headers, redirect });
271
+ if ((res.status !== 429 && res.status !== 503) || attempt >= 6) return res;
272
+ const after = Number(res.headers?.get?.('retry-after'));
273
+ const wait = Number.isFinite(after) && after > 0 ? Math.min(after, 120) * 1000 : retryDelay * 2 ** (attempt + 1);
274
+ pausedUntil = Math.max(pausedUntil, Date.now() + wait);
275
+ }
212
276
  };
213
277
  const getText = async (url) => {
214
278
  const res = await get(url);
@@ -216,16 +280,32 @@ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, c
216
280
  return res.text();
217
281
  };
218
282
 
219
- // The home page: the project and both sidebars.
283
+ // The home page: the project, and on some sites both sidebars.
220
284
  const homeHtml = await getText(`${base}/`);
221
285
  const home = parseSsrProps(homeHtml);
222
286
  if (!home?.context?.projectStore?.data) {
223
287
  throw new Error(`${base} doesn't look like a ReadMe site - its home page has no ReadMe page data.`);
224
288
  }
225
289
  const project = projectFromSsr(home);
290
+ // Where the home page doesn't carry a section's sidebar, the section's
291
+ // own address (/docs, /reference - ReadMe opens its first page) does, as
292
+ // `sidebar`. A section that's switched off, or answers with no sidebar,
293
+ // is empty.
294
+ const sectionSidebar = async (section, fromHome) => {
295
+ if (Array.isArray(fromHome)) return sidebarCategories(fromHome);
296
+ try {
297
+ const res = await get(`${base}/${section}`);
298
+ if (!res.ok) return [];
299
+ const ssr = parseSsrProps(await res.text());
300
+ return sidebarCategories(Array.isArray(ssr?.sidebar) ? ssr.sidebar : []);
301
+ } catch (err) {
302
+ problems.push({ where: section, message: `Couldn't read the ${section} sidebar: ${err.message}` });
303
+ return [];
304
+ }
305
+ };
226
306
  const sidebars = {
227
- docs: sidebarCategories(home.guideCategories),
228
- reference: sidebarCategories(home.referenceCategories),
307
+ docs: project.sections.docs?.visible === false ? [] : await sectionSidebar('docs', home.guideCategories),
308
+ reference: project.sections.reference?.visible === false ? [] : await sectionSidebar('reference', home.referenceCategories),
229
309
  };
230
310
 
231
311
  // Every guide and reference page, from its own ssr-props.
@@ -234,12 +314,23 @@ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, c
234
314
  for (const p of flattenSidebar(sidebars[section])) jobs.push({ section, slug: p.slug, type: p.type });
235
315
  }
236
316
  const recipesIndex = [];
317
+ const customPages = [];
318
+ const changelog = [];
237
319
  let llmsTxt = null;
238
320
  try {
239
321
  llmsTxt = await getText(`${base}/llms.txt`);
240
- recipesIndex.push(...recipesFromLlmsTxt(llmsTxt, base));
322
+ if (project.sections.recipes?.visible !== false) recipesIndex.push(...recipesFromLlmsTxt(llmsTxt, base));
323
+ // Custom pages (/page/...) and changelog entries are read like guides,
324
+ // from their own ssr-props; llms.txt is what lists them.
325
+ customPages.push(...sectionLinksFromLlmsTxt(llmsTxt, base, 'page'));
326
+ if (project.sections.changelog?.visible !== false) changelog.push(...sectionLinksFromLlmsTxt(llmsTxt, base, 'changelog'));
241
327
  } catch (err) {
242
- problems.push({ where: 'llms.txt', message: `Couldn't read llms.txt (${err.message}), so no recipes were found.` });
328
+ problems.push({ where: 'llms.txt', message: `Couldn't read llms.txt (${err.message}), so no recipes, custom pages or changelog entries were found.` });
329
+ }
330
+ for (const p of customPages) jobs.push({ section: 'page', slug: p.slug, type: 'basic' });
331
+ for (const p of changelog) jobs.push({ section: 'changelog', slug: p.slug, type: 'basic' });
332
+ if (!jobs.length && !recipesIndex.length) {
333
+ throw new Error(`no pages found on ${base} - neither its home page nor /docs and /reference list any.`);
243
334
  }
244
335
  const total = jobs.length + recipesIndex.length;
245
336
  let done = 0;
@@ -265,7 +356,7 @@ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, c
265
356
  // A page with no content of its own - an API tag's page above its
266
357
  // endpoints - answers with a redirect to its first child, whose page
267
358
  // data then comes back. Keep only where it leads.
268
- if (page.slug && page.slug !== slug) {
359
+ if (page.slug && page.slug.normalize() !== slug.normalize()) {
269
360
  pages[id] = { slug, title: null, type: 'basic', body: '', redirectsTo: `${section}/${page.slug}` };
270
361
  return;
271
362
  }
@@ -291,6 +382,63 @@ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, c
291
382
  // Back in llms.txt's order - mapLimit finishes them in any order.
292
383
  recipes.sort((a, b) => recipesIndex.findIndex((r) => r.slug === a.slug) - recipesIndex.findIndex((r) => r.slug === b.slug));
293
384
 
385
+ // Pages the sidebars don't list, found by following links. A hidden page
386
+ // isn't in the sidebar data ReadMe gives a visitor, but its address works
387
+ // - and pages link to it. A renamed page's old address redirects to the
388
+ // new one. Each round follows the links of the pages the last one found.
389
+ const discovered = []; // { id, title, type } - kept as hidden pages
390
+ const linkRedirects = []; // { source, destination } - ReadMe's own redirects
391
+ const tried = new Set();
392
+ const known = () => new Set([...Object.keys(pages), ...recipes.map((r) => `recipes/${r.slug}`)]);
393
+ const linksOf = (page) => [page.body, ...(page.customBlocks ?? []).map((b) => b.source)].join('\n');
394
+ for (let round = 0; round < 5; round++) {
395
+ const have = known();
396
+ const frontier = new Set();
397
+ // The pages, and the landing page's HTML - often the only link to a page.
398
+ const sources = [
399
+ ...Object.values(pages).map((page) => [linksOf(page), false]),
400
+ ...project.landingPage.map((s) => [[s.html, s.text].filter(Boolean).join('\n'), true]),
401
+ ];
402
+ for (const [source, fromRoot] of sources) {
403
+ for (const id of internalLinkTargets(source, base, { fromRoot })) if (!have.has(id) && !tried.has(id) && !id.startsWith('recipes/')) frontier.add(id);
404
+ }
405
+ if (!frontier.size) break;
406
+ await mapLimit([...frontier], concurrency, async (id) => {
407
+ tried.add(id);
408
+ const [section, ...rest] = id.split('/');
409
+ const url = `${base}/${section}/${encodeURIComponent(rest.join('/'))}`;
410
+ try {
411
+ const res = await get(url);
412
+ if (res.status === 429 || res.status === 503) {
413
+ problems.push({ where: id, message: `${url} kept answering ${res.status} (too many requests), so a page there may be missing - convert again later.` });
414
+ return;
415
+ }
416
+ if (!res.ok) return; // broken on ReadMe too - broken-links lists it
417
+ let finalId = id;
418
+ if (res.url) {
419
+ const final = new URL(res.url);
420
+ if (final.origin !== base) {
421
+ linkRedirects.push({ source: `/${id}`, destination: final.href });
422
+ return;
423
+ }
424
+ const parts = decodeURIComponent(final.pathname).replace(/^\/v\d+(?:\.\d+)*(?=\/)/, '').split('/').filter(Boolean);
425
+ if (parts.length === 2) finalId = parts.join('/');
426
+ }
427
+ const page = pageFromSsr(parseSsrProps(await res.text()));
428
+ if (!page) return;
429
+ if (page.slug && finalId === id && page.slug.normalize() !== rest.join('/').normalize()) finalId = `${section}/${page.slug}`;
430
+ if (finalId.normalize() !== id.normalize()) {
431
+ linkRedirects.push({ source: `/${id}`, destination: `/${finalId}` });
432
+ if (known().has(finalId)) return;
433
+ }
434
+ pages[finalId] = { ...page, hidden: true };
435
+ discovered.push({ id: finalId, title: page.title, type: page.api ? 'endpoint' : 'basic' });
436
+ } catch {
437
+ // unreachable - left for broken-links to report
438
+ }
439
+ });
440
+ }
441
+
294
442
  // The API definitions: one OpenAPI file each, from the registry.
295
443
  const definitions = new Map(); // uri -> { filename, registryId }
296
444
  for (const page of Object.values(pages)) {
@@ -330,6 +478,10 @@ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, c
330
478
  sidebars,
331
479
  pages,
332
480
  recipes,
481
+ customPages,
482
+ changelog,
483
+ discovered,
484
+ linkRedirects,
333
485
  openapi,
334
486
  problems,
335
487
  };
@@ -170,6 +170,68 @@ function element(node, rewriteUrl, indent) {
170
170
  return `${open}>\n${lines.join('\n')}\n${indent}</${tag}>`;
171
171
  }
172
172
 
173
+ /** The top-level statements of a style sheet - rules and at-rules, each
174
+ * with its block - skipping comments and strings while counting braces. */
175
+ function cssStatements(css) {
176
+ const out = [];
177
+ let start = 0;
178
+ let depth = 0;
179
+ let i = 0;
180
+ while (i < css.length) {
181
+ const c = css[i];
182
+ if (c === '/' && css[i + 1] === '*') {
183
+ const end = css.indexOf('*/', i + 2);
184
+ i = end === -1 ? css.length : end + 2;
185
+ continue;
186
+ }
187
+ if (c === '"' || c === "'") {
188
+ let j = i + 1;
189
+ while (j < css.length && css[j] !== c) j += css[j] === '\\' ? 2 : 1;
190
+ i = j + 1;
191
+ continue;
192
+ }
193
+ if (c === '{') depth++;
194
+ else if (c === '}') {
195
+ depth = Math.max(0, depth - 1);
196
+ if (depth === 0) {
197
+ out.push(css.slice(start, i + 1).trim());
198
+ start = i + 1;
199
+ }
200
+ } else if (c === ';' && depth === 0) {
201
+ out.push(css.slice(start, i + 1).trim());
202
+ start = i + 1;
203
+ }
204
+ i++;
205
+ }
206
+ const rest = css.slice(start).trim();
207
+ if (rest) out.push(rest);
208
+ return out.filter(Boolean);
209
+ }
210
+
211
+ // At-rules that can't go inside @scope (or mean nothing there), kept at the
212
+ // top level.
213
+ const TOP_LEVEL_AT = /^@(import|font-face|(-[a-z]+-)?keyframes|property|layer|namespace|counter-style|font-feature-values|page)\b/i;
214
+
215
+ /**
216
+ * A ReadMe project's custom CSS, applied only inside `scopeSelector` - the
217
+ * HTML converted from ReadMe. That CSS styled ReadMe's whole page: its own
218
+ * header and sidebar (`.rm-Header`), `html`, `body`, and the classes of the
219
+ * project's hand-written HTML. Inside `@scope`, only the last can match;
220
+ * nothing reaches writedocs' own layout. `@charset` is dropped; `@import`,
221
+ * `@font-face`, `@keyframes` and the like stay at the top level.
222
+ */
223
+ export function scopeCustomCss(css, scopeSelector) {
224
+ const top = [];
225
+ const scoped = [];
226
+ for (const statement of cssStatements(String(css ?? ''))) {
227
+ if (/^@charset\b/i.test(statement)) continue;
228
+ (TOP_LEVEL_AT.test(statement) ? top : scoped).push(statement);
229
+ }
230
+ const parts = [...top];
231
+ if (scoped.length) parts.push(`@scope (${scopeSelector}) {\n${scoped.join('\n')}\n}`);
232
+ return `${parts.join('\n\n')}\n`;
233
+ }
234
+
173
235
  /**
174
236
  * The MDX for an HTML fragment: one block, no blank lines inside it.
175
237
  * Top-level text becomes a <p>-free inline run of its own; top-level
@@ -158,6 +158,10 @@ export function makeLinkRewriter({ baseUrl, subdomain } = {}) {
158
158
  // Splitting the body
159
159
  // ---------------------------------------------------------------------
160
160
 
161
+ // A fence line: indentation and any list markers (`1. ```html`), the marks,
162
+ // and the info string.
163
+ const FENCE_RE = /^(\s*(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)*)(`{3,}|~{3,})(.*)$/;
164
+
161
165
  /** The body as segments: { kind: 'text' | 'code' | 'html', lines | text }.
162
166
  * A code segment is one fence; an html segment is an <HTMLBlock>'s HTML. */
163
167
  export function splitBody(body) {
@@ -170,15 +174,19 @@ export function splitBody(body) {
170
174
  };
171
175
  for (let i = 0; i < lines.length; i++) {
172
176
  const line = lines[i];
173
- const fence = /^(\s*)(`{3,}|~{3,})(.*)$/.exec(line);
177
+ const fence = FENCE_RE.exec(line);
174
178
  if (fence && !(fence[2][0] === '`' && fence[3].includes('`'))) {
175
- const [, indent, marks, info] = fence;
179
+ // `prefix` is what comes before the fence on its line - indentation,
180
+ // and list markers when the fence opens a list item (`1. ```html`);
181
+ // `indent` is the same width in spaces, for the lines after it.
182
+ const [, prefix, marks, info] = fence;
183
+ const indent = prefix.replace(/\S/g, ' ');
176
184
  const close = new RegExp(`^\\s*${marks[0] === '`' ? '`' : '~'}{${marks.length},}\\s*$`);
177
185
  const body = [];
178
186
  let j = i + 1;
179
187
  while (j < lines.length && !close.test(lines[j])) body.push(lines[j++]);
180
188
  flushText();
181
- segments.push({ kind: 'code', indent, marks, info: info.trim(), body });
189
+ segments.push({ kind: 'code', prefix, indent, marks, info: info.trim(), body });
182
190
  i = j; // the closing fence (or the end)
183
191
  continue;
184
192
  }
@@ -222,9 +230,9 @@ export function normalizeFenceInfo(info, { inGroup = false } = {}) {
222
230
  return title ? `${mapped} ${title}` : mapped;
223
231
  }
224
232
 
225
- function renderCode(seg, inGroup) {
233
+ function renderCode(seg, inGroup, prefix = seg.prefix ?? seg.indent) {
226
234
  const info = normalizeFenceInfo(seg.info, { inGroup });
227
- return [`${seg.indent}${seg.marks}${info}`, ...seg.body, `${seg.indent}${seg.marks}`];
235
+ return [`${prefix}${seg.marks}${info}`, ...seg.body, `${seg.indent}${seg.marks}`];
228
236
  }
229
237
 
230
238
  // ---------------------------------------------------------------------
@@ -273,8 +281,8 @@ export function convertBlockquoteCallouts(lines, unwrap = (s) => s.replace(/`([^
273
281
  const out = [];
274
282
  let fence = null;
275
283
  for (let i = 0; i < lines.length; i++) {
276
- const f = /^\s*(`{3,}|~{3,})/.exec(lines[i]);
277
- if (f && (!fence || (f[1][0] === fence[0] && f[1].length >= fence.length))) fence = fence ? null : f[1];
284
+ const f = FENCE_RE.exec(lines[i]);
285
+ if (f && (!fence || (f[2][0] === fence[0] && f[2].length >= fence.length))) fence = fence ? null : f[2];
278
286
  const m = !fence && !f && /^(\s*)>\s?(.*)$/.exec(lines[i]);
279
287
  const emoji = m && EMOJI_TYPES.find(([e]) => m[2].startsWith(e));
280
288
  if (!emoji) {
@@ -301,6 +309,131 @@ export function convertBlockquoteCallouts(lines, unwrap = (s) => s.replace(/`([^
301
309
  return out;
302
310
  }
303
311
 
312
+ // ---------------------------------------------------------------------
313
+ // ReadMe's older block syntax
314
+ // ---------------------------------------------------------------------
315
+
316
+ /** A video service's embed address for `url` (YouTube, Vimeo, Loom), or null. */
317
+ export function videoEmbedUrl(url) {
318
+ let u;
319
+ try {
320
+ u = new URL(String(url).replace(/^\/\//, 'https://'));
321
+ } catch {
322
+ return null;
323
+ }
324
+ const host = u.hostname.replace(/^www\.|^m\./, '');
325
+ if (host === 'youtube.com' || host === 'youtube-nocookie.com') {
326
+ const id = u.searchParams.get('v') ?? /^\/(?:embed|shorts|live)\/([\w-]+)/.exec(u.pathname)?.[1];
327
+ return id ? `https://www.youtube.com/embed/${id}` : null;
328
+ }
329
+ if (host === 'youtu.be') return /^\/([\w-]+)/.test(u.pathname) ? `https://www.youtube.com/embed/${u.pathname.slice(1).split('/')[0]}` : null;
330
+ if (host === 'vimeo.com' || host === 'player.vimeo.com') {
331
+ const id = /(\d{5,})/.exec(u.pathname)?.[1];
332
+ return id ? `https://player.vimeo.com/video/${id}` : null;
333
+ }
334
+ if (host === 'loom.com') {
335
+ const id = /\/(?:share|embed)\/([\w-]+)/.exec(u.pathname)?.[1];
336
+ return id ? `https://www.loom.com/embed/${id}` : null;
337
+ }
338
+ return null;
339
+ }
340
+
341
+ /** An embed: a <Video> for a video service, otherwise a card to the URL. */
342
+ function embedToMdx(url, title, note) {
343
+ const video = videoEmbedUrl(url);
344
+ if (video) return `<Video src="${video}"${title ? ` ${jsxAttr('title', title)}` : ''} />`;
345
+ note('embed', 'An embed of something other than a video became a card linking to it.');
346
+ return `<Card ${jsxAttr('title', title || url)} icon="external-link" href="${url}" />`;
347
+ }
348
+
349
+ /** A value safe in a ReadMe-style `name="..."` attribute, which the later
350
+ * passes read back with parseAttributes(). */
351
+ const attrText = (v) => String(v ?? '').replace(/"/g, "'").replace(/\s*\n\s*/g, ' ').trim();
352
+
353
+ /** One legacy block's JSON, as the ReadMe MDX the rest of the conversion
354
+ * handles - or null for a type that has no conversion. */
355
+ function legacyBlock(type, data, note) {
356
+ switch (type) {
357
+ case 'image':
358
+ return (data.images ?? [])
359
+ .map((img) => {
360
+ const [raw, title, alt] = Array.isArray(img.image) ? img.image : [img.image];
361
+ // Some exports hold the URL as a Markdown link to itself.
362
+ const src = /^\[[^\]]*\]\(\s*([^)\s]+)\s*\)$/.exec(String(raw ?? '').trim())?.[1] ?? raw;
363
+ if (!src) return '';
364
+ const parts = [`src="${attrText(src)}"`];
365
+ if (img.sizing && !/^(smart|auto|original|full)$/.test(img.sizing)) parts.push(`width="${attrText(img.sizing)}"`);
366
+ if (alt || title) parts.push(`alt="${attrText(alt || title)}"`);
367
+ if (img.caption) parts.push(`caption="${attrText(img.caption)}"`);
368
+ return `<Image ${parts.join(' ')} />`;
369
+ })
370
+ .filter(Boolean)
371
+ .join('\n\n');
372
+ case 'html':
373
+ return typeof data.html === 'string' ? `<HTMLBlock>{\`${data.html.replace(/`/g, '\\`').replace(/\$\{/g, '\\${')}\`}</HTMLBlock>` : '';
374
+ case 'parameters': {
375
+ const d = data.data ?? {};
376
+ const cols = Number(data.cols) || Object.keys(d).filter((k) => /^h-\d+$/.test(k)).length;
377
+ const rows = Number(data.rows) || Math.max(0, ...Object.keys(d).map((k) => Number(/^(\d+)-\d+$/.exec(k)?.[1] ?? -1) + 1));
378
+ if (!cols) return '';
379
+ const cell = (v) => String(v ?? '').trim().replace(/\|/g, '\\|').replace(/\s*\n\s*/g, '<br />');
380
+ const lines = [`| ${Array.from({ length: cols }, (_, c) => cell(d[`h-${c}`])).join(' | ')} |`, `| ${Array.from({ length: cols }, () => '---').join(' | ')} |`];
381
+ for (let r = 0; r < rows; r++) lines.push(`| ${Array.from({ length: cols }, (_, c) => cell(d[`${r}-${c}`])).join(' | ')} |`);
382
+ return lines.join('\n');
383
+ }
384
+ case 'callout': {
385
+ const theme = { info: 'info', success: 'success', warning: 'warning', danger: 'danger', error: 'danger' }[data.type] ?? 'default';
386
+ const head = data.title ? `### ${String(data.title).replace(/\n/g, ' ')}\n\n` : '';
387
+ return `<Callout theme="${theme}">\n${head}${String(data.body ?? '').trim()}\n</Callout>`;
388
+ }
389
+ case 'code':
390
+ return (data.codes ?? [])
391
+ .map((c) => {
392
+ const code = String(c.code ?? '');
393
+ const ticks = '`'.repeat(Math.max(3, ...[...code.matchAll(/`+/g)].map((m) => m[0].length + 1)));
394
+ const info = [c.language || 'text', c.name && c.name !== c.language ? c.name : ''].filter(Boolean).join(' ');
395
+ return `${ticks}${info}\n${code}\n${ticks}`;
396
+ })
397
+ .join('\n');
398
+ case 'api-header':
399
+ return data.title ? `## ${String(data.title).replace(/\n/g, ' ')}` : '';
400
+ case 'embed': {
401
+ const url = data.url || /src="([^"]+)"/.exec(data.html ?? '')?.[1];
402
+ return url ? embedToMdx(url, data.title, note) : '';
403
+ }
404
+ case 'tutorial-tile':
405
+ return data.slug ? `<TutorialTile slug="${attrText(data.slug)}" title="${attrText(data.title)}" />` : '';
406
+ default:
407
+ return null;
408
+ }
409
+ }
410
+
411
+ /** Converts ReadMe's older `[block:type]{json}[/block]` syntax - on lines of
412
+ * its own, or on one line inside a list item - into the ReadMe MDX the
413
+ * rest of the conversion handles. A block whose JSON doesn't parse, or of
414
+ * a type with no conversion, goes in a code fence (so the page builds) and
415
+ * is reported. */
416
+ export function convertLegacyBlocks(source, note = () => {}) {
417
+ if (!source.includes('[block:')) return source;
418
+ return source.replace(/^([ \t]*)\[block:([\w-]+)\]\s*([\s\S]*?)\s*\[\/block\][ \t]*$/gm, (m, indent, type, json) => {
419
+ let data;
420
+ try {
421
+ data = JSON.parse(json);
422
+ } catch {
423
+ data = null;
424
+ }
425
+ let out = data ? legacyBlock(type, data, note) : null;
426
+ if (out === null) {
427
+ note('legacy-block', `A [block:${type}] in ReadMe's older syntax couldn't be converted - it's shown as a code block. Rewrite it with components.`);
428
+ out = `\`\`\`json block:${type}\n${json}\n\`\`\``;
429
+ }
430
+ return out
431
+ .split('\n')
432
+ .map((line) => (line ? indent + line : line))
433
+ .join('\n');
434
+ });
435
+ }
436
+
304
437
  /** The class every converted HTML block is wrapped in - see READMEHTML_CSS. */
305
438
  export const README_HTML_CLASS = 'readme-html';
306
439
 
@@ -317,8 +450,10 @@ export const README_HTML_CSS = `/* Written by writedocs convert --readme. The HT
317
450
  }
318
451
  `;
319
452
 
320
- export function wrapHtml(mdx) {
321
- return `<div className="${README_HTML_CLASS}">\n${mdx}\n</div>`;
453
+ /** `extraClass`: ReadMe's own class for the container, when the project's
454
+ * CSS styles through it (`rm-LandingPage` around the landing page). */
455
+ export function wrapHtml(mdx, extraClass = '') {
456
+ return `<div className="${[README_HTML_CLASS, extraClass].filter(Boolean).join(' ')}">\n${mdx}\n</div>`;
322
457
  }
323
458
 
324
459
  /**
@@ -337,14 +472,7 @@ export function convertReadmeBody(body, ctx) {
337
472
  const note = ctx.note ?? (() => {});
338
473
  const glossary = ctx.glossary ?? new Map();
339
474
  const recipes = ctx.recipes ?? new Set();
340
- let source = String(body ?? '').replace(/\r\n?/g, '\n');
341
- // ReadMe's older [block:type]{json}[/block] syntax isn't converted: each
342
- // block goes in a code fence, so the page builds (its JSON is not MDX)
343
- // and the author sees what to rewrite.
344
- if (/^\[block:[\w-]+\]/m.test(source)) {
345
- note('legacy-blocks', "The page uses ReadMe's older [block:...] syntax, which isn't converted - each block is shown as a code block. Rewrite them with components.");
346
- source = source.replace(/^\[block:([\w-]+)\]\n([\s\S]*?)\n\[\/block\]$/gm, (m, type, json) => `\`\`\`json block:${type}\n${json}\n\`\`\``);
347
- }
475
+ const source = convertLegacyBlocks(String(body ?? '').replace(/\r\n?/g, '\n'), note);
348
476
  const lines = source.split('\n');
349
477
  const segments = splitBody(convertBlockquoteCallouts(lines).join('\n'));
350
478
  const out = [];
@@ -357,10 +485,10 @@ export function convertReadmeBody(body, ctx) {
357
485
  while (segments[s + 1]?.kind === 'code') group.push(segments[++s]);
358
486
  if (group.length === 1) out.push(...renderCode(seg, false));
359
487
  else {
360
- const indent = group[0].indent;
361
- out.push(`${indent}<CodeGroup>`);
362
- for (const g of group) out.push(...renderCode(g, true));
363
- out.push(`${indent}</CodeGroup>`);
488
+ // The group takes the first fence's place - list marker included.
489
+ out.push(`${group[0].prefix ?? group[0].indent}<CodeGroup>`);
490
+ for (const g of group) out.push(...renderCode(g, true, g.indent));
491
+ out.push(`${group[0].indent}</CodeGroup>`);
364
492
  }
365
493
  continue;
366
494
  }
@@ -435,15 +563,17 @@ function convertText(source, ctx) {
435
563
  t = t.replace(/<Image\b((?:[^>"'{]|"[^"]*"|'[^']*'|\{[^}]*\})*?)\/>/g, (m, attrs) => image(attrs));
436
564
  t = t.replace(/<Image\b((?:[^>"'{]|"[^"]*"|'[^']*'|\{[^}]*\})*?)>([\s\S]*?)<\/Image>/g, (m, attrs, child) => image(attrs, child));
437
565
 
438
- // <Embed>: a card to what it embedded.
566
+ // <Embed>: a video, or a card to what it embedded.
439
567
  t = t.replace(/<Embed\b([\s\S]*?)\/>/g, (m, attrs) => {
440
568
  const a = parseAttributes(attrs);
441
569
  const url = plain(a.url) ?? plain(a.href);
442
- if (!url) return '';
443
- ctx.note('embed', 'An <Embed> became a card linking to what it embedded.');
444
- return `<Card ${jsxAttr('title', plain(a.title) || url)} icon="external-link" href="${url}" />`;
570
+ return url ? embedToMdx(url, plain(a.title), ctx.note) : '';
445
571
  });
446
572
 
573
+ // `<h2 id="x">Title\n</h2>`: in MDX an element whose text starts on its
574
+ // opening line has to end on that line too.
575
+ t = t.replace(/(<([a-z][a-z0-9]*)\b[^<>\n]*>[^\n]*\S)[ \t]*\n[ \t]*(<\/\2>)/g, '$1$3');
576
+
447
577
  // Glossary terms.
448
578
  const tooltip = (term) => {
449
579
  const def = ctx.glossary.get(term.trim().toLowerCase());
@@ -475,6 +605,13 @@ function convertText(source, ctx) {
475
605
  return restore(t);
476
606
  }
477
607
 
608
+ // Braces in Markdown text are MDX expressions; ReadMe showed `{id}` as text
609
+ // (and an expression naming something undefined would fail the page), so
610
+ // they're escaped - all but an MDX comment, which is kept.
611
+ export function escapeTextBraces(text) {
612
+ return text.replace(/\{\/\*[\s\S]*?\*\/\}|[{}]/g, (m) => (m.length > 1 ? m : `\\${m}`));
613
+ }
614
+
478
615
  /** Raw HTML and stray `<` in the text, made valid MDX - see the header. */
479
616
  function fixRawHtml(text, ctx) {
480
617
  let out = '';
@@ -482,10 +619,10 @@ function fixRawHtml(text, ctx) {
482
619
  while (i < text.length) {
483
620
  const lt = text.indexOf('<', i);
484
621
  if (lt === -1) {
485
- out += text.slice(i);
622
+ out += escapeTextBraces(text.slice(i));
486
623
  break;
487
624
  }
488
- out += text.slice(i, lt);
625
+ out += escapeTextBraces(text.slice(i, lt));
489
626
  if (text.startsWith('<!--', lt)) {
490
627
  const end = text.indexOf('-->', lt + 4);
491
628
  const body = text.slice(lt + 4, end === -1 ? text.length : end).trim().replace(/\*\//g, '* /');
@@ -503,7 +640,7 @@ function fixRawHtml(text, ctx) {
503
640
  const [, closing, rawName] = tag;
504
641
  const inner = text.slice(lt + tag[0].length, end); // attributes, and a trailing "/"
505
642
  const name = TABLE_COMPONENTS[rawName] ?? rawName;
506
- if (KNOWN_COMPONENTS.has(rawName) || isUnknownComponent(rawName, closing, inner, text, end)) {
643
+ if (KNOWN_COMPONENTS.has(rawName) || ctx.components?.has(rawName) || isUnknownComponent(rawName, closing, inner, text, end)) {
507
644
  // A component: writedocs' own, or one it will report as unknown.
508
645
  out += text.slice(lt, end + 1);
509
646
  } else if (HTML_ELEMENTS.has(name) || name.includes('-') && /^[a-z]/.test(name) && /=/.test(inner)) {
@@ -91,7 +91,7 @@ export function convertRecipe(markdown, ctx) {
91
91
 
92
92
  // The steps: split the rest of the page at its top-level headings.
93
93
  const restText = rest
94
- .map((seg) => (seg.kind === 'text' ? seg.lines.join('\n') : seg.kind === 'code' ? [seg.indent + seg.marks + seg.info, ...seg.body, seg.indent + seg.marks].join('\n') : `<HTMLBlock>{\`${seg.html}\`}</HTMLBlock>`))
94
+ .map((seg) => (seg.kind === 'text' ? seg.lines.join('\n') : seg.kind === 'code' ? [seg.prefix + seg.marks + seg.info, ...seg.body, seg.indent + seg.marks].join('\n') : `<HTMLBlock>{\`${seg.html}\`}</HTMLBlock>`))
95
95
  .join('\n');
96
96
  const steps = [];
97
97
  const intro = [];