6
toolkitsSource,
7
getLLMText,
8
} from '@/lib/source';
9
+import { openapi } from '@/lib/openapi';
10
import { notFound } from 'next/navigation';
11
import { readFile } from 'fs/promises';
12
import { join } from 'path';
14
15
export const revalidate = false;
16
16
-// OpenAPI spec cache
17
-let openapiSpecCache: Record<string, unknown> | null = null;
17
+// Types for OpenAPI structures (from dereferenced document)
18
+interface OpenAPISchema {
19
+ type?: string;
20
+ format?: string;
21
+ description?: string;
22
+ properties?: Record<string, OpenAPISchema>;
23
+ items?: OpenAPISchema;
24
+ required?: string[];
25
+ enum?: string[];
26
+ oneOf?: OpenAPISchema[];
27
+ anyOf?: OpenAPISchema[];
28
+ allOf?: OpenAPISchema[];
29
+ default?: unknown;
30
+ example?: unknown;
31
+ minimum?: number;
32
+ maximum?: number;
33
+ minLength?: number;
34
+ maxLength?: number;
35
+}
36
19
-async function getOpenAPISpec(): Promise<Record<string, unknown>> {
20
- if (openapiSpecCache) return openapiSpecCache;
21
- const filePath = join(process.cwd(), 'public/openapi.json');
22
- const data = await readFile(filePath, 'utf-8');
23
- const spec = JSON.parse(data) as Record<string, unknown>;
24
- openapiSpecCache = spec;
25
- return spec;
37
+interface OpenAPIParameter {
38
+ name: string;
39
+ in: 'query' | 'path' | 'header' | 'cookie';
40
+ description?: string;
41
+ required?: boolean;
42
+ schema?: OpenAPISchema;
43
+ example?: unknown;
44
+}
45
+
46
+interface OpenAPIRequestBody {
47
+ description?: string;
48
+ required?: boolean;
49
+ content?: Record<string, { schema?: OpenAPISchema; example?: unknown }>;
50
+}
51
+
52
+interface OpenAPIResponse {
53
+ description?: string;
54
+ content?: Record<string, { schema?: OpenAPISchema; example?: unknown }>;
55
+}
56
+
57
+interface OpenAPISecurityScheme {
58
+ type: string;
59
+ description?: string;
60
+ name?: string;
61
+ in?: string;
62
+ scheme?: string;
63
+ bearerFormat?: string;
64
}
65
66
interface OpenAPIOperation {
29
- method: string;
30
- path: string;
67
+ summary?: string;
68
+ description?: string;
69
+ operationId?: string;
70
+ parameters?: OpenAPIParameter[];
71
+ requestBody?: OpenAPIRequestBody;
72
+ responses?: Record<string, OpenAPIResponse>;
73
+ security?: Array<Record<string, string[]>>;
74
tags?: string[];
75
}
76
79
description?: string;
80
getAPIPageProps: () => {
81
document: string;
39
- operations?: OpenAPIOperation[];
40
- webhooks?: { name: string; method: string }[];
82
+ operations?: Array<{ method: string; path: string; tags?: string[] }>;
83
+ webhooks?: Array<{ name: string; method: string }>;
84
};
85
}
86
44
-// Helper to render JSON schema properties as markdown
45
-function renderSchemaProperties(
46
- schema: Record<string, unknown>,
47
- indent = 0
48
-): string[] {
87
+// Generate sample value for a schema
88
+function generateSampleValue(schema: OpenAPISchema, depth = 0): unknown {
89
+ if (depth > 3) return '...'; // Prevent infinite recursion
90
+
91
+ if (schema.example !== undefined) return schema.example;
92
+ if (schema.default !== undefined) return schema.default;
93
+ if (schema.enum && schema.enum.length > 0) return schema.enum[0];
94
+
95
+ switch (schema.type) {
96
+ case 'string':
97
+ if (schema.format === 'email') return 'user@example.com';
98
+ if (schema.format === 'uri' || schema.format === 'url') return 'https://example.com';
99
+ if (schema.format === 'date') return '2024-01-15';
100
+ if (schema.format === 'date-time') return '2024-01-15T10:30:00Z';
101
+ if (schema.format === 'uuid') return '550e8400-e29b-41d4-a716-446655440000';
102
+ return 'string';
103
+ case 'integer':
104
+ case 'number':
105
+ return schema.minimum ?? 1;
106
+ case 'boolean':
107
+ return true;
108
+ case 'array':
109
+ if (schema.items) {
110
+ return [generateSampleValue(schema.items, depth + 1)];
111
+ }
112
+ return [];
113
+ case 'object':
114
+ if (schema.properties) {
115
+ const obj: Record<string, unknown> = {};
116
+ for (const [key, prop] of Object.entries(schema.properties)) {
117
+ obj[key] = generateSampleValue(prop, depth + 1);
118
+ }
119
+ return obj;
120
+ }
121
+ return {};
122
+ default:
123
+ return null;
124
+ }
125
+}
126
+
127
+// Render schema as markdown with proper nesting
128
+function renderSchema(schema: OpenAPISchema, indent = 0, maxDepth = 4): string[] {
129
+ if (indent > maxDepth) return [' '.repeat(indent) + '- ...'];
130
+
131
const lines: string[] = [];
132
const prefix = ' '.repeat(indent);
133
+ const required = schema.required || [];
134
135
if (schema.type === 'object' && schema.properties) {
53
- const props = schema.properties as Record<string, Record<string, unknown>>;
54
- const required = (schema.required as string[]) || [];
55
-
56
- for (const [name, prop] of Object.entries(props)) {
136
+ for (const [name, prop] of Object.entries(schema.properties)) {
137
const isRequired = required.includes(name);
58
- const type = (prop.type as string) || 'any';
59
- const desc = (prop.description as string) || '';
60
- const reqMark = isRequired ? ' **(required)**' : '';
138
+ const reqMark = isRequired ? ' *(required)*' : '';
139
+ const typeStr = getTypeString(prop);
140
+ const desc = prop.description ? `: ${prop.description}` : '';
141
62
- lines.push(`${prefix}- \`${name}\` (${type})${reqMark}: ${desc}`);
142
+ lines.push(`${prefix}- \`${name}\` (${typeStr})${reqMark}${desc}`);
143
64
- // Recurse for nested objects
144
+ // Recurse for nested objects/arrays
145
if (prop.type === 'object' && prop.properties) {
66
- lines.push(...renderSchemaProperties(prop, indent + 1));
146
+ lines.push(...renderSchema(prop, indent + 1, maxDepth));
147
+ } else if (prop.type === 'array' && prop.items?.type === 'object' && prop.items.properties) {
148
+ lines.push(`${prefix} - Array items:`);
149
+ lines.push(...renderSchema(prop.items, indent + 2, maxDepth));
150
}
151
}
152
} else if (schema.oneOf || schema.anyOf) {
70
- const variants = (schema.oneOf || schema.anyOf) as Record<string, unknown>[];
71
- lines.push(`${prefix}One of the following:`);
153
+ const variants = schema.oneOf || schema.anyOf || [];
154
+ lines.push(`${prefix}*One of:*`);
155
for (const variant of variants.slice(0, 3)) {
73
- if (variant.type === 'object') {
74
- lines.push(...renderSchemaProperties(variant, indent + 1));
156
+ if (variant.type === 'object' && variant.properties) {
157
+ lines.push(...renderSchema(variant, indent + 1, maxDepth));
158
+ } else {
159
+ lines.push(`${prefix} - ${getTypeString(variant)}`);
160
+ }
161
+ }
162
+ if (variants.length > 3) {
163
+ lines.push(`${prefix} - ... and ${variants.length - 3} more`);
164
+ }
165
+ } else if (schema.allOf) {
166
+ for (const part of schema.allOf) {
167
+ if (part.type === 'object' && part.properties) {
168
+ lines.push(...renderSchema(part, indent, maxDepth));
169
}
170
}
171
}
173
return lines;
174
}
175
82
-// Generate cURL example
83
-function generateCurlExample(
176
+// Get a readable type string
177
+function getTypeString(schema: OpenAPISchema): string {
178
+ if (schema.enum) {
179
+ return `enum: ${schema.enum.slice(0, 3).map(e => `"${e}"`).join(' | ')}${schema.enum.length > 3 ? ' | ...' : ''}`;
180
+ }
181
+ if (schema.type === 'array' && schema.items) {
182
+ return `array<${getTypeString(schema.items)}>`;
183
+ }
184
+ if (schema.format) {
185
+ return `${schema.type} (${schema.format})`;
186
+ }
187
+ return schema.type || 'any';
188
+}
189
+
190
+// Generate cURL example with sample data
191
+function generateCurl(
192
method: string,
193
path: string,
194
baseUrl: string,
87
- hasBody: boolean
195
+ parameters: OpenAPIParameter[] = [],
196
+ requestBody?: OpenAPIRequestBody
197
): string {
89
- const pathWithExample = path.replace(/\{(\w+)\}/g, 'example_$1');
90
- let curl = `curl -X ${method.toUpperCase()} "${baseUrl}${pathWithExample}"`;
198
+ // Build path with sample values
199
+ let url = path;
200
+ const queryParams: string[] = [];
201
+
202
+ for (const param of parameters) {
203
+ const sample = param.example ?? generateSampleValue(param.schema || { type: 'string' });
204
+ if (param.in === 'path') {
205
+ url = url.replace(`{${param.name}}`, String(sample));
206
+ } else if (param.in === 'query' && param.required) {
207
+ queryParams.push(`${param.name}=${encodeURIComponent(String(sample))}`);
208
+ }
209
+ }
210
+
211
+ if (queryParams.length > 0) {
212
+ url += '?' + queryParams.join('&');
213
+ }
214
+
215
+ let curl = `curl -X ${method.toUpperCase()} "${baseUrl}${url}"`;
216
curl += ` \\\n -H "x-api-key: YOUR_API_KEY"`;
92
- if (hasBody) {
217
+
218
+ // Add request body
219
+ if (requestBody?.content?.['application/json']) {
220
curl += ` \\\n -H "Content-Type: application/json"`;
94
- curl += ` \\\n -d '{}'`;
221
+ const schema = requestBody.content['application/json'].schema;
222
+ const example = requestBody.content['application/json'].example;
223
+ const body = example ?? (schema ? generateSampleValue(schema) : {});
224
+ curl += ` \\\n -d '${JSON.stringify(body, null, 2).split('\n').join('\n ')}'`;
225
}
226
+
227
return curl;
228
}
229
99
-// Convert OpenAPI page to markdown
230
+// Convert OpenAPI page to comprehensive markdown
231
async function openapiPageToMarkdown(
232
page: { url: string; data: OpenAPIPageData }
233
): Promise<string> {
234
const { title, description } = page.data;
235
const props = page.data.getAPIPageProps();
105
- const spec = await getOpenAPISpec();
106
- const paths = spec.paths as Record<string, Record<string, unknown>> | undefined;
107
- const securitySchemes = (spec.components as Record<string, unknown>)?.securitySchemes as Record<string, Record<string, unknown>> | undefined;
236
+
237
+ // Get fully dereferenced document from fumadocs-openapi
238
+ const processed = await openapi.getSchema(props.document);
239
+ const spec = processed.dereferenced;
240
+ const paths = spec.paths as Record<string, Record<string, OpenAPIOperation>> | undefined;
241
+ const securitySchemes = (spec.components as Record<string, unknown>)?.securitySchemes as Record<string, OpenAPISecurityScheme> | undefined;
242
const servers = spec.servers as Array<{ url: string; description?: string }> | undefined;
243
const baseUrl = servers?.[0]?.url || 'https://backend.composio.dev';
244
111
- const lines: string[] = [`# ${title} (${page.url})`, ''];
245
+ const lines: string[] = [`# ${title}`, ''];
246
+ lines.push(`**Documentation:** ${page.url}`, '');
247
248
if (description) {
249
lines.push(description, '');
255
const pathData = paths[op.path];
256
if (!pathData) continue;
257
123
- const methodData = pathData[op.method] as Record<string, unknown> | undefined;
124
- if (!methodData) continue;
258
+ const operation = pathData[op.method];
259
+ if (!operation) continue;
260
126
- lines.push(`## ${(op.method as string).toUpperCase()} ${op.path}`, '');
127
- lines.push(`**Base URL:** \`${baseUrl}\``, '');
261
+ lines.push('---', '');
262
+ lines.push(`## ${op.method.toUpperCase()} \`${op.path}\``, '');
263
+ lines.push(`**Endpoint:** \`${baseUrl}${op.path}\``, '');
264
129
- if (methodData.summary) {
130
- lines.push(`${methodData.summary}`, '');
265
+ if (operation.summary) {
266
+ lines.push(`**Summary:** ${operation.summary}`, '');
267
}
268
133
- if (methodData.description) {
134
- lines.push(`${methodData.description}`, '');
269
+ if (operation.description) {
270
+ lines.push(operation.description, '');
271
}
272
273
// Authentication
138
- const security = methodData.security as Array<Record<string, string[]>> | undefined;
274
+ const security = operation.security;
275
if (security && security.length > 0 && securitySchemes) {
276
lines.push('### Authentication', '');
277
+ const authMethods: string[] = [];
278
for (const secReq of security) {
279
for (const schemeName of Object.keys(secReq)) {
280
const scheme = securitySchemes[schemeName];
281
if (scheme) {
145
- const inLoc = scheme.in as string;
146
- const headerName = scheme.name as string;
147
- const schemeDesc = scheme.description as string;
148
- lines.push(`- **${schemeName}**: ${schemeDesc || ''}`);
149
- lines.push(` - Type: \`${scheme.type}\``);
150
- lines.push(` - In: \`${inLoc}\``);
151
- lines.push(` - Header: \`${headerName}\``);
282
+ if (scheme.type === 'apiKey') {
283
+ authMethods.push(`**${schemeName}** - API Key in \`${scheme.in}\` header \`${scheme.name}\``);
284
+ } else if (scheme.type === 'http' && scheme.scheme === 'bearer') {
285
+ authMethods.push(`**${schemeName}** - Bearer token in Authorization header`);
286
+ } else {
287
+ authMethods.push(`**${schemeName}** - ${scheme.type}`);
288
+ }
289
}
290
}
291
}
155
- lines.push('');
292
+ lines.push(authMethods.join(' OR '), '');
293
}
294
158
- // Parameters
159
- const parameters = methodData.parameters as Array<{
160
- name: string;
161
- in: string;
162
- description?: string;
163
- required?: boolean;
164
- schema?: { type?: string; format?: string; default?: unknown };
165
- }> | undefined;
166
-
167
- if (parameters && parameters.length > 0) {
168
- lines.push('### Parameters', '');
169
- lines.push('| Name | In | Required | Type | Description |');
170
- lines.push('|------|-----|----------|------|-------------|');
171
- for (const param of parameters) {
172
- const type = param.schema?.type || 'string';
173
- const format = param.schema?.format ? ` (${param.schema.format})` : '';
174
- const required = param.required ? 'Yes' : 'No';
175
- const desc = (param.description || '').replace(/\|/g, '\\|').replace(/\n/g, ' ');
176
- lines.push(`| ${param.name} | ${param.in} | ${required} | ${type}${format} | ${desc} |`);
295
+ // Path Parameters
296
+ const pathParams = operation.parameters?.filter(p => p.in === 'path') || [];
297
+ if (pathParams.length > 0) {
298
+ lines.push('### Path Parameters', '');
299
+ for (const param of pathParams) {
300
+ const typeStr = getTypeString(param.schema || { type: 'string' });
301
+ lines.push(`- \`${param.name}\` (${typeStr}) *(required)*: ${param.description || ''}`);
302
}
303
lines.push('');
304
}
305
181
- // Request body
182
- const requestBody = methodData.requestBody as {
183
- description?: string;
184
- required?: boolean;
185
- content?: Record<string, { schema?: Record<string, unknown> }>;
186
- } | undefined;
306
+ // Query Parameters
307
+ const queryParams = operation.parameters?.filter(p => p.in === 'query') || [];
308
+ if (queryParams.length > 0) {
309
+ lines.push('### Query Parameters', '');
310
+ for (const param of queryParams) {
311
+ const typeStr = getTypeString(param.schema || { type: 'string' });
312
+ const reqMark = param.required ? ' *(required)*' : '';
313
+ lines.push(`- \`${param.name}\` (${typeStr})${reqMark}: ${param.description || ''}`);
314
+ }
315
+ lines.push('');
316
+ }
317
188
- if (requestBody?.content) {
318
+ // Request Body
319
+ if (operation.requestBody?.content?.['application/json']) {
320
lines.push('### Request Body', '');
190
- if (requestBody.description) {
191
- lines.push(requestBody.description, '');
321
+ if (operation.requestBody.description) {
322
+ lines.push(operation.requestBody.description, '');
323
}
193
- const jsonContent = requestBody.content['application/json'];
194
- if (jsonContent?.schema) {
195
- const schemaProps = renderSchemaProperties(jsonContent.schema);
196
- if (schemaProps.length > 0) {
197
- lines.push('**Properties:**', '');
198
- lines.push(...schemaProps);
199
- lines.push('');
200
- }
324
+ const schema = operation.requestBody.content['application/json'].schema;
325
+ if (schema) {
326
+ lines.push('**Schema:**', '');
327
+ lines.push(...renderSchema(schema));
328
+ lines.push('');
329
+
330
+ // Example
331
+ const example = operation.requestBody.content['application/json'].example ?? generateSampleValue(schema);
332
+ lines.push('**Example:**', '');
333
+ lines.push('```json');
334
+ lines.push(JSON.stringify(example, null, 2));
335
+ lines.push('```', '');
336
}
337
}
338
339
// Responses
205
- const responses = methodData.responses as Record<string, {
206
- description?: string;
207
- content?: Record<string, { schema?: Record<string, unknown> }>;
208
- }> | undefined;
209
-
210
- if (responses) {
211
- // Response status codes table
340
+ if (operation.responses) {
341
lines.push('### Responses', '');
213
- lines.push('| Status | Description |');
214
- lines.push('|--------|-------------|');
215
- for (const [status, response] of Object.entries(responses)) {
216
- const desc = (response.description || '').replace(/\|/g, '\\|').replace(/\n/g, ' ');
217
- lines.push(`| ${status} | ${desc} |`);
218
- }
219
- lines.push('');
342
221
- // Success response body (2xx only)
222
- for (const [status, response] of Object.entries(responses)) {
223
- if (!status.startsWith('2')) continue;
343
+ for (const [status, response] of Object.entries(operation.responses)) {
344
+ const statusEmoji = status.startsWith('2') ? '✅' : status.startsWith('4') ? '⚠️' : '❌';
345
+ lines.push(`#### ${statusEmoji} ${status} - ${response.description || ''}`, '');
346
+
347
const jsonContent = response.content?.['application/json'];
348
if (jsonContent?.schema) {
226
- const schemaProps = renderSchemaProperties(jsonContent.schema);
227
- if (schemaProps.length > 0) {
228
- lines.push(`### Response Body (${status})`, '');
229
- lines.push(...schemaProps);
230
- lines.push('');
349
+ lines.push('**Response Schema:**', '');
350
+ lines.push(...renderSchema(jsonContent.schema));
351
+ lines.push('');
352
+
353
+ // Only show example for success responses
354
+ if (status.startsWith('2')) {
355
+ const example = jsonContent.example ?? generateSampleValue(jsonContent.schema);
356
+ if (example && Object.keys(example as object).length > 0) {
357
+ lines.push('**Example Response:**', '');
358
+ lines.push('```json');
359
+ lines.push(JSON.stringify(example, null, 2));
360
+ lines.push('```', '');
361
+ }
362
}
363
}
364
}
365
}
366
236
- // cURL example
237
- lines.push('### Example Request', '');
367
+ // cURL Example
368
+ lines.push('### Example cURL Request', '');
369
lines.push('```bash');
239
- lines.push(generateCurlExample(op.method, op.path, baseUrl, !!requestBody?.content));
370
+ lines.push(generateCurl(op.method, op.path, baseUrl, operation.parameters, operation.requestBody));
371
lines.push('```', '');
372
}
373
}