@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.
- package/bin/writedocs.js +23 -7
- package/package.json +1 -1
- package/src/cli/convert.js +120 -15
- package/src/lib/readme-convert.js +437 -0
- package/src/lib/readme-fetch.js +488 -0
- package/src/lib/readme-html.js +263 -0
- package/src/lib/readme-mdx.js +706 -0
- package/src/lib/readme-recipes.js +135 -0
- package/src/pages/[...slug].astro +60 -1
package/bin/writedocs.js
CHANGED
|
@@ -279,27 +279,43 @@ program
|
|
|
279
279
|
|
|
280
280
|
program
|
|
281
281
|
.command('convert')
|
|
282
|
-
.description("Convert another docs tool's
|
|
283
|
-
.argument('[dir]', 'project directory (contains docs.json or config.json)', '.')
|
|
282
|
+
.description("Convert another docs tool's project into a writedocs project")
|
|
283
|
+
.argument('[dir]', 'project directory (contains docs.json or config.json; with --readme, where to write the project)', '.')
|
|
284
284
|
.option('--mintlify', "convert a Mintlify project's docs.json")
|
|
285
285
|
.option('--docs.json', 'same as --mintlify')
|
|
286
286
|
.option('--writedocs', "convert a project from the previous writedocs (its config.json)")
|
|
287
287
|
.option('--config.json', 'same as --writedocs')
|
|
288
|
-
.option('--
|
|
288
|
+
.option('--readme <site>', 'convert a published ReadMe site (its address) into a new project in [dir]')
|
|
289
|
+
.option('--force', 'overwrite an existing writedocs.json (with --readme: and every file the conversion writes)')
|
|
289
290
|
.option('--dry-run', 'print the converted writedocs.json instead of writing it')
|
|
290
291
|
.action(async (dir, options) => {
|
|
291
292
|
// Commander camel-cases only on hyphens: `--docs.json` is stored under
|
|
292
293
|
// the key "docs.json", not `docsJson`.
|
|
293
294
|
const mintlify = options.mintlify || options['docs.json'];
|
|
294
295
|
const legacy = options.writedocs || options['config.json'];
|
|
295
|
-
|
|
296
|
+
const readme = options.readme;
|
|
297
|
+
const chosen = [mintlify, legacy, readme].filter(Boolean).length;
|
|
298
|
+
if (chosen !== 1) {
|
|
296
299
|
log.error(
|
|
297
|
-
|
|
298
|
-
? 'Pick one: --mintlify or --
|
|
299
|
-
: 'Say what to convert from: writedocs convert --mintlify [dir],
|
|
300
|
+
chosen
|
|
301
|
+
? 'Pick one: --mintlify, --writedocs or --readme.'
|
|
302
|
+
: 'Say what to convert from: writedocs convert --mintlify [dir], --writedocs for the previous writedocs, or --readme <site> [dir].'
|
|
300
303
|
);
|
|
301
304
|
throw new CliExit(1);
|
|
302
305
|
}
|
|
306
|
+
if (readme) {
|
|
307
|
+
if (options.dryRun) {
|
|
308
|
+
log.error('--dry-run isn\'t available with --readme - convert into an empty folder instead.');
|
|
309
|
+
throw new CliExit(1);
|
|
310
|
+
}
|
|
311
|
+
const { runReadmeConvert } = await import('../src/cli/convert.js');
|
|
312
|
+
await runReadmeConvert({
|
|
313
|
+
site: readme,
|
|
314
|
+
contentDir: canonicalPath(path.resolve(process.cwd(), dir)),
|
|
315
|
+
force: Boolean(options.force),
|
|
316
|
+
});
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
303
319
|
const { runConvert } = await import('../src/cli/convert.js');
|
|
304
320
|
await runConvert({
|
|
305
321
|
source: legacy ? 'writedocs' : 'mintlify',
|
package/package.json
CHANGED
package/src/cli/convert.js
CHANGED
|
@@ -4,10 +4,18 @@
|
|
|
4
4
|
// `writedocs validate` does. The conversions themselves are
|
|
5
5
|
// lib/mintlify-convert.js and lib/writedocs-legacy-convert.js; this file is
|
|
6
6
|
// the CLI around them.
|
|
7
|
+
//
|
|
8
|
+
// `writedocs convert --readme <site> [dir]` is different: there's no project
|
|
9
|
+
// folder to start from, only a published ReadMe site. It reads the site
|
|
10
|
+
// (lib/readme-fetch.js), converts it into a whole project - pages, OpenAPI
|
|
11
|
+
// files and writedocs.json (lib/readme-convert.js) - writes that into [dir],
|
|
12
|
+
// downloads the images ReadMe hosts, and then checks the pages the same way.
|
|
7
13
|
import fs from 'node:fs';
|
|
8
14
|
import path from 'node:path';
|
|
9
15
|
import { loadMintlifyConfig, convertMintlifyConfig, formatNotes } from '../lib/mintlify-convert.js';
|
|
10
16
|
import { loadLegacyConfig, convertLegacyConfig } from '../lib/writedocs-legacy-convert.js';
|
|
17
|
+
import { fetchReadmeSite, normalizeBaseUrl } from '../lib/readme-fetch.js';
|
|
18
|
+
import { convertReadmeSnapshot } from '../lib/readme-convert.js';
|
|
11
19
|
import { validateDocsConfig, formatValidationIssuesDetailed } from '../lib/config-schema.js';
|
|
12
20
|
import { checkContent, formatContentIssues } from '../lib/content-check.js';
|
|
13
21
|
import { log, step, plural, color, displayPath, CliExit, logToStderr } from './output.js';
|
|
@@ -65,10 +73,24 @@ export async function runConvert({ source = 'mintlify', contentDir, force = fals
|
|
|
65
73
|
}
|
|
66
74
|
|
|
67
75
|
const { config, notes } = await from.convert(input, contentDir);
|
|
68
|
-
const text =
|
|
76
|
+
const text = configText(config);
|
|
69
77
|
|
|
70
|
-
|
|
71
|
-
|
|
78
|
+
if (dryRun) {
|
|
79
|
+
process.stdout.write(text);
|
|
80
|
+
} else {
|
|
81
|
+
fs.writeFileSync(outPath, text);
|
|
82
|
+
log.success(`Converted ${from.file} to ${color.bold(displayPath(outPath))}`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
reportNotes(notes);
|
|
86
|
+
await checkPages(contentDir, text, config, from.domainHint);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** writedocs.json's text - which must pass writedocs' own schema: if it
|
|
90
|
+
* doesn't, that's a converter bug, and writing it would only hand the
|
|
91
|
+
* author a broken file. */
|
|
92
|
+
function configText(config) {
|
|
93
|
+
const text = `${JSON.stringify(config, null, 2)}\n`;
|
|
72
94
|
const result = validateDocsConfig(text);
|
|
73
95
|
if (!result.ok) {
|
|
74
96
|
log.error('The converted writedocs.json is not valid - this is a bug in the converter, please report it:');
|
|
@@ -77,23 +99,106 @@ export async function runConvert({ source = 'mintlify', contentDir, force = fals
|
|
|
77
99
|
log.line(`\n${text}`);
|
|
78
100
|
throw new CliExit(1);
|
|
79
101
|
}
|
|
102
|
+
return text;
|
|
103
|
+
}
|
|
80
104
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
105
|
+
function reportNotes(notes) {
|
|
106
|
+
if (!notes.length) return;
|
|
107
|
+
log.line();
|
|
108
|
+
log.info(`${plural(notes.length, 'thing')} couldn't be carried over as-is:`);
|
|
109
|
+
log.line();
|
|
110
|
+
log.line(formatNotes(notes));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Downloads `assets` ({ url, path }) into `contentDir`, a few at a time.
|
|
114
|
+
* Returns the ones that failed. */
|
|
115
|
+
async function downloadAssets(assets, contentDir, { fetchImpl = globalThis.fetch, concurrency = 4, onProgress } = {}) {
|
|
116
|
+
const failed = [];
|
|
117
|
+
let next = 0;
|
|
118
|
+
let done = 0;
|
|
119
|
+
const worker = async () => {
|
|
120
|
+
while (next < assets.length) {
|
|
121
|
+
const asset = assets[next++];
|
|
122
|
+
try {
|
|
123
|
+
const res = await fetchImpl(asset.url);
|
|
124
|
+
if (!res.ok) throw new Error(`answered ${res.status}`);
|
|
125
|
+
const target = path.join(contentDir, asset.path);
|
|
126
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
127
|
+
fs.writeFileSync(target, Buffer.from(await res.arrayBuffer()));
|
|
128
|
+
} catch (err) {
|
|
129
|
+
failed.push({ ...asset, error: err.message });
|
|
130
|
+
}
|
|
131
|
+
onProgress?.(++done, assets.length);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, assets.length) }, worker));
|
|
135
|
+
return failed;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function runReadmeConvert({ site, contentDir, force = false, fetchImpl }) {
|
|
139
|
+
let baseUrl;
|
|
140
|
+
try {
|
|
141
|
+
baseUrl = normalizeBaseUrl(site);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
log.error(`"${site}" isn't a site address: ${err.message}`);
|
|
144
|
+
throw new CliExit(1);
|
|
145
|
+
}
|
|
146
|
+
const outPath = path.join(contentDir, 'writedocs.json');
|
|
147
|
+
if (!force && fs.existsSync(outPath)) {
|
|
148
|
+
log.error(`${displayPath(outPath)} already exists.`);
|
|
149
|
+
log.detail(color.dim('Convert into an empty folder, or pass --force to overwrite the files the conversion writes.'));
|
|
150
|
+
throw new CliExit(1);
|
|
86
151
|
}
|
|
87
152
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
153
|
+
const reading = step(`Reading ${baseUrl}`);
|
|
154
|
+
let snapshot;
|
|
155
|
+
try {
|
|
156
|
+
snapshot = await fetchReadmeSite(baseUrl, {
|
|
157
|
+
fetchImpl,
|
|
158
|
+
onProgress: ({ done, total }) => reading.update?.(`Reading ${baseUrl} - ${done} of ${total} pages`),
|
|
159
|
+
});
|
|
160
|
+
} catch (err) {
|
|
161
|
+
reading.stop();
|
|
162
|
+
log.error(`Couldn't read ${baseUrl}: ${err.message}`);
|
|
163
|
+
throw new CliExit(1);
|
|
164
|
+
}
|
|
165
|
+
reading.stop();
|
|
166
|
+
|
|
167
|
+
const { config, files, assets, notes, counts } = convertReadmeSnapshot(snapshot);
|
|
168
|
+
const text = configText(config);
|
|
169
|
+
|
|
170
|
+
fs.mkdirSync(contentDir, { recursive: true });
|
|
171
|
+
for (const file of files) {
|
|
172
|
+
const target = path.join(contentDir, file.path);
|
|
173
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
174
|
+
fs.writeFileSync(target, file.content);
|
|
175
|
+
}
|
|
176
|
+
fs.writeFileSync(outPath, text);
|
|
177
|
+
|
|
178
|
+
const downloading = step(`Downloading ${plural(assets.length, 'image')}`);
|
|
179
|
+
const failed = await downloadAssets(assets, contentDir, {
|
|
180
|
+
fetchImpl,
|
|
181
|
+
onProgress: (done, total) => downloading.update?.(`Downloading images - ${done} of ${total}`),
|
|
182
|
+
});
|
|
183
|
+
downloading.stop();
|
|
184
|
+
|
|
185
|
+
const parts = [plural(counts.pages, 'page')];
|
|
186
|
+
if (counts.endpoints) parts.push(`${counts.endpoints} of them API operations`);
|
|
187
|
+
if (counts.recipes) parts.push(plural(counts.recipes, 'recipe'));
|
|
188
|
+
log.success(`Converted ${baseUrl} into ${color.bold(displayPath(contentDir))}: ${parts.join(', ')}, ${plural(assets.length - failed.length, 'image')}`);
|
|
189
|
+
if (failed.length) {
|
|
91
190
|
log.line();
|
|
92
|
-
log.
|
|
191
|
+
log.warn(`${plural(failed.length, 'image')} couldn't be downloaded - the pages point at a file that isn't there:`);
|
|
192
|
+
for (const f of failed) log.detail(`${f.path} ${color.dim(`${f.url} (${f.error})`)}`);
|
|
93
193
|
}
|
|
94
194
|
|
|
95
|
-
|
|
96
|
-
|
|
195
|
+
reportNotes(notes);
|
|
196
|
+
await checkPages(contentDir, text, config, '(ReadMe had no custom domain set.)');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// The pages, checked against the converted config - what's left to fix
|
|
200
|
+
// before the first build.
|
|
201
|
+
async function checkPages(contentDir, text, config, domainHint) {
|
|
97
202
|
const checking = step('Checking pages');
|
|
98
203
|
const content = await checkContent(contentDir, text);
|
|
99
204
|
// The domain reminder comes once, at the end, with where the source tool
|
|
@@ -118,7 +223,7 @@ export async function runConvert({ source = 'mintlify', contentDir, force = fals
|
|
|
118
223
|
else log.success(summary);
|
|
119
224
|
if (!config.domain) {
|
|
120
225
|
log.info(
|
|
121
|
-
`Next: set "domain" in writedocs.json to your site's URL - it turns on sitemap.xml and absolute links for social previews. ${
|
|
226
|
+
`Next: set "domain" in writedocs.json to your site's URL - it turns on sitemap.xml and absolute links for social previews. ${domainHint}`
|
|
122
227
|
);
|
|
123
228
|
}
|
|
124
229
|
}
|
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
// Turns a ReadMe site, read by lib/readme-fetch.js into a snapshot, into a
|
|
2
|
+
// writedocs project: the pages, the OpenAPI files, writedocs.json, and the
|
|
3
|
+
// images to download - `writedocs convert --readme <site>`
|
|
4
|
+
// (src/cli/convert.js). A pure function of the snapshot: nothing here
|
|
5
|
+
// touches the network or the disk.
|
|
6
|
+
//
|
|
7
|
+
// The project keeps ReadMe's addresses, so links and search results that
|
|
8
|
+
// point at the old site keep working on the new one:
|
|
9
|
+
//
|
|
10
|
+
// /docs/<slug> guides -> docs/<slug>.mdx
|
|
11
|
+
// /reference/<slug> reference -> reference/<slug>.mdx
|
|
12
|
+
// /recipes/<slug> recipes -> recipes/<slug>.mdx
|
|
13
|
+
// / landing page -> index.mdx (mode: custom)
|
|
14
|
+
//
|
|
15
|
+
// Navigation: each ReadMe section (Guides, API Reference, Recipes) is a
|
|
16
|
+
// tab, named as the site names it; each sidebar category is a group; a page
|
|
17
|
+
// with child pages is a group whose label opens that page (or a plain group
|
|
18
|
+
// when the page is empty - ReadMe's API tag pages). A "link" page is an
|
|
19
|
+
// external link in the sidebar. Hidden pages stay in the navigation with
|
|
20
|
+
// `hidden: true`, which keeps them out of the sidebar but builds them.
|
|
21
|
+
//
|
|
22
|
+
// API reference: an endpoint page is a page with `openapi: "<file> METHOD
|
|
23
|
+
// /path"` frontmatter, so it keeps its own address, title and place in the
|
|
24
|
+
// sidebar. The OpenAPI file is ReadMe's API definition, written to
|
|
25
|
+
// openapi/<its file name>.
|
|
26
|
+
|
|
27
|
+
import { convertReadmeBody, makeLinkRewriter, wrapHtml, README_HTML_CLASS, README_HTML_CSS } from './readme-mdx.js';
|
|
28
|
+
import { convertRecipe } from './readme-recipes.js';
|
|
29
|
+
import { htmlToMdx, scopeCustomCss } from './readme-html.js';
|
|
30
|
+
import { Notes } from './mintlify-convert.js';
|
|
31
|
+
import { parseHex, contrastRatio } from './color.js';
|
|
32
|
+
import { posix } from 'node:path';
|
|
33
|
+
|
|
34
|
+
// writedocs' dark background when `styles.background` doesn't set one.
|
|
35
|
+
const DARK_BACKGROUND = '#0b1120';
|
|
36
|
+
|
|
37
|
+
/** A version of `hex` readable as link text on the dark background - mixed
|
|
38
|
+
* toward white until it has 4.5:1 contrast - or null when `hex` already
|
|
39
|
+
* does (or isn't a hex color). ReadMe sites are often light-only, with a
|
|
40
|
+
* dark brand color no one ever saw on a dark page. */
|
|
41
|
+
export function darkModePrimary(hex) {
|
|
42
|
+
const rgb = parseHex(hex);
|
|
43
|
+
if (!rgb || (contrastRatio(hex, DARK_BACKGROUND) ?? 0) >= 4.5) return null;
|
|
44
|
+
const toHex = (c) => `#${c.map((v) => Math.round(v).toString(16).padStart(2, '0')).join('')}`;
|
|
45
|
+
const [r, g, b] = Array.isArray(rgb) ? rgb : [rgb.r, rgb.g, rgb.b];
|
|
46
|
+
for (let t = 0.05; t <= 1; t += 0.05) {
|
|
47
|
+
const mixed = toHex([r, g, b].map((v) => v + (255 - v) * t));
|
|
48
|
+
if (contrastRatio(mixed, DARK_BACKGROUND) >= 4.5) return mixed;
|
|
49
|
+
}
|
|
50
|
+
return '#ffffff';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const README_FILES = /(^|\.)readme\.io$/i;
|
|
54
|
+
|
|
55
|
+
/** YAML frontmatter from an object; strings JSON-quoted (valid YAML). */
|
|
56
|
+
export function frontmatter(fields) {
|
|
57
|
+
const lines = ['---'];
|
|
58
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
59
|
+
if (value === undefined || value === null || value === false || value === '') continue;
|
|
60
|
+
lines.push(`${key}: ${typeof value === 'string' ? JSON.stringify(value) : JSON.stringify(value)}`);
|
|
61
|
+
}
|
|
62
|
+
lines.push('---');
|
|
63
|
+
return lines.join('\n');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A file name for a downloaded image: the URL's path, made safe. */
|
|
67
|
+
export function imageFileName(url) {
|
|
68
|
+
const u = new URL(url);
|
|
69
|
+
let name = u.pathname
|
|
70
|
+
.split('/')
|
|
71
|
+
.filter(Boolean)
|
|
72
|
+
.map((part) => {
|
|
73
|
+
try {
|
|
74
|
+
return decodeURIComponent(part);
|
|
75
|
+
} catch {
|
|
76
|
+
return part;
|
|
77
|
+
}
|
|
78
|
+
})
|
|
79
|
+
.join('-');
|
|
80
|
+
name = name.replace(/[^\w.-]+/g, '-').replace(/-{2,}/g, '-').replace(/^[-.]+/, '');
|
|
81
|
+
return name || 'image';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Rebuilds an OpenAPI file from the one-operation specs endpoint pages
|
|
85
|
+
* embed - when the registry couldn't be read. */
|
|
86
|
+
export function mergeEmbeddedSpecs(specs) {
|
|
87
|
+
let merged = null;
|
|
88
|
+
for (const spec of specs) {
|
|
89
|
+
if (!spec?.paths) continue;
|
|
90
|
+
if (!merged) {
|
|
91
|
+
merged = { ...spec, paths: {}, components: { ...(spec.components ?? {}) } };
|
|
92
|
+
for (const k of Object.keys(merged.components)) merged.components[k] = { ...merged.components[k] };
|
|
93
|
+
}
|
|
94
|
+
for (const [p, ops] of Object.entries(spec.paths)) merged.paths[p] = { ...(merged.paths[p] ?? {}), ...ops };
|
|
95
|
+
for (const [k, group] of Object.entries(spec.components ?? {})) {
|
|
96
|
+
merged.components[k] = { ...(merged.components[k] ?? {}), ...group };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return merged;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function operation(spec, method, path) {
|
|
103
|
+
return spec?.paths?.[path]?.[String(method).toLowerCase()] ?? null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* @param {object} snapshot from fetchReadmeSite()
|
|
108
|
+
* @returns {{
|
|
109
|
+
* config: object,
|
|
110
|
+
* files: { path: string, content: string }[],
|
|
111
|
+
* assets: { url: string, path: string }[],
|
|
112
|
+
* notes: ReturnType<Notes['list']>,
|
|
113
|
+
* counts: { pages: number, endpoints: number, recipes: number, images: number },
|
|
114
|
+
* }}
|
|
115
|
+
*/
|
|
116
|
+
export function convertReadmeSnapshot(snapshot) {
|
|
117
|
+
const notes = new Notes();
|
|
118
|
+
const files = [];
|
|
119
|
+
const assets = new Map(); // url -> path
|
|
120
|
+
const project = snapshot.project ?? {};
|
|
121
|
+
const counts = { pages: 0, endpoints: 0, recipes: 0, images: 0 };
|
|
122
|
+
|
|
123
|
+
const rewriteLink = makeLinkRewriter({ baseUrl: snapshot.baseUrl, subdomain: project.subdomain });
|
|
124
|
+
const localImage = (url) => {
|
|
125
|
+
let u;
|
|
126
|
+
try {
|
|
127
|
+
u = new URL(url);
|
|
128
|
+
} catch {
|
|
129
|
+
return url;
|
|
130
|
+
}
|
|
131
|
+
if (!README_FILES.test(u.hostname)) return rewriteLink(url);
|
|
132
|
+
if (!assets.has(u.href)) {
|
|
133
|
+
let path = `images/${imageFileName(u.href)}`;
|
|
134
|
+
const taken = new Set(assets.values());
|
|
135
|
+
for (let n = 2; taken.has(path); n++) path = path.replace(/(\.[^.]+)?$/, (ext) => `-${n}${ext}`);
|
|
136
|
+
assets.set(u.href, path);
|
|
137
|
+
}
|
|
138
|
+
return `/${assets.get(u.href)}`;
|
|
139
|
+
};
|
|
140
|
+
const glossary = new Map((project.glossary ?? []).map((g) => [String(g.term).toLowerCase(), g.definition]));
|
|
141
|
+
const recipeSlugs = new Set((snapshot.recipes ?? []).map((r) => r.slug));
|
|
142
|
+
// ReadMe's reusable content ("custom blocks", used as `<Duvidas />`): one
|
|
143
|
+
// snippet each, imported by every page that uses it.
|
|
144
|
+
const blocks = new Map();
|
|
145
|
+
for (const page of Object.values(snapshot.pages ?? {})) {
|
|
146
|
+
for (const b of page.customBlocks ?? []) if (/^[A-Z][A-Za-z0-9]*$/.test(b.tag) && !blocks.has(b.tag)) blocks.set(b.tag, b.source);
|
|
147
|
+
}
|
|
148
|
+
const usedBlocks = new Set();
|
|
149
|
+
const ctxFor = (where) => ({
|
|
150
|
+
rewriteLink: (url) => rewriteLink(url, where),
|
|
151
|
+
localImage,
|
|
152
|
+
glossary,
|
|
153
|
+
recipes: recipeSlugs,
|
|
154
|
+
components: new Set(blocks.keys()),
|
|
155
|
+
note: (key, message) => notes.add(key, [where], message),
|
|
156
|
+
});
|
|
157
|
+
/** The import lines for the custom blocks `body` uses, from page `id`. */
|
|
158
|
+
const blockImports = (id, body) => {
|
|
159
|
+
const lines = [];
|
|
160
|
+
for (const tag of blocks.keys()) {
|
|
161
|
+
if (!new RegExp(`<${tag}[\\s/>]`).test(body)) continue;
|
|
162
|
+
usedBlocks.add(tag);
|
|
163
|
+
let rel = posix.relative(posix.dirname(id), `snippets/${tag}.mdx`);
|
|
164
|
+
if (!rel.startsWith('.')) rel = `./${rel}`;
|
|
165
|
+
lines.push(`import ${tag} from '${rel}';`);
|
|
166
|
+
}
|
|
167
|
+
return lines.join('\n');
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
// The OpenAPI files, by ReadMe's definition uri.
|
|
171
|
+
const specs = new Map();
|
|
172
|
+
for (const def of snapshot.openapi ?? []) {
|
|
173
|
+
// The registry's file, with every operation an endpoint page shows that
|
|
174
|
+
// it lacks taken from that page's own embedded spec: the registry can
|
|
175
|
+
// be unreachable, and for an API written page by page in ReadMe's editor
|
|
176
|
+
// it serves the file with no operations at all ("x-readme-fauxas").
|
|
177
|
+
const pages = Object.values(snapshot.pages ?? {}).filter((p) => p.api?.uri === def.uri && p.embeddedSpec);
|
|
178
|
+
const missing = pages.filter((p) => !operation(def.spec, p.api.method, p.api.path));
|
|
179
|
+
const spec = missing.length ? mergeEmbeddedSpecs([def.spec, ...missing.map((p) => p.embeddedSpec)].filter(Boolean)) : def.spec;
|
|
180
|
+
if (!spec) continue;
|
|
181
|
+
if (def.spec && missing.length) {
|
|
182
|
+
notes.add(`spec-filled:${def.uri}`, [def.filename], `${missing.length} of the operations the pages show weren't in the API definition ReadMe serves - they're taken from the endpoint pages.`);
|
|
183
|
+
}
|
|
184
|
+
const path = `openapi/${def.filename.replace(/[^\w.-]+/g, '-')}`;
|
|
185
|
+
specs.set(def.uri, { path, spec });
|
|
186
|
+
files.push({ path, content: `${JSON.stringify(spec, null, 2)}\n` });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const writePage = (id, fields, body) => {
|
|
190
|
+
const imports = body ? blockImports(id, body) : '';
|
|
191
|
+
if (imports) body = `${imports}\n\n${body}`;
|
|
192
|
+
files.push({ path: `${id}.mdx`, content: `${frontmatter(fields)}\n${body ? `\n${body}\n` : ''}` });
|
|
193
|
+
counts.pages++;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const pageRedirects = [];
|
|
197
|
+
|
|
198
|
+
// One sidebar entry -> a navigation item (and its page file).
|
|
199
|
+
const navItem = (section, entry) => {
|
|
200
|
+
const id = `${section}/${entry.slug}`;
|
|
201
|
+
const page = snapshot.pages?.[id];
|
|
202
|
+
const children = (entry.pages ?? []).map((child) => navItem(section, child)).filter(Boolean);
|
|
203
|
+
if (!page) {
|
|
204
|
+
notes.add('unreadable-page', [id], "This page couldn't be read from the site, so it's not in the project.");
|
|
205
|
+
return children.length ? { group: entry.title, pages: children } : null;
|
|
206
|
+
}
|
|
207
|
+
if (page.redirectsTo) {
|
|
208
|
+
// No content of its own (an API tag's page): a plain group, and its
|
|
209
|
+
// old address goes where ReadMe sent it.
|
|
210
|
+
pageRedirects.push({ source: `/${id}`, destination: `/${page.redirectsTo}` });
|
|
211
|
+
return children.length ? { group: entry.title, pages: children } : null;
|
|
212
|
+
}
|
|
213
|
+
if (entry.type === 'link' || page.type === 'link') {
|
|
214
|
+
if (!page.link?.url) {
|
|
215
|
+
notes.add('link-without-url', [id], 'A sidebar link with no address - left out.');
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
return { label: entry.title, href: rewriteLink(page.link.url) };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const fields = { title: page.title ?? entry.title };
|
|
222
|
+
let body = page.body?.trim() ? convertReadmeBody(page.body, ctxFor(id)) : '';
|
|
223
|
+
if (page.api && entry.type === 'endpoint') {
|
|
224
|
+
const spec = specs.get(page.api.uri);
|
|
225
|
+
const op = spec && operation(spec.spec, page.api.method, page.api.path);
|
|
226
|
+
if (!op) {
|
|
227
|
+
notes.add('missing-operation', [id], `${page.api.method.toUpperCase()} ${page.api.path} isn't in the API definition - the page shows only its text.`);
|
|
228
|
+
} else {
|
|
229
|
+
fields.openapi = `${spec.path} ${page.api.method.toUpperCase()} ${page.api.path}`;
|
|
230
|
+
counts.endpoints++;
|
|
231
|
+
}
|
|
232
|
+
// The operation's description is shown on the page already.
|
|
233
|
+
const excerpt = page.excerpt?.trim();
|
|
234
|
+
if (excerpt && excerpt !== op?.description?.trim() && excerpt !== op?.summary?.trim()) fields.description = excerpt;
|
|
235
|
+
} else {
|
|
236
|
+
const description = page.excerpt?.trim() || page.metaDescription?.trim();
|
|
237
|
+
if (description) fields.description = description;
|
|
238
|
+
}
|
|
239
|
+
if (page.hidden || entry.hidden) fields.hidden = true;
|
|
240
|
+
if (entry.deprecated) fields.deprecated = true;
|
|
241
|
+
if (page.robots && /noindex/i.test(page.robots)) fields.noindex = true;
|
|
242
|
+
if (page.metaTitle && page.metaTitle !== fields.title) {
|
|
243
|
+
notes.add('meta-title', [id], `The SEO title "${page.metaTitle}" isn't carried over - the page's <title> is its title.`);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// An empty page with children is a heading in ReadMe's sidebar (an API
|
|
247
|
+
// tag's page): a plain group here.
|
|
248
|
+
const empty = !body && !fields.openapi && !fields.description;
|
|
249
|
+
if (children.length && empty && entry.isBodyEmpty !== false) return { group: fields.title, pages: children };
|
|
250
|
+
writePage(id, fields, body);
|
|
251
|
+
return children.length ? { group: fields.title, page: id, pages: children } : id;
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
const sectionNav = (section) => {
|
|
255
|
+
const out = [];
|
|
256
|
+
for (const category of snapshot.sidebars?.[section] ?? []) {
|
|
257
|
+
const pages = category.pages.map((entry) => navItem(section, entry)).filter(Boolean);
|
|
258
|
+
if (pages.length) out.push({ group: category.title, pages });
|
|
259
|
+
}
|
|
260
|
+
return out;
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
const tabs = [];
|
|
264
|
+
const tabFor = {}; // section -> its tab
|
|
265
|
+
let notFound = null;
|
|
266
|
+
const label = (key, fallback) => project.sections?.[key]?.label || fallback;
|
|
267
|
+
const docsNav = sectionNav('docs');
|
|
268
|
+
if (docsNav.length) tabs.push((tabFor.docs = { tab: label('docs', 'Guides'), pages: docsNav }));
|
|
269
|
+
const recipesNav = [];
|
|
270
|
+
for (const recipe of snapshot.recipes ?? []) {
|
|
271
|
+
const id = `recipes/${recipe.slug}`;
|
|
272
|
+
const { title, body } = convertRecipe(recipe.markdown, ctxFor(id));
|
|
273
|
+
writePage(id, { title: title ?? recipe.title }, body);
|
|
274
|
+
counts.recipes++;
|
|
275
|
+
recipesNav.push(id);
|
|
276
|
+
}
|
|
277
|
+
if (recipesNav.length) tabs.push((tabFor.recipes = { tab: label('recipes', 'Recipes'), pages: recipesNav }));
|
|
278
|
+
const referenceNav = sectionNav('reference');
|
|
279
|
+
if (referenceNav.length) tabs.push((tabFor.reference = { tab: label('reference', 'API Reference'), pages: referenceNav }));
|
|
280
|
+
|
|
281
|
+
// A page read from its ssr-props outside the sidebars: a custom page or a
|
|
282
|
+
// changelog entry. Its body is Markdown, or HTML for an HTML custom page.
|
|
283
|
+
const standalonePage = (id, fallbackTitle, extra = {}) => {
|
|
284
|
+
const page = snapshot.pages?.[id];
|
|
285
|
+
if (!page) {
|
|
286
|
+
notes.add('unreadable-page', [id], "This page couldn't be read from the site, so it's not in the project.");
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
const fields = { title: page.title ?? fallbackTitle };
|
|
290
|
+
const description = page.excerpt?.trim() || page.metaDescription?.trim();
|
|
291
|
+
if (description) fields.description = description;
|
|
292
|
+
Object.assign(fields, extra);
|
|
293
|
+
const body = !page.body?.trim()
|
|
294
|
+
? ''
|
|
295
|
+
: page.contentType === 'html'
|
|
296
|
+
? wrapHtml(htmlToMdx(page.body, { rewriteUrl: (url, name) => (name === 'src' ? localImage(url) : rewriteLink(url, id)) }))
|
|
297
|
+
: convertReadmeBody(page.body, ctxFor(id));
|
|
298
|
+
writePage(id, fields, body);
|
|
299
|
+
return id;
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
// The changelog: a tab of its own, newest first, as llms.txt lists it.
|
|
303
|
+
const changelogNav = (snapshot.changelog ?? []).map((c) => standalonePage(`changelog/${c.slug}`, c.title)).filter(Boolean);
|
|
304
|
+
if (changelogNav.length) tabs.push((tabFor.changelog = { tab: label('changelog', 'Changelog'), pages: changelogNav }));
|
|
305
|
+
|
|
306
|
+
// Custom pages (/page/...): in no sidebar on ReadMe - linked from the
|
|
307
|
+
// landing page or the header. Hidden pages here, so they're built at the
|
|
308
|
+
// same address without showing up in a sidebar. The one ReadMe shows for
|
|
309
|
+
// a missing address is the 404 page instead.
|
|
310
|
+
const customNav = [];
|
|
311
|
+
for (const c of snapshot.customPages ?? []) {
|
|
312
|
+
if (c.slug === project.notFoundPage) {
|
|
313
|
+
const page = snapshot.pages?.[`page/${c.slug}`];
|
|
314
|
+
notFound = { title: page?.title ?? c.title };
|
|
315
|
+
notes.add('not-found-page', [`page/${c.slug}`], "This custom page was the site's \"page not found\" page: its title is notFound.title. Its content isn't carried over - writedocs' page has a title and a description.");
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
const id = standalonePage(`page/${c.slug}`, c.title, { hidden: true });
|
|
319
|
+
if (id) customNav.push(id);
|
|
320
|
+
}
|
|
321
|
+
if (customNav.length) {
|
|
322
|
+
if (tabs.length) tabs[0].pages.push(...customNav);
|
|
323
|
+
else tabs.push({ tab: label('docs', 'Guides'), pages: customNav });
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// Pages found by following links (lib/readme-fetch.js): hidden on ReadMe,
|
|
327
|
+
// so hidden here, in their section's tab - built at the same address,
|
|
328
|
+
// out of the sidebar.
|
|
329
|
+
for (const d of snapshot.discovered ?? []) {
|
|
330
|
+
const [section, ...rest] = d.id.split('/');
|
|
331
|
+
const item =
|
|
332
|
+
section === 'docs' || section === 'reference'
|
|
333
|
+
? navItem(section, { slug: rest.join('/'), title: d.title, type: d.type, hidden: true, pages: [] })
|
|
334
|
+
: standalonePage(d.id, d.title, { hidden: true });
|
|
335
|
+
if (typeof item !== 'string') continue;
|
|
336
|
+
const tab = tabFor[section] ?? tabs[0];
|
|
337
|
+
if (tab) tab.pages.push(item);
|
|
338
|
+
else tabs.push((tabFor[section] = { tab: label(section, 'Guides'), pages: [item] }));
|
|
339
|
+
}
|
|
340
|
+
if (snapshot.discovered?.length) {
|
|
341
|
+
notes.add('discovered', ['navigation'], `${snapshot.discovered.length} hidden pages - out of ReadMe's sidebars, but linked to from other pages - were found and kept as hidden pages.`);
|
|
342
|
+
}
|
|
343
|
+
for (const r of snapshot.linkRedirects ?? []) pageRedirects.push(r);
|
|
344
|
+
|
|
345
|
+
// The landing page.
|
|
346
|
+
const landing = (project.landingPage ?? []).filter((s) => s.html || s.title || s.text);
|
|
347
|
+
if (landing.length) {
|
|
348
|
+
const parts = [];
|
|
349
|
+
for (const section of landing) {
|
|
350
|
+
if (section.type === 'html' && section.html) {
|
|
351
|
+
parts.push(wrapHtml(htmlToMdx(section.html, { rewriteUrl: (url, name) => (name === 'src' ? localImage(url) : rewriteLink(url, 'index')) }), 'rm-LandingPage'));
|
|
352
|
+
} else {
|
|
353
|
+
if (section.title) parts.push(`## ${section.title}`);
|
|
354
|
+
if (section.text) parts.push(convertReadmeBody(section.text, ctxFor('index')));
|
|
355
|
+
notes.add('landing-section', ['index'], `A "${section.type}" section of the landing page was carried over as its title and text only - lay it out again with components.`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
writePage('index', { title: project.name ?? 'Home', mode: 'custom' }, parts.join('\n\n'));
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
for (const tag of usedBlocks) {
|
|
362
|
+
files.push({ path: `snippets/${tag}.mdx`, content: `${convertReadmeBody(blocks.get(tag), ctxFor(`snippets/${tag}`))}\n` });
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const hasHtml = files.some((f) => f.path.endsWith('.mdx') && f.content.includes(`className="${README_HTML_CLASS}`));
|
|
366
|
+
if (hasHtml) files.push({ path: 'readme-html.css', content: README_HTML_CSS });
|
|
367
|
+
// The project's custom CSS, for its hand-written HTML: scoped to it, so
|
|
368
|
+
// the rules for ReadMe's own page can't reach writedocs'.
|
|
369
|
+
if (project.customCss?.trim() && hasHtml) {
|
|
370
|
+
files.push({
|
|
371
|
+
path: 'readme-custom.css',
|
|
372
|
+
content: `/* Written by writedocs convert --readme: the ReadMe project's custom CSS,\n applied only inside the HTML converted from ReadMe (.${README_HTML_CLASS}). */\n${scopeCustomCss(project.customCss, `.${README_HTML_CLASS}`)}`,
|
|
373
|
+
});
|
|
374
|
+
notes.add('custom-css', ['readme-custom.css'], "The project's custom CSS is in readme-custom.css, applied only inside the HTML converted from ReadMe (the landing page and HTML blocks) - its rules for ReadMe's own header and sidebar don't apply. Review it, and remove what isn't needed.");
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
if (project.sections?.changelog?.visible && !changelogNav.length) {
|
|
378
|
+
notes.add('changelog', ['changelog'], "The site's changelog couldn't be read (llms.txt lists no entries) - add its entries as pages (the Update component suits them).");
|
|
379
|
+
}
|
|
380
|
+
if (project.customCss?.trim() && !hasHtml) notes.add('custom-css', ['appearance'], 'The project has custom CSS - not carried over: it styles ReadMe\'s own page, and no HTML was converted for it to style. See "Custom CSS and scripts".');
|
|
381
|
+
if (project.customJs) notes.add('custom-js', ['appearance'], 'The project has custom JavaScript - not carried over.');
|
|
382
|
+
|
|
383
|
+
// writedocs.json.
|
|
384
|
+
const config = { name: project.name || new URL(snapshot.baseUrl).hostname };
|
|
385
|
+
if (project.description) config.description = project.description;
|
|
386
|
+
if (project.customDomain) config.domain = project.customDomain;
|
|
387
|
+
const styles = {};
|
|
388
|
+
if (project.colors?.primary) {
|
|
389
|
+
styles.colors = { primary: project.colors.primary };
|
|
390
|
+
const dark = project.colors.primaryDark || darkModePrimary(project.colors.primary);
|
|
391
|
+
if (dark) styles.colors.dark = { primary: dark };
|
|
392
|
+
if (dark && !project.colors.primaryDark) {
|
|
393
|
+
notes.add('dark-primary', ['styles.colors.dark.primary'], `The brand color ${project.colors.primary} is too dark to read on a dark page, and ReadMe had no dark-mode color - set to ${dark}, a lighter version of it. Change it if the brand has its own.`);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
const logoLight = project.logo?.light ? localImage(project.logo.light) : null;
|
|
397
|
+
const logoDark = project.logo?.dark ? localImage(project.logo.dark) : null;
|
|
398
|
+
if (logoLight && logoDark && logoLight !== logoDark) styles.logo = { light: logoLight, dark: logoDark };
|
|
399
|
+
else if (logoLight || logoDark) styles.logo = logoLight || logoDark;
|
|
400
|
+
if (project.favicon) styles.favicon = localImage(project.favicon);
|
|
401
|
+
if (project.theme === 'light' || project.theme === 'dark') styles.appearance = { default: project.theme };
|
|
402
|
+
if (Object.keys(styles).length) config.styles = styles;
|
|
403
|
+
// index.mdx is the home page whether or not the navigation lists it.
|
|
404
|
+
config.navigation = tabs.length > 1 ? { tabs } : tabs[0]?.pages ?? [];
|
|
405
|
+
if (notFound) config.notFound = notFound;
|
|
406
|
+
|
|
407
|
+
const redirects = [...pageRedirects];
|
|
408
|
+
for (const r of project.redirects ?? []) {
|
|
409
|
+
const source = r.source ?? r.from;
|
|
410
|
+
const destination = r.destination ?? r.to;
|
|
411
|
+
if (typeof source !== 'string' || typeof destination !== 'string') continue;
|
|
412
|
+
if (/[*:]/.test(source)) {
|
|
413
|
+
notes.add('pattern-redirect', ['redirects'], `The redirect from ${source} uses a pattern - writedocs redirects match one exact path, so it's left out.`);
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
redirects.push({ source: rewriteLink(source), destination: rewriteLink(destination) });
|
|
417
|
+
}
|
|
418
|
+
// One redirect per address, and none away from a page the project has.
|
|
419
|
+
const pageAddresses = new Set(files.filter((f) => f.path.endsWith('.mdx')).map((f) => `/${f.path.replace(/\.mdx$/, '')}`));
|
|
420
|
+
const bySource = new Map();
|
|
421
|
+
for (const r of redirects) if (!bySource.has(r.source) && !pageAddresses.has(r.source)) bySource.set(r.source, r);
|
|
422
|
+
if (bySource.size) config.redirects = [...bySource.values()];
|
|
423
|
+
if (project.variables?.length) {
|
|
424
|
+
config.variables = Object.fromEntries(project.variables.map((v) => [v.name, String(v.default ?? v.name)]));
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
for (const problem of snapshot.problems ?? []) notes.add(`fetch:${problem.message}`, [problem.where], problem.message);
|
|
428
|
+
|
|
429
|
+
counts.images = assets.size;
|
|
430
|
+
return {
|
|
431
|
+
config,
|
|
432
|
+
files,
|
|
433
|
+
assets: [...assets].map(([url, path]) => ({ url, path })),
|
|
434
|
+
notes: notes.list(),
|
|
435
|
+
counts,
|
|
436
|
+
};
|
|
437
|
+
}
|