@writedocs/generator 0.20.0 → 0.21.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.
@@ -0,0 +1,336 @@
1
+ // Reads a published ReadMe site (readme.io / a ReadMe custom domain) into
2
+ // one plain JSON "snapshot" - everything `writedocs convert --readme` needs,
3
+ // fetched once, so the conversion itself (lib/readme-convert.js) is a pure
4
+ // function of the snapshot and can be tested without the network.
5
+ //
6
+ // Where each piece comes from - all public, no browser and no ReadMe API key:
7
+ //
8
+ // - Every ReadMe page embeds its data as JSON in
9
+ // <script id="ssr-props" type="application/x-ssr-props">. The home page's
10
+ // holds the project's settings (context.projectStore.data: name, brand
11
+ // colors, logo, favicon, the landing page's HTML, the custom domain,
12
+ // redirects) and both sidebars (guideCategories, referenceCategories).
13
+ // - A guide or reference page's own ssr-props has its raw source
14
+ // (document.content.body - the author's MDX, with `doc:` links, not the
15
+ // rendered page), its excerpt and SEO metadata, and for an endpoint page
16
+ // the operation (document.api.method/path) and the API definition it
17
+ // belongs to (document.api.uri, oasPublicUrl).
18
+ // - A "link" page redirects to its target: its address is the redirect's
19
+ // Location.
20
+ // - Recipes have no ssr document: their list is in llms.txt and their
21
+ // content is the page's `.md` export (code blocks, then one `# Step`
22
+ // heading per step with `<!-- lang@from-to -->` line ranges).
23
+ // - The whole OpenAPI file of an API definition is served by ReadMe's API
24
+ // registry, https://dash.readme.com/api/v1/api-registry/<id>, the id
25
+ // being the part of oasPublicUrl after "#". When that fails, the
26
+ // conversion falls back to merging the one-operation specs every endpoint
27
+ // page embeds.
28
+ //
29
+ // `fetchImpl` is injectable for tests. Only the default version of the
30
+ // project is read.
31
+
32
+ export const SNAPSHOT_VERSION = 1;
33
+
34
+ const SSR_RE = /<script id="ssr-props" type="application\/x-ssr-props">([\s\S]*?)<\/script>/;
35
+ const REGISTRY = 'https://dash.readme.com/api/v1/api-registry/';
36
+ const USER_AGENT = 'Mozilla/5.0 (compatible; writedocs-convert)';
37
+
38
+ /** The JSON a ReadMe page embeds, or null when the HTML has none. */
39
+ export function parseSsrProps(html) {
40
+ const m = SSR_RE.exec(html);
41
+ if (!m) return null;
42
+ try {
43
+ return JSON.parse(m[1]);
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ /** The site's root URL, without a trailing slash: "developer.example.com"
50
+ * and "https://developer.example.com/docs/intro" both give
51
+ * "https://developer.example.com". */
52
+ export function normalizeBaseUrl(input) {
53
+ const raw = String(input ?? '').trim();
54
+ if (!raw) throw new Error('No ReadMe site address given.');
55
+ const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`);
56
+ return url.origin;
57
+ }
58
+
59
+ /** The recipes listed in llms.txt: `- [Title](https://site/recipes/slug.md)`. */
60
+ export function recipesFromLlmsTxt(text, baseUrl) {
61
+ const out = [];
62
+ const seen = new Set();
63
+ const re = /\[([^\]]+)\]\((\S+?)\)/g;
64
+ let m;
65
+ while ((m = re.exec(text))) {
66
+ let url;
67
+ try {
68
+ url = new URL(m[2], baseUrl);
69
+ } catch {
70
+ continue;
71
+ }
72
+ if (url.origin !== new URL(baseUrl).origin) continue;
73
+ const parts = url.pathname.replace(/\.md$/, '').split('/').filter(Boolean);
74
+ if (parts.length !== 2 || parts[0] !== 'recipes') continue;
75
+ const slug = decodeURIComponent(parts[1]);
76
+ if (seen.has(slug)) continue;
77
+ seen.add(slug);
78
+ out.push({ slug, title: m[1].trim() });
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /** Every page in a ReadMe sidebar (categories > pages > child pages), in order. */
84
+ export function flattenSidebar(categories) {
85
+ const out = [];
86
+ const walk = (pages) => {
87
+ for (const p of pages ?? []) {
88
+ out.push(p);
89
+ walk(p.pages);
90
+ }
91
+ };
92
+ for (const c of categories ?? []) walk(c.pages);
93
+ return out;
94
+ }
95
+
96
+ /** The part of a sidebar entry the conversion uses. */
97
+ function sidebarPage(p) {
98
+ return {
99
+ slug: p.slug,
100
+ title: p.title,
101
+ type: p.type,
102
+ hidden: Boolean(p.hidden),
103
+ deprecated: Boolean(p.deprecated),
104
+ isBodyEmpty: Boolean(p.isBodyEmpty),
105
+ method: p.api_method ?? null,
106
+ pages: (p.pages ?? []).map(sidebarPage),
107
+ };
108
+ }
109
+
110
+ function sidebarCategories(categories) {
111
+ return (categories ?? []).map((c) => ({ title: c.title, pages: (c.pages ?? []).map(sidebarPage) }));
112
+ }
113
+
114
+ /** The settings of the project a snapshot keeps, from the home page's ssr-props. */
115
+ export function projectFromSsr(ssr) {
116
+ const d = ssr?.context?.projectStore?.data ?? {};
117
+ const a = d.appearance ?? {};
118
+ const brand = a.brand ?? {};
119
+ const logo = a.logo ?? {};
120
+ const links = a.navigation?.links ?? {};
121
+ const label = (key) => {
122
+ const l = links[key];
123
+ if (!l) return null;
124
+ return { label: l.alias || l.label || null, visible: l.visibility !== 'disabled' };
125
+ };
126
+ return {
127
+ name: d.name ?? ssr?.meta?.title ?? null,
128
+ description: d.description ?? null,
129
+ customDomain: d.custom_domain?.name ?? null,
130
+ colors: {
131
+ primary: brand.primary_color ?? a.colors?.main ?? null,
132
+ primaryDark: brand.primary_color_dark ?? null,
133
+ link: brand.link_color ?? null,
134
+ linkDark: brand.link_color_dark ?? null,
135
+ },
136
+ theme: brand.theme ?? null,
137
+ logo: { light: logo.main?.url ?? null, dark: logo.dark_mode?.url ?? null },
138
+ favicon: logo.favicon?.url ?? null,
139
+ sections: {
140
+ home: label('home'),
141
+ docs: label('guides'),
142
+ reference: label('reference'),
143
+ recipes: label('recipes'),
144
+ changelog: label('changelog'),
145
+ },
146
+ landingPage: (a.landing_page?.sections ?? []).map((s) => ({ type: s.type, title: s.title ?? null, text: s.text ?? null, html: s.html ?? null })),
147
+ customCss: a.custom_code?.css ?? null,
148
+ customJs: a.custom_code?.js ?? null,
149
+ redirects: Array.isArray(d.redirects) ? d.redirects : [],
150
+ glossary: Array.isArray(d.glossary) ? d.glossary.map((g) => ({ term: g.term, definition: g.definition })) : [],
151
+ variables: Array.isArray(d.variable_defaults) ? d.variable_defaults.filter((v) => v.source !== 'security').map((v) => ({ name: v.name, default: v.default ?? '' })) : [],
152
+ };
153
+ }
154
+
155
+ /** The part of a page's ssr document the conversion uses. */
156
+ export function pageFromSsr(ssr) {
157
+ const doc = ssr?.document;
158
+ if (!doc) return null;
159
+ const api = doc.api && doc.api.path ? { method: doc.api.method, path: doc.api.path, uri: doc.api.uri ?? null } : null;
160
+ return {
161
+ slug: doc.slug ?? null,
162
+ title: doc.title,
163
+ type: doc.type,
164
+ body: doc.content?.body ?? '',
165
+ excerpt: doc.content?.excerpt ?? null,
166
+ metaTitle: doc.metadata?.title ?? null,
167
+ metaDescription: doc.metadata?.description ?? null,
168
+ keywords: doc.metadata?.keywords ?? null,
169
+ icon: doc.appearance?.icon?.name ?? null,
170
+ hidden: ssr?.meta?.hidden ?? false,
171
+ robots: ssr?.meta?.robots ?? null,
172
+ link: doc.content?.link?.url ? { url: doc.content.link.url, newTab: Boolean(doc.content.link.new_tab) } : null,
173
+ api,
174
+ // The one-operation spec ReadMe embeds in an endpoint page - the
175
+ // fallback when the registry can't be read.
176
+ embeddedSpec: doc.api?.schema ?? null,
177
+ registryId: typeof ssr?.oasPublicUrl === 'string' && ssr.oasPublicUrl.includes('#') ? ssr.oasPublicUrl.split('#').pop() : null,
178
+ apiDefinitions: (ssr?.apiDefinitions ?? []).map((d) => ({ filename: d.filename, uri: d.uri })),
179
+ };
180
+ }
181
+
182
+ async function mapLimit(items, limit, fn) {
183
+ const out = new Array(items.length);
184
+ let next = 0;
185
+ const worker = async () => {
186
+ while (next < items.length) {
187
+ const i = next++;
188
+ out[i] = await fn(items[i], i);
189
+ }
190
+ };
191
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
192
+ return out;
193
+ }
194
+
195
+ /**
196
+ * Reads the site at `baseUrl` into a snapshot.
197
+ *
198
+ * @param {string} baseUrl any address on the site
199
+ * @param {object} [options]
200
+ * @param {typeof fetch} [options.fetchImpl]
201
+ * @param {number} [options.concurrency] pages fetched at once (default 4)
202
+ * @param {(event: {done: number, total: number}) => void} [options.onProgress]
203
+ */
204
+ export async function fetchReadmeSite(baseUrl, { fetchImpl = globalThis.fetch, concurrency = 4, onProgress } = {}) {
205
+ const base = normalizeBaseUrl(baseUrl);
206
+ const headers = { 'user-agent': USER_AGENT };
207
+ const problems = [];
208
+
209
+ const get = async (url, { redirect = 'follow' } = {}) => {
210
+ const res = await fetchImpl(url, { headers, redirect });
211
+ return res;
212
+ };
213
+ const getText = async (url) => {
214
+ const res = await get(url);
215
+ if (!res.ok) throw new Error(`${url} answered ${res.status}`);
216
+ return res.text();
217
+ };
218
+
219
+ // The home page: the project and both sidebars.
220
+ const homeHtml = await getText(`${base}/`);
221
+ const home = parseSsrProps(homeHtml);
222
+ if (!home?.context?.projectStore?.data) {
223
+ throw new Error(`${base} doesn't look like a ReadMe site - its home page has no ReadMe page data.`);
224
+ }
225
+ const project = projectFromSsr(home);
226
+ const sidebars = {
227
+ docs: sidebarCategories(home.guideCategories),
228
+ reference: sidebarCategories(home.referenceCategories),
229
+ };
230
+
231
+ // Every guide and reference page, from its own ssr-props.
232
+ const jobs = [];
233
+ for (const section of ['docs', 'reference']) {
234
+ for (const p of flattenSidebar(sidebars[section])) jobs.push({ section, slug: p.slug, type: p.type });
235
+ }
236
+ const recipesIndex = [];
237
+ let llmsTxt = null;
238
+ try {
239
+ llmsTxt = await getText(`${base}/llms.txt`);
240
+ recipesIndex.push(...recipesFromLlmsTxt(llmsTxt, base));
241
+ } catch (err) {
242
+ problems.push({ where: 'llms.txt', message: `Couldn't read llms.txt (${err.message}), so no recipes were found.` });
243
+ }
244
+ const total = jobs.length + recipesIndex.length;
245
+ let done = 0;
246
+ const tick = () => onProgress?.({ done: ++done, total });
247
+
248
+ const pages = {};
249
+ await mapLimit(jobs, concurrency, async ({ section, slug, type }) => {
250
+ const id = `${section}/${slug}`;
251
+ const url = `${base}/${section}/${encodeURIComponent(slug)}`;
252
+ try {
253
+ if (type === 'link') {
254
+ // A link page answers with a redirect to its target.
255
+ const res = await get(url, { redirect: 'manual' });
256
+ const location = res.headers.get('location');
257
+ if (location && new URL(location, base).origin !== base) {
258
+ pages[id] = { title: null, type: 'link', body: '', link: { url: new URL(location, base).href, newTab: true } };
259
+ return;
260
+ }
261
+ }
262
+ const html = await getText(url);
263
+ const page = pageFromSsr(parseSsrProps(html));
264
+ if (!page) throw new Error('the page has no ReadMe page data');
265
+ // A page with no content of its own - an API tag's page above its
266
+ // endpoints - answers with a redirect to its first child, whose page
267
+ // data then comes back. Keep only where it leads.
268
+ if (page.slug && page.slug !== slug) {
269
+ pages[id] = { slug, title: null, type: 'basic', body: '', redirectsTo: `${section}/${page.slug}` };
270
+ return;
271
+ }
272
+ pages[id] = page;
273
+ } catch (err) {
274
+ problems.push({ where: id, message: `Couldn't read ${url}: ${err.message}` });
275
+ } finally {
276
+ tick();
277
+ }
278
+ });
279
+
280
+ const recipes = [];
281
+ await mapLimit(recipesIndex, concurrency, async (r) => {
282
+ const url = `${base}/recipes/${encodeURIComponent(r.slug)}.md`;
283
+ try {
284
+ recipes.push({ ...r, markdown: await getText(url) });
285
+ } catch (err) {
286
+ problems.push({ where: `recipes/${r.slug}`, message: `Couldn't read ${url}: ${err.message}` });
287
+ } finally {
288
+ tick();
289
+ }
290
+ });
291
+ // Back in llms.txt's order - mapLimit finishes them in any order.
292
+ recipes.sort((a, b) => recipesIndex.findIndex((r) => r.slug === a.slug) - recipesIndex.findIndex((r) => r.slug === b.slug));
293
+
294
+ // The API definitions: one OpenAPI file each, from the registry.
295
+ const definitions = new Map(); // uri -> { filename, registryId }
296
+ for (const page of Object.values(pages)) {
297
+ if (!page.api?.uri) continue;
298
+ if (!definitions.has(page.api.uri)) {
299
+ const def = page.apiDefinitions?.find((d) => d.uri === page.api.uri);
300
+ const filename = def?.filename ?? page.api.uri.split('/').pop();
301
+ definitions.set(page.api.uri, { filename, registryId: page.registryId });
302
+ }
303
+ }
304
+ const openapi = [];
305
+ for (const [uri, def] of definitions) {
306
+ let spec = null;
307
+ if (def.registryId) {
308
+ try {
309
+ const res = await get(`${REGISTRY}${encodeURIComponent(def.registryId)}`);
310
+ if (res.ok) spec = await res.json();
311
+ } catch {
312
+ spec = null;
313
+ }
314
+ }
315
+ if (!spec?.paths) {
316
+ problems.push({
317
+ where: def.filename,
318
+ message: `Couldn't download ${def.filename} from ReadMe's API registry - it's rebuilt from the operations the endpoint pages show, so operations without a page are missing.`,
319
+ });
320
+ spec = null;
321
+ }
322
+ openapi.push({ uri, filename: def.filename, spec });
323
+ }
324
+
325
+ return {
326
+ version: SNAPSHOT_VERSION,
327
+ baseUrl: base,
328
+ fetchedAt: new Date().toISOString(),
329
+ project,
330
+ sidebars,
331
+ pages,
332
+ recipes,
333
+ openapi,
334
+ problems,
335
+ };
336
+ }
@@ -0,0 +1,201 @@
1
+ // Turns an HTML fragment into MDX that renders the same HTML - for ReadMe's
2
+ // <HTMLBlock> and its HTML landing page, which hold whole hand-written
3
+ // pages: <style> sheets, inline SVG, `class` and `style` attributes,
4
+ // comments. None of that is valid MDX as written, and MDX has no "raw
5
+ // HTML" escape hatch writedocs can use (`<Fragment set:html>` isn't
6
+ // resolved in a page), so the HTML is parsed (parse5, the HTML spec's own
7
+ // parser) and written back out as JSX:
8
+ //
9
+ // - `class` -> `className`, `for` -> `htmlFor`, a `style` string -> a style
10
+ // object; every other attribute keeps its HTML name (`fill-rule`,
11
+ // `viewBox`, `xlink:href`, `data-*`), which Astro renders unchanged.
12
+ // - Void elements are self-closed; comments, <meta>, <title> and <base> are
13
+ // dropped; <html>/<head>/<body> wrappers are unwrapped by the parser.
14
+ // - <style> and <script> keep their text exactly, as a template literal.
15
+ // MDX halves backslashes before the expression reaches the JavaScript
16
+ // parser (`"\\201C"` arrives as the invalid escape `"\201C"`), so every
17
+ // backslash, backtick and `$` is written as a \u escape instead.
18
+ // - Text: an element whose children include text is written on one line,
19
+ // so MDX keeps it inline instead of wrapping it in <p>. Its text is
20
+ // Markdown-escaped (MDX parses Markdown inside JSX: `*a*` would become
21
+ // <em>). Elements that hold only elements are written one per line,
22
+ // indented, with no blank lines - a blank line inside JSX would turn
23
+ // what follows into Markdown paragraphs.
24
+ // - <pre> and <textarea> keep their whitespace, as a string expression.
25
+ //
26
+ // `rewriteUrl(url, attribute)` lets the caller change href/src values -
27
+ // ReadMe links to local pages, images to their downloaded copies.
28
+
29
+ import { parseFragment } from 'parse5';
30
+
31
+ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
32
+ const DROPPED = new Set(['meta', 'title', 'base']);
33
+ const RAW_TEXT = new Set(['style', 'script']);
34
+ const PRESERVE_WS = new Set(['pre', 'textarea']);
35
+ const URL_ATTRS = new Set(['href', 'src', 'poster', 'action', 'xlink:href']);
36
+ const RENAMED = { class: 'className', for: 'htmlFor' };
37
+
38
+ /** A JavaScript string literal that survives MDX: every character MDX or
39
+ * a JS string could read specially is a \u escape. */
40
+ export function mdxJsString(value) {
41
+ return `"${String(value).replace(/[\\"\n\r\u2028\u2029`$<>{}]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`)}"`;
42
+ }
43
+
44
+ /** A template literal's body that survives MDX - see the comment above. */
45
+ function mdxTemplateBody(value) {
46
+ return String(value).replace(/[\\`$]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
47
+ }
48
+
49
+ /** Splits CSS declarations on `;`, but not inside parentheses or quotes
50
+ * (`background: url(data:image/png;base64,...)`). */
51
+ function splitDeclarations(css) {
52
+ const out = [];
53
+ let depth = 0;
54
+ let quote = null;
55
+ let start = 0;
56
+ for (let i = 0; i < css.length; i++) {
57
+ const c = css[i];
58
+ if (quote) {
59
+ if (c === '\\') i++;
60
+ else if (c === quote) quote = null;
61
+ } else if (c === '"' || c === "'") quote = c;
62
+ else if (c === '(') depth++;
63
+ else if (c === ')') depth = Math.max(0, depth - 1);
64
+ else if (c === ';' && depth === 0) {
65
+ out.push(css.slice(start, i));
66
+ start = i + 1;
67
+ }
68
+ }
69
+ out.push(css.slice(start));
70
+ return out.map((d) => d.trim()).filter(Boolean);
71
+ }
72
+
73
+ /** A style attribute's text as a JSX style object: `color: red; font-size: 2px`
74
+ * -> `{{ color: "red", fontSize: "2px" }}`. Custom properties keep their
75
+ * name, quoted. */
76
+ export function styleToJsx(css) {
77
+ const entries = [];
78
+ for (const decl of splitDeclarations(String(css).replace(/\/\*[\s\S]*?\*\//g, ''))) {
79
+ const colon = decl.indexOf(':');
80
+ if (colon < 1) continue;
81
+ const prop = decl.slice(0, colon).trim();
82
+ const value = decl.slice(colon + 1).trim();
83
+ if (!prop || !value) continue;
84
+ let key;
85
+ if (prop.startsWith('--')) key = mdxJsString(prop);
86
+ else {
87
+ const camel = prop.toLowerCase().replace(/^-ms-/, 'ms-').replace(/-([a-z])/g, (_, ch) => ch.toUpperCase());
88
+ key = /^[A-Za-z_$][\w$]*$/.test(camel) ? camel : mdxJsString(camel);
89
+ }
90
+ entries.push(`${key}: ${mdxJsString(value)}`);
91
+ }
92
+ return `{{ ${entries.join(', ')} }}`;
93
+ }
94
+
95
+ /** Escapes text so MDX shows it as written: Markdown punctuation gets a
96
+ * backslash, and `{`, `}`, `<`, `>` (which a backslash doesn't protect in
97
+ * MDX) become character references. */
98
+ export function escapeMdxText(text) {
99
+ return String(text)
100
+ .replace(/[\\`*_[\]#|~!]/g, (c) => `\\${c}`)
101
+ .replace(/&/g, '&amp;')
102
+ .replace(/[{}<>]/g, (c) => `&#${c.charCodeAt(0)};`);
103
+ }
104
+
105
+ function attrName(attr) {
106
+ const name = attr.prefix ? `${attr.prefix}:${attr.name}` : attr.name;
107
+ return RENAMED[name] ?? name;
108
+ }
109
+
110
+ function attrValue(value) {
111
+ return /^[^"\\{}<>\n\r&]*$/.test(value) ? `"${value}"` : `{${mdxJsString(value)}}`;
112
+ }
113
+
114
+ function attributes(node, rewriteUrl) {
115
+ const parts = [];
116
+ for (const attr of node.attrs ?? []) {
117
+ const original = attr.prefix ? `${attr.prefix}:${attr.name}` : attr.name;
118
+ // An attribute name JSX can't hold (`@click`, `x-on:foo.bar`) is dropped.
119
+ if (!/^[A-Za-z_][\w.:-]*$/.test(original) || /[.]/.test(original)) continue;
120
+ let value = attr.value;
121
+ if (original === 'style') {
122
+ const style = styleToJsx(value);
123
+ if (style !== '{{ }}') parts.push(`style=${style}`);
124
+ continue;
125
+ }
126
+ if (URL_ATTRS.has(original) && rewriteUrl) value = rewriteUrl(value, original) ?? value;
127
+ parts.push(`${attrName(attr)}=${attrValue(value)}`);
128
+ }
129
+ return parts.length ? ` ${parts.join(' ')}` : '';
130
+ }
131
+
132
+ const isText = (n) => n.nodeName === '#text';
133
+ const isElement = (n) => n.tagName !== undefined;
134
+ const textOf = (n) => (n.childNodes ?? []).map((c) => (isText(c) ? c.value : isElement(c) ? textOf(c) : '')).join('');
135
+
136
+ function children(node) {
137
+ // <template> keeps its children in .content.
138
+ return node.content ? node.content.childNodes : node.childNodes ?? [];
139
+ }
140
+
141
+ /** One element written on a single line - its text inline. */
142
+ function inline(node, rewriteUrl) {
143
+ if (isText(node)) return escapeMdxText(node.value.replace(/\s+/g, ' '));
144
+ if (!isElement(node) || DROPPED.has(node.tagName)) return '';
145
+ return element(node, rewriteUrl, null);
146
+ }
147
+
148
+ function element(node, rewriteUrl, indent) {
149
+ const tag = node.tagName;
150
+ const open = `<${tag}${attributes(node, rewriteUrl)}`;
151
+ if (VOID.has(tag)) return `${open} />`;
152
+ if (RAW_TEXT.has(tag)) {
153
+ const text = textOf(node);
154
+ return text.trim() ? `${open}>{\`${mdxTemplateBody(text)}\`}</${tag}>` : `${open}></${tag}>`;
155
+ }
156
+ if (PRESERVE_WS.has(tag)) {
157
+ const text = textOf(node);
158
+ return text ? `${open}>{${mdxJsString(text)}}</${tag}>` : `${open}></${tag}>`;
159
+ }
160
+ const kids = children(node).filter((c) => isElement(c) || isText(c));
161
+ const hasText = kids.some((c) => isText(c) && c.value.trim());
162
+ if (!kids.some((c) => isElement(c) || c.value.trim())) return `${open}></${tag}>`;
163
+ if (hasText || indent === null) {
164
+ // Inline: one line, whitespace between parts collapsed to one space.
165
+ const body = kids.map((c) => inline(c, rewriteUrl)).join('').replace(/^ +| +$/g, '');
166
+ return `${open}>${body}</${tag}>`;
167
+ }
168
+ const pad = `${indent} `;
169
+ const lines = kids.filter(isElement).filter((c) => !DROPPED.has(c.tagName)).map((c) => pad + element(c, rewriteUrl, pad));
170
+ return `${open}>\n${lines.join('\n')}\n${indent}</${tag}>`;
171
+ }
172
+
173
+ /**
174
+ * The MDX for an HTML fragment: one block, no blank lines inside it.
175
+ * Top-level text becomes a <p>-free inline run of its own; top-level
176
+ * elements are written one after another.
177
+ *
178
+ * @param {string} html
179
+ * @param {{ rewriteUrl?: (url: string, attribute: string) => string | undefined }} [options]
180
+ */
181
+ export function htmlToMdx(html, { rewriteUrl } = {}) {
182
+ const fragment = parseFragment(String(html ?? ''));
183
+ const out = [];
184
+ let run = [];
185
+ const flush = () => {
186
+ const text = run.join('').replace(/\s+/g, ' ').trim();
187
+ if (text) out.push(`<span>${text}</span>`);
188
+ run = [];
189
+ };
190
+ for (const node of fragment.childNodes) {
191
+ if (isText(node)) {
192
+ if (node.value.trim()) run.push(escapeMdxText(node.value));
193
+ continue;
194
+ }
195
+ if (!isElement(node) || DROPPED.has(node.tagName)) continue;
196
+ flush();
197
+ out.push(element(node, rewriteUrl, ''));
198
+ }
199
+ flush();
200
+ return out.join('\n');
201
+ }