@writedocs/generator 0.10.14 → 0.10.15

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.
@@ -1,384 +1,418 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import SwaggerParser from '@apidevtools/swagger-parser';
4
- import matter from 'gray-matter';
5
- import { writedocsTempDir } from '../lib/writedocs-temp-dir.js';
6
- import { parseOpenApiRef, openApiOperationKey, specDirName } from '../lib/openapi-ref.js';
7
- import { findAllPages } from '../lib/pages.js';
8
- import { readConfigText } from '../lib/config-file.js';
9
- import { HTTP_METHODS, collectOpenApiGroups } from '../lib/openapi-spec.js';
10
-
11
-
12
- /** Canonical "METHOD /path" key used everywhere an operation needs to be
13
- * identified: the manifest, a hand-written page's `openapi:` frontmatter,
14
- * and the ApiPlayground component's own `operation` prop all use exactly
15
- * this format, so no separate id scheme needs to be invented or kept in
16
- * sync. */
17
- function operationKey(method, urlPath) {
18
- return `${method.toUpperCase()} ${urlPath}`;
19
- }
20
-
21
- /** Filesystem-safe form of an operation key, for the per-operation JSON
22
- * file written under writedocsTempDir()/openapi/<path>/operations/ - the
23
- * sanitization only needs to be *stable and collision-free*, not
24
- * reversible (the operation's own method/path are stored inside the
25
- * JSON body too). */
26
- function operationFileName(method, urlPath) {
27
- return `${method.toLowerCase()}_${urlPath.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_+|_+$/g, '')}.json`;
28
- }
29
-
30
- function slugify(value) {
31
- return (
32
- value
33
- .toLowerCase()
34
- .replace(/[{}]/g, '')
35
- .replace(/[^a-z0-9]+/g, '-')
36
- .replace(/^-+|-+$/g, '') || 'root'
37
- );
38
- }
39
-
40
- /** Strips leading/trailing slashes from a group's `openapi.path`, giving
41
- * the value used both as the URL prefix segment and as this spec's own
42
- * namespace directory under writedocsTempDir()/openapi/ - e.g. "/api" -> "api",
43
- * "/v2/api/" -> "v2/api" (multi-segment paths just nest normally, both
44
- * as generated docs/ subdirectories and as a manifest directory path). */
45
- function normalizePathPrefix(rawPath) {
46
- return rawPath.replace(/^\/+|\/+$/g, '');
47
- }
48
-
49
- /** The generated stub's own file id (writedocs.json-navigation-facing path,
50
- * and the actual URL it's served at) for an operation with no
51
- * hand-written override - namespaced under the owning group's own
52
- * `path` prefix (so two openapi groups never collide with each other),
53
- * then grouped by its first tag (or "untagged") purely for directory
54
- * tidiness, mirroring how a hand-authored API reference is usually
55
- * organized. Also doubles as the stub's own on-disk path relative to
56
- * writedocsTempDir()'s generated-docs/ directory (see
57
- * generateApiPagesForGroup below) -
58
- * there's no docs/ tree to avoid colliding with any more (unlike a
59
- * hand-written page, which could live anywhere), so this can be the
60
- * literal file path too, with no separate "_generated/" prefix needed
61
- * to keep it out of a hand-written page's own namespace. */
62
- function generatedSlugFor(pathPrefix, method, urlPath, tags) {
63
- const tagSlug = slugify(tags[0] ?? 'untagged');
64
- const opSlug = slugify(`${method}-${urlPath}`);
65
- return `${pathPrefix}/${tagSlug}/${opSlug}`;
66
- }
67
-
68
- /** Directories at the content root a hand-written-override scan never
69
- * descends into - mirrors EXCLUDED_TOP_LEVEL_DIRS in lib/config.ts's
70
- * findAllPages() exactly (this file deliberately doesn't import that TS
71
- * module - see collectOpenApiGroups()'s own doc comment on the same
72
- * point - so the same small list is just duplicated here). docs/ has no
73
- * special status - scanned like any other folder, same as page
74
- * discovery itself. */
75
- const OVERRIDE_SCAN_EXCLUDED_DIRS = new Set(['node_modules', 'dist', '.astro', '.writedocs', 'public', '.git']);
76
-
77
- /** Recursively scans `contentDir` for .md/.mdx files claiming an
78
- * operation via frontmatter `openapi: "METHOD /path"`, recording each
79
- * one's file id - its path relative to `contentDir`, extension
80
- * stripped, trailing `/index` segment dropped (mirroring Astro's own
81
- * default id computation exactly - see fileIdForEntry()'s comment in
82
- * lib/config.ts for why that stripping matters: without it, an override
83
- * page at e.g. `docs/webhooks/index.mdx` would be recorded under a file
84
- * id ("docs/webhooks/index") the rest of the routing pipeline would
85
- * never actually resolve, since the page's real id is "docs/webhooks") -
86
- * into `overrides`, skipping OVERRIDE_SCAN_EXCLUDED_DIRS at the content
87
- * root's own top level. */
88
- function scanDirForOverrides(dir, relBase, overrides) {
89
- let entries;
90
- try {
91
- entries = fs.readdirSync(dir, { withFileTypes: true });
92
- } catch {
93
- return;
94
- }
95
- for (const entry of entries) {
96
- const full = path.join(dir, entry.name);
97
- const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
98
- if (entry.isDirectory()) {
99
- if (relBase === '' && OVERRIDE_SCAN_EXCLUDED_DIRS.has(entry.name)) continue;
100
- scanDirForOverrides(full, rel, overrides);
101
- continue;
102
- }
103
- if (!/\.mdx?$/i.test(entry.name)) continue;
104
- const raw = fs.readFileSync(full, 'utf-8');
105
- let data;
106
- try {
107
- ({ data } = matter(raw));
108
- } catch {
109
- continue; // invalid frontmatter - `writedocs validate` and the build report it
110
- }
111
- if (typeof data.openapi !== 'string') continue;
112
- const fileId = rel.replace(/\.mdx?$/i, '').replace(/\/index$/, '');
113
- // Keyed by "METHOD /path" whichever form the page wrote - Mintlify's
114
- // "spec.json METHOD /path" included (see lib/openapi-ref.js).
115
- overrides.set(openApiOperationKey(data.openapi) ?? data.openapi.trim().replace(/\s+/g, ' '), fileId);
116
- }
117
- }
118
-
119
- /** Scans for hand-written pages that claim an operation via frontmatter
120
- * `openapi: "METHOD /path"` - these always win over an auto-generated
121
- * stub for the same operation, so an author can add custom prose above
122
- * the playground for any specific endpoint without losing the
123
- * auto-generated coverage for everything else. Scanned once and shared
124
- * across every openapi group in writedocs.json (not scoped to a single spec)
125
- * - simplest to reason about, and in practice a method+path colliding
126
- * across two genuinely different specs mounted in the same site is rare
127
- * enough not to be worth a more elaborate per-spec disambiguation scheme
128
- * unless it turns out to matter. A single scan of the whole content
129
- * directory (docs/ has no special status - see scanDirForOverrides()
130
- * above), so a hand-authored override page works the same wherever it
131
- * lives. */
132
- function findHandWrittenOverrides(contentDir) {
133
- const overrides = new Map(); // operationKey -> file id
134
- scanDirForOverrides(contentDir, '', overrides);
135
- return overrides;
136
- }
137
-
138
- function resolveSecurity(operation, spec) {
139
- const requirements = operation.security ?? spec.security ?? [];
140
- const schemes = spec.components?.securitySchemes ?? {};
141
- return requirements
142
- .flatMap((req) => Object.keys(req))
143
- .map((name) => ({ name, ...schemes[name] }))
144
- .filter((s) => s.type);
145
- }
146
-
147
- function buildOperations(spec) {
148
- const operations = [];
149
- for (const [urlPath, pathItem] of Object.entries(spec.paths ?? {})) {
150
- for (const method of HTTP_METHODS) {
151
- const operation = pathItem[method];
152
- if (!operation) continue;
153
- const parameters = [...(pathItem.parameters ?? []), ...(operation.parameters ?? [])];
154
- operations.push({
155
- method: method.toUpperCase(),
156
- path: urlPath,
157
- operationId: operation.operationId ?? null,
158
- summary: operation.summary ?? null,
159
- description: operation.description ?? null,
160
- tags: operation.tags ?? [],
161
- parameters,
162
- requestBody: operation.requestBody ?? null,
163
- responses: operation.responses ?? {},
164
- servers: operation.servers ?? spec.servers ?? [],
165
- security: resolveSecurity(operation, spec),
166
- });
167
- }
168
- }
169
- return operations;
170
- }
171
-
172
- /** An operation as JSON. A recursive schema - a tree whose nodes contain
173
- * nodes - dereferences into a cycle (SwaggerParser.dereference() resolves
174
- * the $ref to the very same object), which JSON can't hold and the API
175
- * pages couldn't render anyway. Where a schema would contain itself, a
176
- * short stand-in takes its place: its type and title, marked
177
- * x-circular. Shared, non-recursive schemas are written in full each time,
178
- * as before. */
179
- function operationJson(operation) {
180
- const ancestors = [];
181
- const cut = (node) => {
182
- if (node === null || typeof node !== 'object') return node;
183
- if (ancestors.includes(node)) {
184
- return { ...(node.type ? { type: node.type } : {}), ...(node.title ? { title: node.title } : {}), 'x-circular': true };
185
- }
186
- ancestors.push(node);
187
- const out = Array.isArray(node) ? node.map(cut) : Object.fromEntries(Object.entries(node).map(([k, v]) => [k, cut(v)]));
188
- ancestors.pop();
189
- return out;
190
- };
191
- return JSON.stringify(cut(operation), null, 2);
192
- }
193
-
194
- function rmrf(dir) {
195
- fs.rmSync(dir, { recursive: true, force: true });
196
- }
197
-
198
- /** Generates every page for one `{ group, openapi: { src, path } }`
199
- * navigation node: dereferences its spec, writes a stub page per
200
- * operation (unless a hand-written override already claims it), and
201
- * writes this spec's own manifest + resolved operation JSON under
202
- * writedocsTempDir()'s openapi/<path>/ directory - namespaced by `path` so multiple specs
203
- * in the same writedocs.json never collide with each other on disk, exactly
204
- * as they won't collide in the URL space either (both keyed off the
205
- * same `path` value). */
206
- async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary }) {
207
- const pathPrefix = normalizePathPrefix(group.openapi.path);
208
- const specPath = path.resolve(contentDir, group.openapi.src);
209
- if (!fs.existsSync(specPath)) {
210
- throw new Error(
211
- `[writedocs] writedocs.json's "${group.group}" group has openapi.src "${group.openapi.src}" ` +
212
- `(resolved to ${specPath}), which doesn't exist`
213
- );
214
- }
215
-
216
- const spec = await SwaggerParser.dereference(specPath);
217
- const operations = buildOperations(spec);
218
-
219
- const openapiOutDir = path.join(writedocsTempDir(contentDir), 'openapi', pathPrefix);
220
- fs.mkdirSync(path.join(openapiOutDir, 'operations'), { recursive: true });
221
-
222
- const manifest = [];
223
- for (const operation of operations) {
224
- const key = operationKey(operation.method, operation.path);
225
- const overrideSlug = overrides.get(key);
226
- const generated = !overrideSlug;
227
- const slug = overrideSlug ?? generatedSlugFor(pathPrefix, operation.method, operation.path, operation.tags);
228
- const title = operation.summary ?? `${operation.method} ${operation.path}`;
229
-
230
- if (generated) {
231
- // Written under writedocsTempDir()'s generated-docs/ directory
232
- // (its own content collection - see content.config.ts) rather than
233
- // anywhere inside the project itself, so a site's own project
234
- // folder never shows these machine-generated files when a reader
235
- // browses it directly. `slug` here doubles as
236
- // this file's own path (relative to that collection's base) and
237
- // its frontmatter override, so the page's served URL is pinned to
238
- // exactly this value regardless of whatever id Astro's own
239
- // default (path-derived) computation would otherwise have picked.
240
- const filePath = path.join(generatedDocsDir, `${slug}.mdx`);
241
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
242
- const frontmatter = [
243
- '---',
244
- `title: ${JSON.stringify(title)}`,
245
- operation.description ? `description: ${JSON.stringify(operation.description)}` : null,
246
- `openapi: ${JSON.stringify(key)}`,
247
- `slug: ${JSON.stringify(slug)}`,
248
- '---',
249
- '',
250
- ]
251
- .filter((line) => line !== null)
252
- .join('\n');
253
- fs.writeFileSync(filePath, frontmatter);
254
- }
255
-
256
- manifest.push({ slug, method: operation.method, path: operation.path, tags: operation.tags, title, generated });
257
-
258
- const opFile = path.join(openapiOutDir, 'operations', operationFileName(operation.method, operation.path));
259
- fs.writeFileSync(opFile, operationJson(operation));
260
- }
261
-
262
- fs.writeFileSync(path.join(openapiOutDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
263
- summary.groups.push({ group: group.group, src: group.openapi.src, operations: operations.length });
264
- }
265
-
266
- /**
267
- * Runs before Astro starts (both `writedocs dev` and `writedocs build`):
268
- * finds every `{ group, openapi: { src, path } }` node anywhere in
269
- * writedocs.json's `navigation` tree, and for each one, parses its spec and
270
- * either points each operation at an existing hand-written page
271
- * (frontmatter `openapi: "METHOD /path"`) or writes a minimal generated
272
- * stub under writedocsTempDir()'s generated-docs/ directory - its own
273
- * content collection (see content.config.ts), kept entirely out of the
274
- * project itself so a site's own project folder never shows these
275
- * machine-generated files. (An earlier version of this tried
276
- * docs/_generated/ - and, before that, a docs/.generated/ dot-directory,
277
- * which Astro's glob loader silently skips outright since fast-glob-style
278
- * dotfile exclusion can't be turned off through its public options -
279
- * before settling on a fully separate collection instead, which
280
- * sidesteps both problems.) Also writes an openapi/<path>/manifest.json
281
- * (consumed by lib/config.ts to expand a group's `openapi` shorthand into
282
- * concrete `{ group, pages }`) and one resolved operation JSON per
283
- * operation under openapi/<path>/operations/ (consumed by
284
- * ApiPlayground.astro/ApiReferencePanel.astro at render time - keeping
285
- * the actual $ref dereferencing work in this one place rather than
286
- * repeating it, or re-adding swagger-parser as an Astro/Vite-side
287
- * dependency, per page render), both also under writedocsTempDir(). Each
288
- * spec's own output is namespaced under its group's `path`, so any number
289
- * of openapi groups can coexist in one writedocs.json without colliding with
290
- * each other.
291
- *
292
- * No-ops (after clearing any stale output from a previous run) if
293
- * writedocs.json's navigation has no openapi groups at all - most sites don't
294
- * have one.
295
- *
296
- * Prints nothing: returns what it did, for the CLI to report -
297
- * { groups: [{ group, src, operations }], pageSpecs: [{ spec, operations }],
298
- * warnings: [message] }.
299
- */
300
- export async function generateApiPages({ contentDir }) {
301
- const summary = { groups: [], pageSpecs: [], warnings: [] };
302
- const generatedDocsDir = path.join(writedocsTempDir(contentDir), 'generated-docs');
303
- const openapiOutDir = path.join(writedocsTempDir(contentDir), 'openapi');
304
-
305
- let config;
306
- try {
307
- config = JSON.parse(readConfigText(contentDir));
308
- } catch {
309
- return summary; // preflightCheck() (run first, see dev.js/build.js) already reports this
310
- }
311
-
312
- // Always start from a clean slate: a group's `path` (or the group
313
- // itself) may have changed or been removed since the last run, and
314
- // there's no cheap way to tell stale generated output apart from
315
- // still-current output without just regenerating everything.
316
- rmrf(generatedDocsDir);
317
- rmrf(openapiOutDir);
318
-
319
- const groups = collectOpenApiGroups(config.navigation);
320
-
321
- const seenPaths = new Map(); // normalized path -> owning group's label
322
- for (const group of groups) {
323
- const normalized = normalizePathPrefix(group.openapi.path);
324
- const owner = seenPaths.get(normalized);
325
- if (owner) {
326
- throw new Error(
327
- `[writedocs] writedocs.json has two openapi groups both mounted at "${group.openapi.path}" ` +
328
- `("${owner}" and "${group.group}") - give each group's openapi.path a distinct value.`
329
- );
330
- }
331
- seenPaths.set(normalized, group.group);
332
- }
333
-
334
- const overrides = findHandWrittenOverrides(contentDir);
335
- for (const group of groups) {
336
- await generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary });
337
- }
338
-
339
- await parsePageSpecs({ contentDir, openapiOutDir, groupSpecs: groups.map((g) => path.resolve(contentDir, g.openapi.src)), summary });
340
- return summary;
341
- }
342
-
343
- /** Mintlify's page-level form, `openapi: "/spec.json METHOD /path"`: the
344
- * page names its spec itself instead of belonging to an openapi group in
345
- * writedocs.json. Every such spec (that no group already parsed) is parsed
346
- * here and its operations written under openapi/_pages/<spec>/operations/,
347
- * where findOperationFile() (lib/openapi-render.ts) looks for them. No
348
- * pages are generated - the pages that name the spec are the pages. A
349
- * spec that's missing or doesn't parse is a warning, not a build failure:
350
- * its pages show the playground's own "no operation found" notice. */
351
- async function parsePageSpecs({ contentDir, openapiOutDir, groupSpecs, summary }) {
352
- const specs = new Set();
353
- for (const rel of findAllPages(contentDir)) {
354
- let data;
355
- try {
356
- ({ data } = matter(fs.readFileSync(path.join(contentDir, rel), 'utf-8')));
357
- } catch {
358
- continue;
359
- }
360
- const ref = parseOpenApiRef(data?.openapi);
361
- if (ref?.spec) specs.add(ref.spec);
362
- }
363
- for (const spec of specs) {
364
- const specPath = path.resolve(contentDir, spec);
365
- if (groupSpecs.includes(specPath)) continue;
366
- if (!fs.existsSync(specPath)) {
367
- summary.warnings.push(`Pages name the OpenAPI spec "${spec}", which doesn't exist - their API playground shows a notice instead.`);
368
- continue;
369
- }
370
- let operations;
371
- try {
372
- operations = buildOperations(await SwaggerParser.dereference(specPath));
373
- } catch (err) {
374
- summary.warnings.push(`Couldn't parse the OpenAPI spec "${spec}" that pages name: ${err.message}`);
375
- continue;
376
- }
377
- const outDir = path.join(openapiOutDir, '_pages', specDirName(spec), 'operations');
378
- fs.mkdirSync(outDir, { recursive: true });
379
- for (const operation of operations) {
380
- fs.writeFileSync(path.join(outDir, operationFileName(operation.method, operation.path)), operationJson(operation));
381
- }
382
- summary.pageSpecs.push({ spec, operations: operations.length });
383
- }
384
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import SwaggerParser from '@apidevtools/swagger-parser';
4
+ import matter from 'gray-matter';
5
+ import { writedocsTempDir } from '../lib/writedocs-temp-dir.js';
6
+ import { parseOpenApiRef, openApiOperationKey, specDirName } from '../lib/openapi-ref.js';
7
+ import { findAllPages } from '../lib/pages.js';
8
+ import { readConfigText } from '../lib/config-file.js';
9
+ import { HTTP_METHODS, collectOpenApiGroups } from '../lib/openapi-spec.js';
10
+ import { operationMetaDescription } from '../lib/meta-description.js';
11
+ import { writeMovedApiPages, untaggedRedirects } from '../lib/moved-api-pages.js';
12
+
13
+
14
+ /** Canonical "METHOD /path" key used everywhere an operation needs to be
15
+ * identified: the manifest, a hand-written page's `openapi:` frontmatter,
16
+ * and the ApiPlayground component's own `operation` prop all use exactly
17
+ * this format, so no separate id scheme needs to be invented or kept in
18
+ * sync. */
19
+ function operationKey(method, urlPath) {
20
+ return `${method.toUpperCase()} ${urlPath}`;
21
+ }
22
+
23
+ /** Filesystem-safe form of an operation key, for the per-operation JSON
24
+ * file written under writedocsTempDir()/openapi/<path>/operations/ - the
25
+ * sanitization only needs to be *stable and collision-free*, not
26
+ * reversible (the operation's own method/path are stored inside the
27
+ * JSON body too). */
28
+ function operationFileName(method, urlPath) {
29
+ return `${method.toLowerCase()}_${urlPath.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_+|_+$/g, '')}.json`;
30
+ }
31
+
32
+ function slugify(value) {
33
+ return (
34
+ value
35
+ .toLowerCase()
36
+ .replace(/[{}]/g, '')
37
+ .replace(/[^a-z0-9]+/g, '-')
38
+ .replace(/^-+|-+$/g, '') || 'root'
39
+ );
40
+ }
41
+
42
+ /** Strips leading/trailing slashes from a group's `openapi.path`, giving
43
+ * the value used both as the URL prefix segment and as this spec's own
44
+ * namespace directory under writedocsTempDir()/openapi/ - e.g. "/api" -> "api",
45
+ * "/v2/api/" -> "v2/api" (multi-segment paths just nest normally, both
46
+ * as generated docs/ subdirectories and as a manifest directory path). */
47
+ function normalizePathPrefix(rawPath) {
48
+ return rawPath.replace(/^\/+|\/+$/g, '');
49
+ }
50
+
51
+ /** The generated stub's own file id (writedocs.json-navigation-facing path,
52
+ * and the actual URL it's served at) for an operation with no
53
+ * hand-written override - namespaced under the owning group's own
54
+ * `path` prefix (so two openapi groups never collide with each other),
55
+ * then grouped by its first tag purely for directory tidiness, mirroring
56
+ * how a hand-authored API reference is usually organized. An operation
57
+ * with no tag sits directly under the prefix - it used to get an
58
+ * "untagged" segment, which said nothing to a reader and looked like a
59
+ * mistake in the address (legacyUntaggedSlugFor() below is that old
60
+ * address, for the redirect from it). Also doubles as the stub's own on-disk path relative to
61
+ * writedocsTempDir()'s generated-docs/ directory (see
62
+ * generateApiPagesForGroup below) -
63
+ * there's no docs/ tree to avoid colliding with any more (unlike a
64
+ * hand-written page, which could live anywhere), so this can be the
65
+ * literal file path too, with no separate "_generated/" prefix needed
66
+ * to keep it out of a hand-written page's own namespace. */
67
+ function generatedSlugFor(pathPrefix, method, urlPath, tags) {
68
+ const opSlug = slugify(`${method}-${urlPath}`);
69
+ return tags.length ? `${pathPrefix}/${slugify(tags[0])}/${opSlug}` : `${pathPrefix}/${opSlug}`;
70
+ }
71
+
72
+ /** Where an operation with no tag was served before - see generatedSlugFor(). */
73
+ function legacyUntaggedSlugFor(pathPrefix, method, urlPath) {
74
+ return `${pathPrefix}/untagged/${slugify(`${method}-${urlPath}`)}`;
75
+ }
76
+
77
+ /** Directories at the content root a hand-written-override scan never
78
+ * descends into - mirrors EXCLUDED_TOP_LEVEL_DIRS in lib/config.ts's
79
+ * findAllPages() exactly (this file deliberately doesn't import that TS
80
+ * module - see collectOpenApiGroups()'s own doc comment on the same
81
+ * point - so the same small list is just duplicated here). docs/ has no
82
+ * special status - scanned like any other folder, same as page
83
+ * discovery itself. */
84
+ const OVERRIDE_SCAN_EXCLUDED_DIRS = new Set(['node_modules', 'dist', '.astro', '.writedocs', 'public', '.git']);
85
+
86
+ /** Recursively scans `contentDir` for .md/.mdx files claiming an
87
+ * operation via frontmatter `openapi: "METHOD /path"`, recording each
88
+ * one's file id - its path relative to `contentDir`, extension
89
+ * stripped, trailing `/index` segment dropped (mirroring Astro's own
90
+ * default id computation exactly - see fileIdForEntry()'s comment in
91
+ * lib/config.ts for why that stripping matters: without it, an override
92
+ * page at e.g. `docs/webhooks/index.mdx` would be recorded under a file
93
+ * id ("docs/webhooks/index") the rest of the routing pipeline would
94
+ * never actually resolve, since the page's real id is "docs/webhooks") -
95
+ * into `overrides`, skipping OVERRIDE_SCAN_EXCLUDED_DIRS at the content
96
+ * root's own top level. */
97
+ function scanDirForOverrides(dir, relBase, overrides) {
98
+ let entries;
99
+ try {
100
+ entries = fs.readdirSync(dir, { withFileTypes: true });
101
+ } catch {
102
+ return;
103
+ }
104
+ for (const entry of entries) {
105
+ const full = path.join(dir, entry.name);
106
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
107
+ if (entry.isDirectory()) {
108
+ if (relBase === '' && OVERRIDE_SCAN_EXCLUDED_DIRS.has(entry.name)) continue;
109
+ scanDirForOverrides(full, rel, overrides);
110
+ continue;
111
+ }
112
+ if (!/\.mdx?$/i.test(entry.name)) continue;
113
+ const raw = fs.readFileSync(full, 'utf-8');
114
+ let data;
115
+ try {
116
+ ({ data } = matter(raw));
117
+ } catch {
118
+ continue; // invalid frontmatter - `writedocs validate` and the build report it
119
+ }
120
+ if (typeof data.openapi !== 'string') continue;
121
+ const fileId = rel.replace(/\.mdx?$/i, '').replace(/\/index$/, '');
122
+ // Keyed by "METHOD /path" whichever form the page wrote - Mintlify's
123
+ // "spec.json METHOD /path" included (see lib/openapi-ref.js).
124
+ overrides.set(openApiOperationKey(data.openapi) ?? data.openapi.trim().replace(/\s+/g, ' '), fileId);
125
+ }
126
+ }
127
+
128
+ /** Scans for hand-written pages that claim an operation via frontmatter
129
+ * `openapi: "METHOD /path"` - these always win over an auto-generated
130
+ * stub for the same operation, so an author can add custom prose above
131
+ * the playground for any specific endpoint without losing the
132
+ * auto-generated coverage for everything else. Scanned once and shared
133
+ * across every openapi group in writedocs.json (not scoped to a single spec)
134
+ * - simplest to reason about, and in practice a method+path colliding
135
+ * across two genuinely different specs mounted in the same site is rare
136
+ * enough not to be worth a more elaborate per-spec disambiguation scheme
137
+ * unless it turns out to matter. A single scan of the whole content
138
+ * directory (docs/ has no special status - see scanDirForOverrides()
139
+ * above), so a hand-authored override page works the same wherever it
140
+ * lives. */
141
+ function findHandWrittenOverrides(contentDir) {
142
+ const overrides = new Map(); // operationKey -> file id
143
+ scanDirForOverrides(contentDir, '', overrides);
144
+ return overrides;
145
+ }
146
+
147
+ function resolveSecurity(operation, spec) {
148
+ const requirements = operation.security ?? spec.security ?? [];
149
+ const schemes = spec.components?.securitySchemes ?? {};
150
+ return requirements
151
+ .flatMap((req) => Object.keys(req))
152
+ .map((name) => ({ name, ...schemes[name] }))
153
+ .filter((s) => s.type);
154
+ }
155
+
156
+ function buildOperations(spec) {
157
+ const operations = [];
158
+ for (const [urlPath, pathItem] of Object.entries(spec.paths ?? {})) {
159
+ for (const method of HTTP_METHODS) {
160
+ const operation = pathItem[method];
161
+ if (!operation) continue;
162
+ const parameters = [...(pathItem.parameters ?? []), ...(operation.parameters ?? [])];
163
+ operations.push({
164
+ method: method.toUpperCase(),
165
+ path: urlPath,
166
+ operationId: operation.operationId ?? null,
167
+ summary: operation.summary ?? null,
168
+ description: operation.description ?? null,
169
+ tags: operation.tags ?? [],
170
+ parameters,
171
+ requestBody: operation.requestBody ?? null,
172
+ responses: operation.responses ?? {},
173
+ servers: operation.servers ?? spec.servers ?? [],
174
+ security: resolveSecurity(operation, spec),
175
+ });
176
+ }
177
+ }
178
+ return operations;
179
+ }
180
+
181
+ /** An operation as JSON. A recursive schema - a tree whose nodes contain
182
+ * nodes - dereferences into a cycle (SwaggerParser.dereference() resolves
183
+ * the $ref to the very same object), which JSON can't hold and the API
184
+ * pages couldn't render anyway. Where a schema would contain itself, a
185
+ * short stand-in takes its place: its type and title, marked
186
+ * x-circular. Shared, non-recursive schemas are written in full each time,
187
+ * as before. */
188
+ function operationJson(operation) {
189
+ const ancestors = [];
190
+ const cut = (node) => {
191
+ if (node === null || typeof node !== 'object') return node;
192
+ if (ancestors.includes(node)) {
193
+ return { ...(node.type ? { type: node.type } : {}), ...(node.title ? { title: node.title } : {}), 'x-circular': true };
194
+ }
195
+ ancestors.push(node);
196
+ const out = Array.isArray(node) ? node.map(cut) : Object.fromEntries(Object.entries(node).map(([k, v]) => [k, cut(v)]));
197
+ ancestors.pop();
198
+ return out;
199
+ };
200
+ return JSON.stringify(cut(operation), null, 2);
201
+ }
202
+
203
+ function rmrf(dir) {
204
+ fs.rmSync(dir, { recursive: true, force: true });
205
+ }
206
+
207
+ /** Generates every page for one `{ group, openapi: { src, path } }`
208
+ * navigation node: dereferences its spec, writes a stub page per
209
+ * operation (unless a hand-written override already claims it), and
210
+ * writes this spec's own manifest + resolved operation JSON under
211
+ * writedocsTempDir()'s openapi/<path>/ directory - namespaced by `path` so multiple specs
212
+ * in the same writedocs.json never collide with each other on disk, exactly
213
+ * as they won't collide in the URL space either (both keyed off the
214
+ * same `path` value). */
215
+ async function generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves }) {
216
+ const pathPrefix = normalizePathPrefix(group.openapi.path);
217
+ const specPath = path.resolve(contentDir, group.openapi.src);
218
+ if (!fs.existsSync(specPath)) {
219
+ throw new Error(
220
+ `[writedocs] writedocs.json's "${group.group}" group has openapi.src "${group.openapi.src}" ` +
221
+ `(resolved to ${specPath}), which doesn't exist`
222
+ );
223
+ }
224
+
225
+ const spec = await SwaggerParser.dereference(specPath);
226
+ const operations = buildOperations(spec);
227
+
228
+ const openapiOutDir = path.join(writedocsTempDir(contentDir), 'openapi', pathPrefix);
229
+ fs.mkdirSync(path.join(openapiOutDir, 'operations'), { recursive: true });
230
+
231
+ const manifest = [];
232
+ const untagged = [];
233
+ for (const operation of operations) {
234
+ const key = operationKey(operation.method, operation.path);
235
+ const overrideSlug = overrides.get(key);
236
+ const generated = !overrideSlug;
237
+ const slug = overrideSlug ?? generatedSlugFor(pathPrefix, operation.method, operation.path, operation.tags);
238
+ const title = operation.summary ?? `${operation.method} ${operation.path}`;
239
+
240
+ if (generated) {
241
+ // Written under writedocsTempDir()'s generated-docs/ directory
242
+ // (its own content collection - see content.config.ts) rather than
243
+ // anywhere inside the project itself, so a site's own project
244
+ // folder never shows these machine-generated files when a reader
245
+ // browses it directly. `slug` here doubles as
246
+ // this file's own path (relative to that collection's base) and
247
+ // its frontmatter override, so the page's served URL is pinned to
248
+ // exactly this value regardless of whatever id Astro's own
249
+ // default (path-derived) computation would otherwise have picked.
250
+ const filePath = path.join(generatedDocsDir, `${slug}.mdx`);
251
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
252
+ const frontmatter = [
253
+ '---',
254
+ `title: ${JSON.stringify(title)}`,
255
+ operation.description ? `description: ${JSON.stringify(operation.description)}` : null,
256
+ `openapi: ${JSON.stringify(key)}`,
257
+ `slug: ${JSON.stringify(slug)}`,
258
+ // The <meta name="description">: `description` above is the spec's
259
+ // own text, Markdown and all, shown on the page - a search result
260
+ // wants a line of plain text, and wants one even when the spec has
261
+ // no description (lib/meta-description.js).
262
+ 'seo:',
263
+ ` description: ${JSON.stringify(operationMetaDescription(operation))}`,
264
+ '---',
265
+ '',
266
+ ]
267
+ .filter((line) => line !== null)
268
+ .join('\n');
269
+ fs.writeFileSync(filePath, frontmatter);
270
+ if (!operation.tags.length) untagged.push({ oldSlug: legacyUntaggedSlugFor(pathPrefix, operation.method, operation.path), newSlug: slug });
271
+ }
272
+ moves.slugs.add(slug);
273
+
274
+ manifest.push({ slug, method: operation.method, path: operation.path, tags: operation.tags, title, generated });
275
+
276
+ const opFile = path.join(openapiOutDir, 'operations', operationFileName(operation.method, operation.path));
277
+ fs.writeFileSync(opFile, operationJson(operation));
278
+ }
279
+
280
+ fs.writeFileSync(path.join(openapiOutDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
281
+ if (untagged.length) moves.untagged.push({ pathPrefix, moved: untagged });
282
+ summary.groups.push({ group: group.group, src: group.openapi.src, operations: operations.length });
283
+ }
284
+
285
+ /**
286
+ * Runs before Astro starts (both `writedocs dev` and `writedocs build`):
287
+ * finds every `{ group, openapi: { src, path } }` node anywhere in
288
+ * writedocs.json's `navigation` tree, and for each one, parses its spec and
289
+ * either points each operation at an existing hand-written page
290
+ * (frontmatter `openapi: "METHOD /path"`) or writes a minimal generated
291
+ * stub under writedocsTempDir()'s generated-docs/ directory - its own
292
+ * content collection (see content.config.ts), kept entirely out of the
293
+ * project itself so a site's own project folder never shows these
294
+ * machine-generated files. (An earlier version of this tried
295
+ * docs/_generated/ - and, before that, a docs/.generated/ dot-directory,
296
+ * which Astro's glob loader silently skips outright since fast-glob-style
297
+ * dotfile exclusion can't be turned off through its public options -
298
+ * before settling on a fully separate collection instead, which
299
+ * sidesteps both problems.) Also writes an openapi/<path>/manifest.json
300
+ * (consumed by lib/config.ts to expand a group's `openapi` shorthand into
301
+ * concrete `{ group, pages }`) and one resolved operation JSON per
302
+ * operation under openapi/<path>/operations/ (consumed by
303
+ * ApiPlayground.astro/ApiReferencePanel.astro at render time - keeping
304
+ * the actual $ref dereferencing work in this one place rather than
305
+ * repeating it, or re-adding swagger-parser as an Astro/Vite-side
306
+ * dependency, per page render), both also under writedocsTempDir(). Each
307
+ * spec's own output is namespaced under its group's `path`, so any number
308
+ * of openapi groups can coexist in one writedocs.json without colliding with
309
+ * each other.
310
+ *
311
+ * No-ops (after clearing any stale output from a previous run) if
312
+ * writedocs.json's navigation has no openapi groups at all - most sites don't
313
+ * have one.
314
+ *
315
+ * Prints nothing: returns what it did, for the CLI to report -
316
+ * { groups: [{ group, src, operations }], pageSpecs: [{ spec, operations }],
317
+ * warnings: [message] }.
318
+ */
319
+ export async function generateApiPages({ contentDir }) {
320
+ const summary = { groups: [], pageSpecs: [], warnings: [] };
321
+ const generatedDocsDir = path.join(writedocsTempDir(contentDir), 'generated-docs');
322
+ const openapiOutDir = path.join(writedocsTempDir(contentDir), 'openapi');
323
+
324
+ let config;
325
+ try {
326
+ config = JSON.parse(readConfigText(contentDir));
327
+ } catch {
328
+ return summary; // preflightCheck() (run first, see dev.js/build.js) already reports this
329
+ }
330
+
331
+ // Always start from a clean slate: a group's `path` (or the group
332
+ // itself) may have changed or been removed since the last run, and
333
+ // there's no cheap way to tell stale generated output apart from
334
+ // still-current output without just regenerating everything.
335
+ rmrf(generatedDocsDir);
336
+ rmrf(openapiOutDir);
337
+
338
+ const groups = collectOpenApiGroups(config.navigation);
339
+
340
+ const seenPaths = new Map(); // normalized path -> owning group's label
341
+ for (const group of groups) {
342
+ const normalized = normalizePathPrefix(group.openapi.path);
343
+ const owner = seenPaths.get(normalized);
344
+ if (owner) {
345
+ throw new Error(
346
+ `[writedocs] writedocs.json has two openapi groups both mounted at "${group.openapi.path}" ` +
347
+ `("${owner}" and "${group.group}") - give each group's openapi.path a distinct value.`
348
+ );
349
+ }
350
+ seenPaths.set(normalized, group.group);
351
+ }
352
+
353
+ const overrides = findHandWrittenOverrides(contentDir);
354
+ // Untagged operations per group, and every address a generated or
355
+ // overriding page is served at - for the redirects from where untagged
356
+ // operations used to be (lib/moved-api-pages.js).
357
+ const moves = { untagged: [], slugs: new Set() };
358
+ for (const group of groups) {
359
+ await generateApiPagesForGroup({ contentDir, generatedDocsDir, group, overrides, summary, moves });
360
+ }
361
+ const moved = moves.untagged.flatMap(({ pathPrefix, moved: list }) => untaggedRedirects(pathPrefix, list, moves.slugs));
362
+ if (moved.length) writeMovedApiPages(contentDir, moved);
363
+
364
+ const groupSpecs = groups.map((g) => path.resolve(contentDir, g.openapi.src));
365
+ const pageSpecs = await parsePageSpecs({ contentDir, openapiOutDir, groupSpecs, summary });
366
+ // Every spec the site reads, as paths from the project root: these are
367
+ // how the site is built, not files it publishes (lib/project-files.js).
368
+ if (groupSpecs.length || pageSpecs.length) {
369
+ const specs = [...new Set([...groupSpecs, ...pageSpecs].map((abs) => path.relative(contentDir, abs).split(path.sep).join('/')))];
370
+ fs.mkdirSync(openapiOutDir, { recursive: true });
371
+ fs.writeFileSync(path.join(openapiOutDir, 'specs.json'), JSON.stringify(specs, null, 2));
372
+ }
373
+ return summary;
374
+ }
375
+
376
+ /** Mintlify's page-level form, `openapi: "/spec.json METHOD /path"`: the
377
+ * page names its spec itself instead of belonging to an openapi group in
378
+ * writedocs.json. Every such spec (that no group already parsed) is parsed
379
+ * here and its operations written under openapi/_pages/<spec>/operations/,
380
+ * where findOperationFile() (lib/openapi-render.ts) looks for them. No
381
+ * pages are generated - the pages that name the spec are the pages. A
382
+ * spec that's missing or doesn't parse is a warning, not a build failure:
383
+ * its pages show the playground's own "no operation found" notice. */
384
+ async function parsePageSpecs({ contentDir, openapiOutDir, groupSpecs, summary }) {
385
+ const specs = new Set();
386
+ for (const rel of findAllPages(contentDir)) {
387
+ let data;
388
+ try {
389
+ ({ data } = matter(fs.readFileSync(path.join(contentDir, rel), 'utf-8')));
390
+ } catch {
391
+ continue;
392
+ }
393
+ const ref = parseOpenApiRef(data?.openapi);
394
+ if (ref?.spec) specs.add(ref.spec);
395
+ }
396
+ for (const spec of specs) {
397
+ const specPath = path.resolve(contentDir, spec);
398
+ if (groupSpecs.includes(specPath)) continue;
399
+ if (!fs.existsSync(specPath)) {
400
+ summary.warnings.push(`Pages name the OpenAPI spec "${spec}", which doesn't exist - their API playground shows a notice instead.`);
401
+ continue;
402
+ }
403
+ let operations;
404
+ try {
405
+ operations = buildOperations(await SwaggerParser.dereference(specPath));
406
+ } catch (err) {
407
+ summary.warnings.push(`Couldn't parse the OpenAPI spec "${spec}" that pages name: ${err.message}`);
408
+ continue;
409
+ }
410
+ const outDir = path.join(openapiOutDir, '_pages', specDirName(spec), 'operations');
411
+ fs.mkdirSync(outDir, { recursive: true });
412
+ for (const operation of operations) {
413
+ fs.writeFileSync(path.join(outDir, operationFileName(operation.method, operation.path)), operationJson(operation));
414
+ }
415
+ summary.pageSpecs.push({ spec, operations: operations.length });
416
+ }
417
+ return [...specs].map((spec) => path.resolve(contentDir, spec));
418
+ }