@writedocs/generator 0.20.0 → 0.21.1

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.
@@ -0,0 +1,706 @@
1
+ // Turns the body of a ReadMe page - its raw source, ReadMe's own flavor of
2
+ // MDX - into writedocs MDX. Used by lib/readme-convert.js for every guide,
3
+ // reference and recipe page.
4
+ //
5
+ // The body is split into fenced code blocks, <HTMLBlock>s, and the text
6
+ // between them; only the text is rewritten, so nothing inside a code block
7
+ // changes. What changes:
8
+ //
9
+ // - Callouts: `<Callout icon="📘" theme="info">` with a leading `### Title`,
10
+ // and the blockquote form `> 📘 Title`, become `<Callout type title>`.
11
+ // - ReadMe components: `<Cards columns>`/`<Card>` -> `<CardGroup cols>`/
12
+ // `<Card>` (Font Awesome `fa-` icon names lose the prefix), `<Image>` ->
13
+ // a Markdown image, or `<Image>`/`<Frame>` for a width or a caption,
14
+ // `<TutorialTile>`/`<Recipe>` -> a `<Card>` to the recipe, `<Embed>` -> a
15
+ // `<Card>` to the URL, `<Glossary>`/`<<glossary:term>>` -> `<Hint>`,
16
+ // `<Anchor>` -> a link, `<Table>`/`<Tr>`/... -> HTML table elements, and
17
+ // `<HTMLBlock>` -> the HTML written as JSX (lib/readme-html.js).
18
+ // - Links: `doc:slug`, `ref:slug`, `recipe:slug`, `changelog:slug`,
19
+ // `page:slug` and absolute links to the site itself (with or without a
20
+ // `/v1.0` version prefix) become root paths - in Markdown links and in
21
+ // href/src attributes.
22
+ // - Images on files.readme.io are pointed at their local copies (the
23
+ // caller decides the path and downloads them).
24
+ // - Code: adjacent fences (no blank line between them, ReadMe's code tabs)
25
+ // go in a `<CodeGroup>`; language names ReadMe accepts that the
26
+ // highlighter doesn't (`curl`, `node`, `sh`, ...) are mapped.
27
+ // - Raw HTML in the text: `class` -> `className`, `style` strings -> style
28
+ // objects, void elements self-closed, `<!-- -->` -> `{/* */}`; a `<`
29
+ // that doesn't start a known element or component (`<YOUR_API_KEY>`,
30
+ // `a < b`) is escaped, and `<https://...>` autolinks become links - MDX
31
+ // reads all of these as JSX.
32
+ // - `<<variable>>` -> `[[variable]]`, writedocs' variable syntax.
33
+ //
34
+ // Inline code is left alone everywhere.
35
+
36
+ import { htmlToMdx, styleToJsx, mdxJsString } from './readme-html.js';
37
+ import { BUILTIN_COMPONENT_NAMES } from './mdx-inject-builtins.js';
38
+
39
+ const LANG_ALIASES = {
40
+ curl: 'bash', sh: 'bash', shell: 'bash', zsh: 'bash', console: 'bash',
41
+ node: 'javascript', nodejs: 'javascript', js: 'javascript', jsx: 'jsx',
42
+ ts: 'typescript', py: 'python', rb: 'ruby', 'c#': 'csharp', cs: 'csharp', 'objective-c': 'objc',
43
+ kt: 'kotlin', yml: 'yaml', plaintext: 'text', txt: 'text', http: 'http',
44
+ };
45
+ const LANG_LABELS = {
46
+ curl: 'cURL', bash: 'Bash', sh: 'Shell', shell: 'Shell', node: 'Node', nodejs: 'Node', javascript: 'JavaScript', js: 'JavaScript',
47
+ typescript: 'TypeScript', ts: 'TypeScript', python: 'Python', py: 'Python', ruby: 'Ruby', rb: 'Ruby', php: 'PHP', java: 'Java',
48
+ csharp: 'C#', 'c#': 'C#', cs: 'C#', go: 'Go', swift: 'Swift', kotlin: 'Kotlin', json: 'JSON', xml: 'XML', html: 'HTML',
49
+ yaml: 'YAML', text: 'Text', http: 'HTTP', sql: 'SQL', powershell: 'PowerShell', objc: 'Objective-C',
50
+ };
51
+
52
+ // Callout types by ReadMe theme, and by the emoji ReadMe puts first.
53
+ const THEME_TYPES = { info: 'info', okay: 'check', success: 'check', warn: 'warning', warning: 'warning', error: 'danger', danger: 'danger', default: 'note' };
54
+ const EMOJI_TYPES = [
55
+ ['📘', 'info'], ['â„šī¸', 'info'], ['👍', 'check'], ['✅', 'check'], ['🚧', 'warning'], ['âš ī¸', 'warning'],
56
+ ['â—ī¸', 'danger'], ['❗', 'danger'], ['🛑', 'danger'], ['📝', 'note'], ['💡', 'tip'],
57
+ ];
58
+
59
+ // HTML elements a page may use as they are; any other lower-case `<name>`
60
+ // in the text is taken for a placeholder and escaped.
61
+ const HTML_ELEMENTS = new Set(`a abbr address area article aside audio b bdi bdo blockquote br button canvas caption cite code col
62
+ colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6
63
+ header hgroup hr i iframe img input ins kbd label legend li main map mark menu meter nav noscript object ol optgroup option
64
+ output p picture pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup svg
65
+ table tbody td template textarea tfoot th thead time tr track u ul var video wbr path g rect circle line polyline polygon
66
+ ellipse defs use symbol clipPath mask filter linearGradient radialGradient stop text tspan center font`.split(/\s+/));
67
+ const VOID = new Set(['area', 'br', 'col', 'embed', 'hr', 'img', 'input', 'source', 'track', 'wbr']);
68
+ // Upper-case table components ReadMe's editor writes for a table with
69
+ // formatting - the plain HTML elements render the same.
70
+ const TABLE_COMPONENTS = { Table: 'table', Thead: 'thead', Tbody: 'tbody', Tr: 'tr', Th: 'th', Td: 'td' };
71
+ // Components this conversion writes, and the ones writedocs has.
72
+ const KNOWN_COMPONENTS = new Set([...BUILTIN_COMPONENT_NAMES, 'Fragment']);
73
+
74
+ /** Parses JSX-ish attributes: name="v", name='v', name={v}, bare name. */
75
+ export function parseAttributes(text) {
76
+ const attrs = {};
77
+ const re = /([A-Za-z_:][\w:.-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}|([^\s"'>/{}]+)))?/g;
78
+ let m;
79
+ while ((m = re.exec(text))) {
80
+ const [, name, dq, sq, expr, bare] = m;
81
+ if (dq !== undefined) attrs[name] = dq;
82
+ else if (sq !== undefined) attrs[name] = sq;
83
+ else if (expr !== undefined) attrs[name] = { expression: expr.trim() };
84
+ else if (bare !== undefined) attrs[name] = bare;
85
+ else attrs[name] = true;
86
+ }
87
+ return attrs;
88
+ }
89
+
90
+ /** An attribute's plain value: strings as they are, `{3}`/`{"x"}` unwrapped. */
91
+ function plain(value) {
92
+ if (value === undefined || value === null || value === true) return undefined;
93
+ if (typeof value === 'string') return value;
94
+ const e = value.expression;
95
+ if (/^-?\d+(\.\d+)?$/.test(e)) return e;
96
+ const q = /^(["'`])([\s\S]*)\1$/.exec(e);
97
+ return q ? q[2] : undefined;
98
+ }
99
+
100
+ /** `name="value"`, or `name={"..."}` when the value needs escaping. */
101
+ export function jsxAttr(name, value) {
102
+ const v = String(value);
103
+ return /^[^"\\{}<>\n\r&]*$/.test(v) ? `${name}="${v}"` : `${name}={${mdxJsString(v)}}`;
104
+ }
105
+
106
+ /** `fa-solid fa-arrow-right` / `fa-arrow-right` -> `arrow-right`; an emoji
107
+ * or another library's name -> undefined (writedocs looks bare names up
108
+ * in Lucide, then Font Awesome). */
109
+ export function convertIcon(icon) {
110
+ if (typeof icon !== 'string') return undefined;
111
+ const names = icon.split(/\s+/).filter((t) => /^fa-[a-z0-9-]+$/.test(t) && !/^fa-(solid|regular|light|thin|duotone|brands|sharp|kit)$/.test(t));
112
+ if (names.length) return names[names.length - 1].slice(3);
113
+ // Already a bare icon name ("book-open"); an emoji isn't one.
114
+ return /^[a-z0-9]+(-[a-z0-9]+)*$/.test(icon.trim()) ? icon.trim() : undefined;
115
+ }
116
+
117
+ /** ReadMe's link schemes and the site's own absolute URLs, as root paths. */
118
+ export function makeLinkRewriter({ baseUrl, subdomain } = {}) {
119
+ const origins = new Set();
120
+ if (baseUrl) origins.add(new URL(baseUrl).origin);
121
+ if (subdomain) origins.add(`https://${subdomain}.readme.io`);
122
+ const SCHEMES = { doc: '/docs/', ref: '/reference/', recipe: '/recipes/', recipes: '/recipes/', changelog: '/changelog/', page: '/page/' };
123
+ const stripVersion = (p) => p.replace(/^\/v\d+(?:\.\d+)*(?:-[\w-]+)?(?=\/)/, '');
124
+ // `from` is the id of the page the link is on ("docs/webhooks"). A
125
+ // relative link resolves the way it did on ReadMe, whose page addresses
126
+ // have no trailing slash: `events#x` on /docs/webhooks is /docs/events#x.
127
+ // writedocs' addresses end in a slash, so it's written as a root path.
128
+ return (url, from) => {
129
+ if (typeof url !== 'string') return url;
130
+ const s = url.trim();
131
+ if (from && s && !/^([a-z][a-z0-9+.-]*:|\/|#|\?|\{)/i.test(s)) {
132
+ try {
133
+ const u = new URL(s, `https://readme.invalid/${from}`);
134
+ return `${u.pathname}${u.search}${u.hash}`;
135
+ } catch {
136
+ return url;
137
+ }
138
+ }
139
+ const scheme = /^(doc|ref|recipes?|changelog|page):(?!\/\/)([^#?\s]*)([?#].*)?$/i.exec(s);
140
+ if (scheme) return `${SCHEMES[scheme[1].toLowerCase()]}${scheme[2]}${scheme[3] ?? ''}`;
141
+ if (/^https?:\/\//i.test(s)) {
142
+ let u;
143
+ try {
144
+ u = new URL(s);
145
+ } catch {
146
+ return url;
147
+ }
148
+ if (!origins.has(u.origin)) return url;
149
+ const p = stripVersion(u.pathname);
150
+ return `${p === '' ? '/' : p}${u.search}${u.hash}`;
151
+ }
152
+ if (s.startsWith('/')) return stripVersion(s);
153
+ return url;
154
+ };
155
+ }
156
+
157
+ // ---------------------------------------------------------------------
158
+ // Splitting the body
159
+ // ---------------------------------------------------------------------
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
+
165
+ /** The body as segments: { kind: 'text' | 'code' | 'html', lines | text }.
166
+ * A code segment is one fence; an html segment is an <HTMLBlock>'s HTML. */
167
+ export function splitBody(body) {
168
+ const lines = String(body ?? '').replace(/\r\n?/g, '\n').split('\n');
169
+ const segments = [];
170
+ let text = [];
171
+ const flushText = () => {
172
+ if (text.length) segments.push({ kind: 'text', lines: text });
173
+ text = [];
174
+ };
175
+ for (let i = 0; i < lines.length; i++) {
176
+ const line = lines[i];
177
+ const fence = FENCE_RE.exec(line);
178
+ if (fence && !(fence[2][0] === '`' && fence[3].includes('`'))) {
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, ' ');
184
+ const close = new RegExp(`^\\s*${marks[0] === '`' ? '`' : '~'}{${marks.length},}\\s*$`);
185
+ const body = [];
186
+ let j = i + 1;
187
+ while (j < lines.length && !close.test(lines[j])) body.push(lines[j++]);
188
+ flushText();
189
+ segments.push({ kind: 'code', prefix, indent, marks, info: info.trim(), body });
190
+ i = j; // the closing fence (or the end)
191
+ continue;
192
+ }
193
+ const start = line.indexOf('<HTMLBlock');
194
+ if (start !== -1) {
195
+ let j = i;
196
+ let joined = line.slice(start);
197
+ while (!joined.includes('</HTMLBlock>') && j + 1 < lines.length) joined += `\n${lines[++j]}`;
198
+ const end = joined.indexOf('</HTMLBlock>');
199
+ if (end !== -1) {
200
+ if (line.slice(0, start).trim()) text.push(line.slice(0, start));
201
+ flushText();
202
+ const inner = joined.slice(joined.indexOf('>') + 1, end);
203
+ const tpl = /^\s*\{\s*`([\s\S]*)`\s*\}\s*$/.exec(inner);
204
+ segments.push({ kind: 'html', html: tpl ? tpl[1].replace(/\\`/g, '`').replace(/\\\$\{/g, '${') : inner });
205
+ const rest = joined.slice(end + '</HTMLBlock>'.length);
206
+ if (rest.trim()) text.push(rest);
207
+ i = j;
208
+ continue;
209
+ }
210
+ }
211
+ text.push(line);
212
+ }
213
+ flushText();
214
+ return segments;
215
+ }
216
+
217
+ // ---------------------------------------------------------------------
218
+ // Code
219
+ // ---------------------------------------------------------------------
220
+
221
+ /** A fence's info string with ReadMe's language names mapped, and - in a
222
+ * code group, where the title is the tab's label - a title when it has none. */
223
+ export function normalizeFenceInfo(info, { inGroup = false } = {}) {
224
+ if (!info) return '';
225
+ const [lang, ...rest] = info.split(/\s+/);
226
+ const lower = lang.toLowerCase();
227
+ const mapped = LANG_ALIASES[lower] ?? lang;
228
+ let title = rest.join(' ').trim();
229
+ if (!title && inGroup) title = LANG_LABELS[lower] ?? lang;
230
+ return title ? `${mapped} ${title}` : mapped;
231
+ }
232
+
233
+ function renderCode(seg, inGroup, prefix = seg.prefix ?? seg.indent) {
234
+ const info = normalizeFenceInfo(seg.info, { inGroup });
235
+ return [`${prefix}${seg.marks}${info}`, ...seg.body, `${seg.indent}${seg.marks}`];
236
+ }
237
+
238
+ // ---------------------------------------------------------------------
239
+ // Text
240
+ // ---------------------------------------------------------------------
241
+
242
+ function protectInlineCode(text) {
243
+ const saved = [];
244
+ // One line at most: a span reaching across lines is far more often two
245
+ // stray backticks (or a fence) than real inline code.
246
+ const out = text.replace(/(`+)(?!`)([^\n]*?[^`\n])\1(?!`)/g, (m) => {
247
+ saved.push(m);
248
+ return `\u0000${saved.length - 1}\u0000`;
249
+ });
250
+ return { text: out, restore: (s) => s.replace(/\u0000(\d+)\u0000/g, (_, i) => saved[Number(i)]) };
251
+ }
252
+
253
+ function stripInlineMarkup(s) {
254
+ return s.replace(/\*\*([^*]+)\*\*/g, '$1').replace(/__([^_]+)__/g, '$1').replace(/^\*([^*]+)\*$/, '$1').trim();
255
+ }
256
+
257
+ function calloutOpen(type, title) {
258
+ return title ? `<Callout type="${type}" ${jsxAttr('title', title)}>` : `<Callout type="${type}">`;
259
+ }
260
+
261
+ /** `<Callout icon theme>` + a leading heading -> `<Callout type title>`. */
262
+ function convertCalloutTags(text, unwrap) {
263
+ return text.replace(/<Callout\b([^>]*)>([ \t]*\n(?:[ \t]*\n)*([ \t]*)(#{1,6})[ \t]+([^\n]+)\n(?:[ \t]*\n)*)?/g, (m, attrs, headingBlock, indent, hashes, heading) => {
264
+ const a = parseAttributes(attrs);
265
+ // Already writedocs' form - a blockquote callout converted earlier.
266
+ if (a.type !== undefined) return m;
267
+ const theme = plain(a.theme);
268
+ const icon = plain(a.icon);
269
+ let type = theme ? THEME_TYPES[theme] : undefined;
270
+ if (!type && icon) type = EMOJI_TYPES.find(([e]) => icon.startsWith(e))?.[1];
271
+ type ??= 'note';
272
+ const title = heading ? stripInlineMarkup(unwrap(heading.replace(/\s*#+\s*$/, ''))) : undefined;
273
+ return calloutOpen(type, title) + (headingBlock ? '\n' : '');
274
+ });
275
+ }
276
+
277
+ /** `> 📘 Title` + `> body` lines -> a Callout. Runs on the raw body, before
278
+ * it's split, so a code fence inside the quote (`> ```js`) comes out as a
279
+ * real fence; lines inside a fence outside any quote are left alone. */
280
+ export function convertBlockquoteCallouts(lines, unwrap = (s) => s.replace(/`([^`]*)`/g, '$1')) {
281
+ const out = [];
282
+ let fence = null;
283
+ for (let i = 0; i < lines.length; i++) {
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];
286
+ const m = !fence && !f && /^(\s*)>\s?(.*)$/.exec(lines[i]);
287
+ const emoji = m && EMOJI_TYPES.find(([e]) => m[2].startsWith(e));
288
+ if (!emoji) {
289
+ out.push(lines[i]);
290
+ continue;
291
+ }
292
+ const indent = m[1];
293
+ const title = stripInlineMarkup(unwrap(m[2].slice(emoji[0].length).replace(/^\uFE0F/, '')));
294
+ const body = [];
295
+ let j = i + 1;
296
+ while (j < lines.length) {
297
+ const b = new RegExp(`^${indent}>\\s?(.*)$`).exec(lines[j]);
298
+ if (!b) break;
299
+ body.push(b[1]);
300
+ j++;
301
+ }
302
+ while (body.length && !body[0].trim()) body.shift();
303
+ while (body.length && !body[body.length - 1].trim()) body.pop();
304
+ out.push(`${indent}${calloutOpen(emoji[1], title || undefined)}`);
305
+ for (const b of body) out.push(b.trim() ? `${indent} ${b}` : '');
306
+ out.push(`${indent}</Callout>`);
307
+ i = j - 1;
308
+ }
309
+ return out;
310
+ }
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
+
437
+ /** The class every converted HTML block is wrapped in - see READMEHTML_CSS. */
438
+ export const README_HTML_CLASS = 'readme-html';
439
+
440
+ /** Hand-written HTML from ReadMe sets its own colors on a container and
441
+ * lets the headings inside inherit them; writedocs' article heading color
442
+ * (a light one in dark mode) would win over that inheritance, leaving
443
+ * light headings on the HTML's own white cards. Written to the project as
444
+ * readme-html.css when a page has converted HTML. */
445
+ export const README_HTML_CSS = `/* Written by writedocs convert --readme. The HTML converted from ReadMe
446
+ (its HTMLBlocks and landing page) sets its own colors - its headings
447
+ inherit them, instead of the site's heading color. */
448
+ .${README_HTML_CLASS} :where(h1, h2, h3, h4, h5, h6, strong, b) {
449
+ color: inherit;
450
+ }
451
+ `;
452
+
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>`;
457
+ }
458
+
459
+ /**
460
+ * Converts a ReadMe page body.
461
+ *
462
+ * @param {string} body
463
+ * @param {object} ctx
464
+ * @param {(url: string) => string} ctx.rewriteLink
465
+ * @param {(url: string) => string} ctx.localImage the local path for an image URL (or the URL, to keep it)
466
+ * @param {Set<string>} [ctx.recipes] recipe slugs that exist
467
+ * @param {Map<string, string>} [ctx.glossary] term (lower case) -> definition
468
+ * @param {(key: string, message: string) => void} [ctx.note]
469
+ * @returns {string}
470
+ */
471
+ export function convertReadmeBody(body, ctx) {
472
+ const note = ctx.note ?? (() => {});
473
+ const glossary = ctx.glossary ?? new Map();
474
+ const recipes = ctx.recipes ?? new Set();
475
+ const source = convertLegacyBlocks(String(body ?? '').replace(/\r\n?/g, '\n'), note);
476
+ const lines = source.split('\n');
477
+ const segments = splitBody(convertBlockquoteCallouts(lines).join('\n'));
478
+ const out = [];
479
+
480
+ for (let s = 0; s < segments.length; s++) {
481
+ const seg = segments[s];
482
+ if (seg.kind === 'code') {
483
+ // Fences with nothing between them are ReadMe code tabs.
484
+ const group = [seg];
485
+ while (segments[s + 1]?.kind === 'code') group.push(segments[++s]);
486
+ if (group.length === 1) out.push(...renderCode(seg, false));
487
+ else {
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>`);
492
+ }
493
+ continue;
494
+ }
495
+ if (seg.kind === 'html') {
496
+ const mdx = htmlToMdx(seg.html, {
497
+ rewriteUrl: (url, name) => (name === 'src' ? ctx.localImage(url) : ctx.rewriteLink(url)),
498
+ });
499
+ if (mdx) out.push('', wrapHtml(mdx), '');
500
+ continue;
501
+ }
502
+ out.push(convertText(seg.lines.join('\n'), { ...ctx, note, glossary, recipes }));
503
+ }
504
+ return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
505
+ }
506
+
507
+ function convertText(source, ctx) {
508
+ const { text: protectedText, restore } = protectInlineCode(source);
509
+ const unwrap = (s) => restore(s).replace(/`([^`]*)`/g, '$1');
510
+ let t = protectedText;
511
+
512
+ t = convertCalloutTags(t, unwrap);
513
+
514
+ // <TutorialTile> / <tutorial-tile> / <Recipe>: a card to the recipe.
515
+ t = t.replace(/<(TutorialTile|tutorial-tile|Recipe)\b((?:[^>"']|"[^"]*"|'[^']*')*?)(?:\/>|>\s*<\/\1>)/g, (m, name, attrs) => {
516
+ const a = parseAttributes(attrs);
517
+ const slug = plain(a.slug);
518
+ const title = plain(a.title) ?? slug;
519
+ if (!slug || !ctx.recipes.has(slug)) {
520
+ ctx.note('missing-recipe', "A recipe card (TutorialTile) links to a recipe that isn't on the site any more - the card is left out.");
521
+ return '';
522
+ }
523
+ return `<Card ${jsxAttr('title', title)} icon="book-open" href="/recipes/${slug}" />`;
524
+ });
525
+
526
+ // <Cards columns> / <Card>.
527
+ t = t.replace(/<Cards\b([^>]*)>/g, (m, attrs) => {
528
+ const cols = plain(parseAttributes(attrs).columns);
529
+ return /^\d+$/.test(cols ?? '') ? `<CardGroup cols={${cols}}>` : '<CardGroup>';
530
+ });
531
+ t = t.replace(/<\/Cards>/g, '</CardGroup>');
532
+ t = t.replace(/<Card\b([^>]*?)(\/?)>/g, (m, attrs, selfClose) => {
533
+ const a = parseAttributes(attrs);
534
+ const parts = [];
535
+ const title = plain(a.title);
536
+ if (title !== undefined) parts.push(jsxAttr('title', unwrap(title)));
537
+ const icon = convertIcon(plain(a.icon));
538
+ if (icon) parts.push(jsxAttr('icon', icon));
539
+ const href = plain(a.href);
540
+ if (href) parts.push(jsxAttr('href', ctx.rewriteLink(href)));
541
+ return `<Card${parts.length ? ` ${parts.join(' ')}` : ''}${selfClose ? ' />' : '>'}`;
542
+ });
543
+
544
+ // <Image>.
545
+ const image = (attrs, child) => {
546
+ const a = parseAttributes(attrs);
547
+ const src = plain(a.src);
548
+ if (!src) return '';
549
+ const local = ctx.localImage(src);
550
+ const alt = plain(a.alt) ?? plain(a.title) ?? '';
551
+ const caption = (plain(a.caption) ?? child ?? '').trim();
552
+ const width = plain(a.width);
553
+ const size = width && width !== 'smart' && width !== 'auto' ? (/^\d+$/.test(width) ? `${width}px` : width) : undefined;
554
+ if (size || caption) {
555
+ const parts = [jsxAttr('src', local)];
556
+ if (size) parts.push(jsxAttr('size', size));
557
+ if (alt) parts.push(jsxAttr('alt', alt));
558
+ if (caption) parts.push(jsxAttr('caption', unwrap(caption)));
559
+ return `<Image ${parts.join(' ')} />`;
560
+ }
561
+ return `![${alt.replace(/[[\]]/g, '')}](${local})`;
562
+ };
563
+ t = t.replace(/<Image\b((?:[^>"'{]|"[^"]*"|'[^']*'|\{[^}]*\})*?)\/>/g, (m, attrs) => image(attrs));
564
+ t = t.replace(/<Image\b((?:[^>"'{]|"[^"]*"|'[^']*'|\{[^}]*\})*?)>([\s\S]*?)<\/Image>/g, (m, attrs, child) => image(attrs, child));
565
+
566
+ // <Embed>: a video, or a card to what it embedded.
567
+ t = t.replace(/<Embed\b([\s\S]*?)\/>/g, (m, attrs) => {
568
+ const a = parseAttributes(attrs);
569
+ const url = plain(a.url) ?? plain(a.href);
570
+ return url ? embedToMdx(url, plain(a.title), ctx.note) : '';
571
+ });
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
+
577
+ // Glossary terms.
578
+ const tooltip = (term) => {
579
+ const def = ctx.glossary.get(term.trim().toLowerCase());
580
+ if (!def) {
581
+ ctx.note('glossary', `The glossary term "${term}" isn't in the project's glossary - left as plain text.`);
582
+ return term;
583
+ }
584
+ return `<Hint ${jsxAttr('tip', def)}>${term}</Hint>`;
585
+ };
586
+ t = t.replace(/<<glossary:([^>]+)>>/g, (m, term) => tooltip(term));
587
+ t = t.replace(/<Glossary>([\s\S]*?)<\/Glossary>/g, (m, term) => tooltip(term));
588
+ t = t.replace(/<<([A-Za-z_][\w.-]*)>>/g, (m, name) => `[[${name}]]`);
589
+
590
+ // <Anchor label target href>.
591
+ t = t.replace(/<Anchor\b([^>]*)>([\s\S]*?)<\/Anchor>/g, (m, attrs, label) => {
592
+ const href = plain(parseAttributes(attrs).href);
593
+ return href ? `[${label.trim()}](${ctx.rewriteLink(href)})` : label;
594
+ });
595
+
596
+ // Autolinks MDX would read as JSX.
597
+ t = t.replace(/<((?:https?|mailto):[^\s<>]+)>/g, (m, url) => `[${url}](${ctx.rewriteLink(url)})`);
598
+
599
+ // Markdown links and images.
600
+ t = t.replace(/(!?)\[((?:[^[\]]|\[[^\]]*\])*)\]\(\s*<?([^)\s>]+)>?((?:\s+"[^"]*")?)\s*\)/g, (m, bang, label, url, title) =>
601
+ bang ? `![${label}](${ctx.localImage(url)}${title})` : `[${label}](${ctx.rewriteLink(url)}${title})`
602
+ );
603
+
604
+ t = fixRawHtml(t, ctx);
605
+ return restore(t);
606
+ }
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
+
615
+ /** Raw HTML and stray `<` in the text, made valid MDX - see the header. */
616
+ function fixRawHtml(text, ctx) {
617
+ let out = '';
618
+ let i = 0;
619
+ while (i < text.length) {
620
+ const lt = text.indexOf('<', i);
621
+ if (lt === -1) {
622
+ out += escapeTextBraces(text.slice(i));
623
+ break;
624
+ }
625
+ out += escapeTextBraces(text.slice(i, lt));
626
+ if (text.startsWith('<!--', lt)) {
627
+ const end = text.indexOf('-->', lt + 4);
628
+ const body = text.slice(lt + 4, end === -1 ? text.length : end).trim().replace(/\*\//g, '* /');
629
+ out += body ? `{/* ${body} */}` : '';
630
+ i = end === -1 ? text.length : end + 3;
631
+ continue;
632
+ }
633
+ const tag = /^<(\/?)([A-Za-z][\w.:-]*)/.exec(text.slice(lt));
634
+ const end = tag ? tagEnd(text, lt + tag[0].length) : -1;
635
+ if (!tag || end === -1) {
636
+ out += '&lt;';
637
+ i = lt + 1;
638
+ continue;
639
+ }
640
+ const [, closing, rawName] = tag;
641
+ const inner = text.slice(lt + tag[0].length, end); // attributes, and a trailing "/"
642
+ const name = TABLE_COMPONENTS[rawName] ?? rawName;
643
+ if (KNOWN_COMPONENTS.has(rawName) || ctx.components?.has(rawName) || isUnknownComponent(rawName, closing, inner, text, end)) {
644
+ // A component: writedocs' own, or one it will report as unknown.
645
+ out += text.slice(lt, end + 1);
646
+ } else if (HTML_ELEMENTS.has(name) || name.includes('-') && /^[a-z]/.test(name) && /=/.test(inner)) {
647
+ out += closing ? `</${name}>` : htmlOpenTag(name, inner, ctx);
648
+ } else {
649
+ // `<YOUR_API_KEY>`, `<username>`: a placeholder, not an element.
650
+ out += `&lt;${text.slice(lt + 1, end)}&gt;`;
651
+ }
652
+ i = end + 1;
653
+ }
654
+ return out;
655
+ }
656
+
657
+ /** A PascalCase tag that isn't writedocs': kept (the build shows its
658
+ * content and warns) when it's written like a component - self-closed, or
659
+ * closed later. `<YOUR_API_KEY>` or a lone `<Method>` is a placeholder. */
660
+ function isUnknownComponent(name, closing, inner, text, end) {
661
+ if (TABLE_COMPONENTS[name] || !/^[A-Z][A-Za-z0-9]*(\.[A-Z][A-Za-z0-9]*)?$/.test(name) || !/[a-z]/.test(name)) return false;
662
+ if (closing || /\/\s*$/.test(inner)) return true;
663
+ return text.indexOf(`</${name}>`, end) !== -1;
664
+ }
665
+
666
+ /** The index of the `>` that ends a tag, skipping quoted values and {...}. */
667
+ function tagEnd(text, from) {
668
+ let depth = 0;
669
+ let quote = null;
670
+ for (let j = from; j < text.length; j++) {
671
+ const c = text[j];
672
+ if (quote) {
673
+ if (c === quote) quote = null;
674
+ } else if (depth > 0) {
675
+ if (c === '{') depth++;
676
+ else if (c === '}') depth--;
677
+ else if (c === '"' || c === "'" || c === '`') {
678
+ const close = text.indexOf(c, j + 1);
679
+ if (close === -1) return -1;
680
+ j = close;
681
+ }
682
+ } else if (c === '"' || c === "'") quote = c;
683
+ else if (c === '{') depth++;
684
+ else if (c === '>') return j;
685
+ else if (c === '<' || c === '\n' && text[j + 1] === '\n') return -1;
686
+ }
687
+ return -1;
688
+ }
689
+
690
+ function htmlOpenTag(name, inner, ctx) {
691
+ const selfClosing = /\/\s*$/.test(inner);
692
+ const a = parseAttributes(inner.replace(/\/\s*$/, ''));
693
+ const parts = [];
694
+ for (const [key, value] of Object.entries(a)) {
695
+ if (key === 'align' && typeof value === 'object') continue; // <Table align={[...]}>
696
+ const jsxKey = key === 'class' ? 'className' : key === 'for' ? 'htmlFor' : key;
697
+ if (value === true) parts.push(jsxKey);
698
+ else if (typeof value === 'object') parts.push(`${jsxKey}={${value.expression}}`);
699
+ else if (key === 'style') parts.push(`style=${styleToJsx(value)}`);
700
+ else if (key === 'href') parts.push(jsxAttr(jsxKey, ctx.rewriteLink(value)));
701
+ else if (key === 'src') parts.push(jsxAttr(jsxKey, ctx.localImage(value)));
702
+ else parts.push(jsxAttr(jsxKey, value));
703
+ }
704
+ const attrs = parts.length ? ` ${parts.join(' ')}` : '';
705
+ return VOID.has(name) || selfClosing ? `<${name}${attrs} />` : `<${name}${attrs}>`;
706
+ }