1
+/**
2
+ * API reference route guards.
3
+ *
4
+ * fumadocs-openapi's tag grouping silently drops any operation whose tag is
5
+ * not declared in the document's top-level `tags` array (preset-auto:
6
+ * `builder.fromTagName(tag)` returns undefined -> `continue`, no warning).
7
+ * The v10 -> v11 upgrade shipped exactly that: 16 operation pages vanished
8
+ * from the site, sitemap, and search while the checked-in tag landing pages
9
+ * kept rendering quick links that 404ed. Nothing else can catch this class:
10
+ * validate-links only sees markdown links (ApiEndpointsTable hrefs live in a
11
+ * JSX prop), and the integration suite samples fixed routes.
12
+ *
13
+ * Two guards, both derived from the shipped specs rather than snapshots so
14
+ * routine spec syncs (docs-update-data) never churn them:
15
+ * 1. Completeness — every operation/webhook a spec implies maps 1:1 to a page
16
+ * the production loader path actually generates, regardless of the drop
17
+ * mechanism.
18
+ * 2. Quick links — every href serialized into an ApiEndpointsTable in
19
+ * content/reference resolves to a generated page.
20
+ */
21
+import { describe, expect, test } from 'bun:test';
22
+import { readFileSync, readdirSync } from 'node:fs';
23
+import { join, relative } from 'node:path';
24
+import { loader, multiple } from 'fumadocs-core/source';
25
+import { createOpenAPI, openapiSource } from 'fumadocs-openapi/server';
26
+
27
+import { openapi, openapiV3 } from '../../lib/openapi';
28
+import { HIDDEN_API_TAGS } from '../../lib/filter-api-version';
29
+
30
+const DOCS_DIR = join(import.meta.dir, '../..');
31
+
32
+const HTTP_METHODS = [
33
+ 'get',
34
+ 'put',
35
+ 'post',
36
+ 'delete',
37
+ 'options',
38
+ 'head',
39
+ 'patch',
40
+ 'trace',
41
+] as const;
42
+
43
+interface SpecOperation {
44
+ operationId?: string;
45
+ tags?: string[];
46
+}
47
+
48
+interface SpecDocument {
49
+ paths?: Record<string, Record<string, unknown>>;
50
+ webhooks?: Record<string, Record<string, unknown>>;
51
+}
52
+
53
+/** Mirrors the default slugify in fumadocs-openapi's auto preset. */
54
+function slugifyTag(tag: string): string {
55
+ return tag.replace(/\s+/g, '-').toLowerCase();
56
+}
57
+
58
+/** Mirrors the hidden-tag URL filter applied in lib/source.ts. */
59
+function isHiddenReferenceUrl(url: string): boolean {
60
+ for (const tag of HIDDEN_API_TAGS) {
61
+ if (
62
+ url.startsWith(`/reference/api-reference/${tag}/`) ||
63
+ url.startsWith(`/reference/v3/api-reference/${tag}/`)
64
+ ) {
65
+ return true;
66
+ }
67
+ }
68
+ return false;
69
+}
70
+
71
+function* specOperations(document: SpecDocument): Generator<{
72
+ location: string;
73
+ operation: SpecOperation;
74
+}> {
75
+ for (const group of [document.paths, document.webhooks]) {
76
+ for (const [key, pathItem] of Object.entries(group ?? {})) {
77
+ for (const method of HTTP_METHODS) {
78
+ const operation = pathItem?.[method];
79
+ if (!operation || typeof operation !== 'object') continue;
80
+ yield { location: `${method.toUpperCase()} ${key}`, operation };
81
+ }
82
+ }
83
+ }
84
+}
85
+
86
+/**
87
+ * URLs the spec implies: one page per visible (operation, tag) pair, named by
88
+ * operationId — the scheme both fumadocs-openapi (groupBy: 'tag', name
89
+ * algorithm v2) and generate-api-index.ts encode.
90
+ */
91
+function expectedReferenceUrls(document: SpecDocument, baseDir: string): Set<string> {
92
+ const urls = new Set<string>();
93
+ for (const { operation } of specOperations(document)) {
94
+ for (const tag of operation.tags ?? []) {
95
+ const tagSlug = slugifyTag(tag);
96
+ if (HIDDEN_API_TAGS.has(tagSlug)) continue;
97
+ urls.add(`/reference/${baseDir}/${tagSlug}/${operation.operationId}`);
98
+ }
99
+ }
100
+ return urls;
101
+}
102
+
103
+function loadSpec(fileName: string): SpecDocument {
104
+ return JSON.parse(readFileSync(join(DOCS_DIR, 'public', fileName), 'utf-8'));
105
+}
106
+
107
+/**
108
+ * The reference URLs production actually serves, built through the same
109
+ * pipeline as lib/source.ts getReferenceSource (minus the checked-in MDX
110
+ * collection, which bun test cannot load and which contributes no operation
111
+ * pages).
112
+ */
113
+async function generatedReferenceUrls(): Promise<Set<string>> {
114
+ const [latest, v3] = await Promise.all([
115
+ openapiSource(openapi, { groupBy: 'tag', baseDir: 'api-reference' }),
116
+ openapiSource(openapiV3, { groupBy: 'tag', baseDir: 'v3/api-reference' }),
117
+ ]);
118
+ const referenceLoader = loader({
119
+ baseUrl: '/reference',
120
+ source: multiple({ openapi: latest, 'openapi-v3': v3 }),
121
+ });
122
+ return new Set(
123
+ referenceLoader
124
+ .getPages()
125
+ .map((page) => page.url)
126
+ .filter((url) => !isHiddenReferenceUrl(url)),
127
+ );
128
+}
129
+
130
+const generatedUrlsPromise = generatedReferenceUrls();
131
+
132
+describe('API reference route completeness', () => {
133
+ test('every visible operation declares a tag and an operationId', () => {
134
+ const violations: string[] = [];
135
+ for (const fileName of ['openapi.json', 'openapi-v3.json', 'openapi-webhooks.json']) {
136
+ for (const { location, operation } of specOperations(loadSpec(fileName))) {
137
+ const visibleTags = (operation.tags ?? []).filter(
138
+ (tag) => !HIDDEN_API_TAGS.has(slugifyTag(tag)),
139
+ );
140
+ // Untagged operations fall into fumadocs' synthetic "unknown" tag,
141
+ // which is never declared — the page silently vanishes.
142
+ if ((operation.tags ?? []).length === 0) {
143
+ violations.push(`${fileName}: ${location} has no tags`);
144
+ }
145
+ // Without an operationId, fumadocs falls back to a path-derived file
146
+ // name while generate-api-index derives the href from the summary —
147
+ // the quick link is guaranteed to 404.
148
+ if (visibleTags.length > 0 && !operation.operationId) {
149
+ violations.push(`${fileName}: ${location} has no operationId`);
150
+ }
151
+ }
152
+ }
153
+
154
+ expect(violations, violations.join('\n')).toEqual([]);
155
+ });
156
+
157
+ test('every spec operation and webhook yields exactly one generated page', async () => {
158
+ const expected = new Set<string>([
159
+ ...expectedReferenceUrls(loadSpec('openapi.json'), 'api-reference'),
160
+ ...expectedReferenceUrls(loadSpec('openapi-webhooks.json'), 'api-reference'),
161
+ ...expectedReferenceUrls(loadSpec('openapi-v3.json'), 'v3/api-reference'),
162
+ ]);
163
+ const generated = await generatedUrlsPromise;
164
+
165
+ const missing = [...expected].filter((url) => !generated.has(url)).sort();
166
+ const extra = [...generated].filter((url) => !expected.has(url)).sort();
167
+
168
+ expect(expected.size).toBeGreaterThan(0);
169
+ expect(
170
+ missing,
171
+ `pages implied by the OpenAPI specs but not generated (silently dropped):\n${missing.join('\n')}`,
172
+ ).toEqual([]);
173
+ expect(
174
+ extra,
175
+ `generated pages not implied by the OpenAPI specs:\n${extra.join('\n')}`,
176
+ ).toEqual([]);
177
+ });
178
+
179
+ test('the completeness diff flags operations whose tag is undeclared', async () => {
180
+ // The exact v10 -> v11 regression, in miniature: "Projects" is used by an
181
+ // operation but missing from the top-level tags array, and lib/openapi's
182
+ // declareOperationTags normalization is deliberately not applied.
183
+ const document = {
184
+ openapi: '3.0.0',
185
+ info: { title: 'Guard fixture', version: '1' },
186
+ tags: [{ name: 'Auth' }],
187
+ paths: {
188
+ '/v3.1/project/usage/summary': {
189
+ post: {
190
+ tags: ['Projects'],
191
+ operationId: 'postProjectUsageSummary',
192
+ summary: 'Usage summary',
193
+ responses: { '200': { description: 'ok' } },
194
+ },
195
+ },
196
+ '/v3.1/auth/session': {
197
+ get: {
198
+ tags: ['Auth'],
199
+ operationId: 'getSession',
200
+ summary: 'Session',
201
+ responses: { '200': { description: 'ok' } },
202
+ },
203
+ },
204
+ },
205
+ };
206
+
207
+ const server = createOpenAPI({ input: { 'guard-fixture.json': document } });
208
+ const source = await openapiSource(server, { groupBy: 'tag', baseDir: 'api-reference' });
209
+ const generated = new Set(
210
+ loader({ baseUrl: '/reference', source }).getPages().map((page) => page.url),
211
+ );
212
+ const missing = [...expectedReferenceUrls(document, 'api-reference')].filter(
213
+ (url) => !generated.has(url),
214
+ );
215
+
216
+ // fumadocs-openapi still silently drops the undeclared tag...
217
+ expect(generated.has('/reference/api-reference/auth/getSession')).toBe(true);
218
+ // ...and the completeness diff is what surfaces the loss. If this ever
219
+ // fails with `missing` empty, upstream fixed the silent drop and the
220
+ // declareOperationTags workaround in lib/openapi.ts can be retired.
221
+ expect(missing).toEqual([
222
+ '/reference/api-reference/projects/postProjectUsageSummary',
223
+ ]);
224
+ });
225
+});
226
+
227
+describe('API reference quick links', () => {
228
+ function mdxFiles(dir: string): string[] {
229
+ const files: string[] = [];
230
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
231
+ const fullPath = join(dir, entry.name);
232
+ if (entry.isDirectory()) files.push(...mdxFiles(fullPath));
233
+ else if (entry.name.endsWith('.mdx')) files.push(fullPath);
234
+ }
235
+ return files;
236
+ }
237
+
238
+ /** Parses the serialized endpoints of every ApiEndpointsTable in a file. */
239
+ function parseEndpointHrefs(content: string, file: string): string[] {
240
+ const hrefs: string[] = [];
241
+ const prefix = /<ApiEndpointsTable endpoints=\{/g;
242
+ let match: RegExpExecArray | null;
243
+ while ((match = prefix.exec(content)) !== null) {
244
+ const start = match.index + match[0].length;
245
+ const end = content.indexOf('} />', start);
246
+ expect(end, `${file}: unterminated ApiEndpointsTable`).toBeGreaterThan(start);
247
+ const endpoints: { href: string }[] = JSON.parse(content.slice(start, end));
248
+ hrefs.push(...endpoints.map((endpoint) => endpoint.href));
249
+ }
250
+ // A file mentioning the component but yielding no parsed table means the
251
+ // generator's serialization drifted from this extractor — fail loudly
252
+ // instead of silently checking nothing.
253
+ if (content.includes('<ApiEndpointsTable')) {
254
+ expect(hrefs.length, `${file}: found ApiEndpointsTable but extracted no hrefs`).toBeGreaterThan(0);
255
+ }
256
+ return hrefs;
257
+ }
258
+
259
+ test('every ApiEndpointsTable href resolves to a generated reference page', async () => {
260
+ const generated = await generatedUrlsPromise;
261
+ const dead: string[] = [];
262
+ let totalHrefs = 0;
263
+
264
+ for (const file of mdxFiles(join(DOCS_DIR, 'content/reference'))) {
265
+ const content = readFileSync(file, 'utf-8');
266
+ for (const href of parseEndpointHrefs(content, relative(DOCS_DIR, file))) {
267
+ totalHrefs++;
268
+ if (!generated.has(href)) {
269
+ dead.push(`${relative(DOCS_DIR, file)}: ${href}`);
270
+ }
271
+ }
272
+ }
273
+
274
+ // Sanity: the extractor must have found the generated landing pages.
275
+ expect(totalHrefs).toBeGreaterThan(0);
276
+ expect(
277
+ dead,
278
+ `quick links pointing at reference pages that are never generated (would 404):\n${dead.join('\n')}`,
279
+ ).toEqual([]);
280
+ });
281
+});