Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
tsx 317 lines 9.66 KB
Raw
1 import type { ReactNode } from 'react';
2
3 // Types matching fumadocs-openapi internal structure
4 interface FieldBase {
5 description?: ReactNode;
6 infoTags?: ReactNode[];
7 typeName: string;
8 aliasName: string;
9 deprecated?: boolean;
10 experimental?: boolean;
11 enumValues?: string[];
12 }
13
14 export type SchemaData = FieldBase &
15 (
16 | { type: 'primitive' }
17 | {
18 type: 'object';
19 props: { name: string; $type: string; required: boolean }[];
20 }
21 | { type: 'array'; item: { $type: string } }
22 | { type: 'or'; items: { name: string; $type: string }[] }
23 | { type: 'and'; items: { name: string; $type: string }[] }
24 );
25
26 export interface SchemaUIGeneratedData {
27 $root: string;
28 refs: Record<string, SchemaData>;
29 }
30
31 type SimpleSchema = boolean | SimpleSchemaObject;
32
33 interface SimpleSchemaObject {
34 $ref?: string;
35 type?: string | readonly string[];
36 items?: SimpleSchema;
37 oneOf?: readonly SimpleSchema[];
38 anyOf?: readonly SimpleSchema[];
39 allOf?: readonly SimpleSchema[];
40 properties?: Readonly<Record<string, SimpleSchema>>;
41 additionalProperties?: boolean | SimpleSchema;
42 required?: readonly string[];
43 enum?: readonly unknown[];
44 description?: string;
45 format?: string;
46 default?: unknown;
47 readOnly?: boolean;
48 writeOnly?: boolean;
49 deprecated?: boolean;
50 'x-experimental'?: boolean;
51 }
52
53 interface RenderContext {
54 renderMarkdown: (text: string) => ReactNode;
55 schema: {
56 getRawRef: (obj: object) => string | undefined;
57 /**
58 * Shallowly resolves a Reference Object, merging sibling keywords.
59 * Non-reference values are returned unchanged.
60 */
61 resolve: (node: SimpleSchema) => SimpleSchema;
62 };
63 }
64
65 interface SchemaUIOptions {
66 root: SimpleSchema;
67 readOnly?: boolean;
68 writeOnly?: boolean;
69 }
70
71 /**
72 * Removes the source-level marker when the schema provides a structured
73 * experimental flag. Unflagged descriptions keep their original text so they
74 * do not lose their only lifecycle signal.
75 */
76 export function getSchemaDisplayDescription(description: string, experimental: boolean): string {
77 if (!experimental) return description;
78
79 return description.replace(/^\s*\[experimental\]\s*/i, '');
80 }
81
82 export function generateSchemaData(
83 options: SchemaUIOptions,
84 ctx: RenderContext
85 ): SchemaUIGeneratedData {
86 const refs: Record<string, SchemaData> = {};
87 let counter = 0;
88 const autoIds = new WeakMap<object, string>();
89
90 function getSchemaId(schema: SimpleSchema): string {
91 if (typeof schema === 'boolean') return String(schema);
92 if (typeof schema !== 'object' || schema === null) return `__${counter++}`;
93 const raw = ctx.schema.getRawRef(schema);
94 if (raw) return raw;
95 const prev = autoIds.get(schema);
96 if (prev) return prev;
97 const generated = `__${counter++}`;
98 autoIds.set(schema, generated);
99 return generated;
100 }
101
102 function getTypeName(schema: SimpleSchema): string {
103 if (!schema || typeof schema !== 'object') return 'any';
104 if (schema.$ref) {
105 const refName = schema.$ref.split('/').pop() || 'object';
106 return refName;
107 }
108 if (schema.type === 'array' && schema.items) {
109 return `${getTypeName(schema.items)}[]`;
110 }
111 if (schema.oneOf || schema.anyOf) {
112 const variants = schema.oneOf || schema.anyOf || [];
113 return variants.map((v: SimpleSchema) => getTypeName(v)).join(' | ');
114 }
115 if (schema.enum) {
116 return 'enum';
117 }
118 if (Array.isArray(schema.type)) {
119 const isNullable = schema.type.includes('null');
120 const types = schema.type.filter((t: string) => t !== 'null');
121 const typeName = types.join(' | ') || 'any';
122 return isNullable ? `nullable ${typeName}` : typeName;
123 }
124 return typeof schema.type === 'string' ? schema.type : 'any';
125 }
126
127 function isVisible(schema: SimpleSchema): boolean {
128 if (!schema || typeof schema !== 'object') return true;
129 // readOnly/writeOnly live on the referenced target, not the $ref node.
130 const resolved = ctx.schema.resolve(schema);
131 if (!resolved || typeof resolved !== 'object') return true;
132 if (resolved.writeOnly) return options.writeOnly ?? false;
133 if (resolved.readOnly) return options.readOnly ?? false;
134 return true;
135 }
136
137 function processSchema(schema: SimpleSchema): string {
138 if (!schema || typeof schema !== 'object') {
139 const id = `__${counter++}`;
140 refs[id] = {
141 type: 'primitive',
142 typeName: 'any',
143 aliasName: 'any',
144 };
145 return id;
146 }
147
148 const id = getSchemaId(schema);
149 if (id in refs) return id;
150
151 // Mark as processing to prevent infinite recursion on circular refs
152 refs[id] = { type: 'primitive', typeName: 'any', aliasName: 'any' };
153
154 // Derive identity from the raw node so $ref-keyed dedup remains stable, but
155 // read content from the resolved target.
156 const resolved = ctx.schema.resolve(schema);
157 if (!resolved || typeof resolved !== 'object') return id;
158
159 // For arrays, aliasName is the item type (used in "array of X" display).
160 // Display names come from the raw node so a $ref keeps its schema name.
161 const aliasName =
162 resolved.type === 'array' && resolved.items
163 ? getTypeName(resolved.items)
164 : getTypeName(schema);
165
166 const experimental = resolved['x-experimental'] === true;
167 const base: FieldBase = {
168 description: resolved.description
169 ? ctx.renderMarkdown(getSchemaDisplayDescription(resolved.description, experimental))
170 : undefined,
171 infoTags: generateInfoTags(resolved),
172 typeName: getTypeName(schema),
173 aliasName,
174 deprecated: resolved.deprecated,
175 experimental,
176 enumValues: resolved.enum ? resolved.enum.map((v: unknown) => String(v)) : undefined,
177 };
178
179 // Handle oneOf/anyOf
180 if (resolved.oneOf || resolved.anyOf) {
181 const variants = resolved.oneOf || resolved.anyOf || [];
182 refs[id] = {
183 ...base,
184 type: 'or',
185 items: variants.map((variant: SimpleSchema) => ({
186 name: getTypeName(variant),
187 $type: processSchema(variant),
188 })),
189 };
190 return id;
191 }
192
193 // Handle allOf - merge into single object
194 if (resolved.allOf) {
195 // Merge all schemas together. Each member may itself be a Reference
196 // Object, so resolve before reading its properties.
197 const mergedProperties: Record<string, SimpleSchema> = {};
198 const mergedRequired: string[] = [];
199 for (const rawSubSchema of resolved.allOf) {
200 const subSchema = ctx.schema.resolve(rawSubSchema);
201 if (!subSchema || typeof subSchema !== 'object') continue;
202 if (subSchema.properties) {
203 Object.assign(mergedProperties, subSchema.properties);
204 }
205 if (subSchema.required) {
206 mergedRequired.push(...subSchema.required);
207 }
208 }
209 if (Object.keys(mergedProperties).length > 0) {
210 const props = Object.entries(mergedProperties)
211 .filter(([_, propSchema]) => isVisible(propSchema))
212 .map(([name, propSchema]) => ({
213 name,
214 $type: processSchema(propSchema),
215 required: mergedRequired.includes(name),
216 }));
217 refs[id] = {
218 ...base,
219 type: 'object',
220 props,
221 };
222 return id;
223 }
224 }
225
226 // Handle object (with properties and/or additionalProperties)
227 if (
228 (resolved.type === 'object' || resolved.properties) &&
229 (resolved.properties ||
230 (resolved.additionalProperties && typeof resolved.additionalProperties === 'object'))
231 ) {
232 const required = resolved.required || [];
233 const props: { name: string; $type: string; required: boolean }[] = [];
234
235 if (resolved.properties) {
236 for (const [name, propSchema] of Object.entries(resolved.properties)) {
237 if (!isVisible(propSchema)) continue;
238 props.push({
239 name,
240 $type: processSchema(propSchema as SimpleSchema),
241 required: required.includes(name),
242 });
243 }
244 }
245
246 // Include additionalProperties as a synthetic [key: string] entry
247 if (resolved.additionalProperties && typeof resolved.additionalProperties === 'object') {
248 props.push({
249 name: '[key: string]',
250 $type: processSchema(resolved.additionalProperties),
251 required: false,
252 });
253 }
254
255 refs[id] = {
256 ...base,
257 type: 'object',
258 props,
259 };
260 return id;
261 }
262
263 // Handle array
264 if (resolved.type === 'array' && resolved.items) {
265 refs[id] = {
266 ...base,
267 type: 'array',
268 item: { $type: processSchema(resolved.items) },
269 };
270 return id;
271 }
272
273 // Primitive type
274 refs[id] = {
275 ...base,
276 type: 'primitive',
277 };
278 return id;
279 }
280
281 function generateInfoTags(schema: SimpleSchemaObject): ReactNode[] {
282 const tags: ReactNode[] = [];
283
284 if (schema.default !== undefined) {
285 const defaultStr = JSON.stringify(schema.default);
286 // Skip empty objects/arrays as defaults - they're noise
287 if (defaultStr !== '{}' && defaultStr !== '[]') {
288 tags.push(
289 <span key="default" className="text-xs text-fd-muted-foreground">
290 Default:{' '}
291 <code className="rounded border border-fd-border px-1 py-0.5 font-mono">
292 {defaultStr}
293 </code>
294 </span>
295 );
296 }
297 }
298
299 if (schema.format) {
300 tags.push(
301 <span key="format" className="text-xs text-fd-muted-foreground">
302 Format:{' '}
303 <code className="rounded border border-fd-border px-1 py-0.5 font-mono">
304 {schema.format}
305 </code>
306 </span>
307 );
308 }
309
310 // Enum values are rendered separately in the UI, not as an info tag
311
312 return tags;
313 }
314
315 const $root = processSchema(options.root);
316 return { $root, refs };
317 }