@writedocs/generator 0.13.3 → 0.13.5

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