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
ts 191 lines 6 KB
Raw
1 // Fumadocs passes its bundled OpenAPI document to a client component. This
2 // module trims that payload to the operations or webhooks on one reference page.
3
4 import type { OpenAPIPageProps } from 'fumadocs-openapi/ui';
5
6 export interface PageOperation {
7 path: string;
8 method: string;
9 }
10
11 export interface PageWebhook {
12 name: string;
13 method: string;
14 }
15
16 const HTTP_METHODS = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace']);
17
18 // Path-item keys that must travel with a kept operation.
19 const SHARED_PATH_ITEM_KEYS = ['parameters', 'servers', 'summary', 'description'];
20
21 interface SliceableDocument {
22 paths?: Record<string, object | undefined>;
23 webhooks?: Record<string, object | undefined>;
24 components?: {
25 securitySchemes?: Record<string, unknown>;
26 };
27 }
28
29 function decodePointerSegment(segment: string): string {
30 return segment.replace(/~1/g, '/').replace(/~0/g, '~');
31 }
32
33 function resolvePointer(document: unknown, ref: string): unknown {
34 let node = document;
35
36 for (const segment of ref.slice(2).split('/')) {
37 if (node === null || typeof node !== 'object' || Array.isArray(node)) return undefined;
38 node = (node as Record<string, unknown>)[decodePointerSegment(segment)];
39 }
40
41 return node;
42 }
43
44 /**
45 * Collects every `#/components/...` pointer reachable from `node`, following
46 * references transitively. Returns null if a non-component internal reference
47 * is found, signalling the caller to keep the whole document.
48 */
49 function collectComponentRefs(
50 document: unknown,
51 node: unknown,
52 found: Set<string>
53 ): Set<string> | null {
54 if (Array.isArray(node)) {
55 for (const item of node) {
56 if (!collectComponentRefs(document, item, found)) return null;
57 }
58 return found;
59 }
60
61 if (node === null || typeof node !== 'object') return found;
62
63 for (const [key, value] of Object.entries(node)) {
64 if (key === '$ref' && typeof value === 'string') {
65 // External references are resolved before bundling; leave them alone.
66 if (!value.startsWith('#/')) continue;
67 if (!value.startsWith('#/components/')) return null;
68 if (found.has(value)) continue;
69
70 found.add(value);
71 if (!collectComponentRefs(document, resolvePointer(document, value), found)) {
72 return null;
73 }
74 continue;
75 }
76
77 if (!collectComponentRefs(document, value, found)) return null;
78 }
79
80 return found;
81 }
82
83 function pickOperations(
84 pathItem: object,
85 methods: Set<string>
86 ): Record<string, unknown> | undefined {
87 const kept: Record<string, unknown> = {};
88 let matched = false;
89
90 for (const [key, value] of Object.entries(pathItem)) {
91 if (HTTP_METHODS.has(key.toLowerCase())) {
92 if (!methods.has(key.toLowerCase())) continue;
93 kept[key] = value;
94 matched = true;
95 continue;
96 }
97 if (SHARED_PATH_ITEM_KEYS.includes(key)) kept[key] = value;
98 }
99
100 return matched ? kept : undefined;
101 }
102
103 function groupByKey<T extends { method: string }>(
104 entries: T[],
105 keyOf: (entry: T) => string
106 ): Map<string, Set<string>> {
107 const grouped = new Map<string, Set<string>>();
108 for (const entry of entries) {
109 const key = keyOf(entry);
110 const methods = grouped.get(key) ?? new Set<string>();
111 methods.add(entry.method.toLowerCase());
112 grouped.set(key, methods);
113 }
114 return grouped;
115 }
116
117 /**
118 * Returns a self-contained document containing the selected operations or
119 * webhooks and every component they reference transitively.
120 *
121 * When the requested operation is missing or a reference cannot be represented
122 * safely, the original document is returned instead of a partial slice.
123 */
124 export function sliceDocumentForPage<T extends object>(
125 bundled: T,
126 operations: PageOperation[] = [],
127 webhooks: PageWebhook[] = []
128 ): T {
129 if (operations.length === 0 && webhooks.length === 0) return bundled;
130
131 const document = bundled as T & SliceableDocument;
132 const paths: Record<string, unknown> = {};
133 for (const [path, methods] of groupByKey(operations, op => op.path)) {
134 const pathItem = document.paths?.[path];
135 if (!pathItem) return bundled; // Unexpected shape -- do not risk a partial document.
136 const kept = pickOperations(pathItem, methods);
137 if (!kept) return bundled;
138 paths[path] = kept;
139 }
140
141 const keptWebhooks: Record<string, unknown> = {};
142 for (const [name, methods] of groupByKey(webhooks, hook => hook.name)) {
143 const webhookItem = document.webhooks?.[name];
144 if (!webhookItem) return bundled;
145 const kept = pickOperations(webhookItem, methods);
146 if (!kept) return bundled;
147 keptWebhooks[name] = kept;
148 }
149
150 const refs = collectComponentRefs(bundled, { paths, webhooks: keptWebhooks }, new Set());
151 if (!refs) return bundled; // Non-component internal reference -- keep everything.
152
153 const components: Record<string, Record<string, unknown>> = {};
154 for (const ref of refs) {
155 const [, , group, ...rest] = ref.split('/');
156 if (!group || rest.length !== 1) return bundled;
157 const name = decodePointerSegment(rest[0]);
158 const value = resolvePointer(bundled, ref);
159 if (value === undefined) return bundled; // Dangling pointer -- keep everything.
160 (components[group] ??= {})[name] = value;
161 }
162
163 // Security requirements name schemes directly rather than via `$ref`, so the
164 // reachability walk above never sees them.
165 if (document.components?.securitySchemes) {
166 components.securitySchemes = document.components.securitySchemes;
167 }
168
169 const sliced: Record<string, unknown> = { ...bundled, paths };
170 if (Object.keys(components).length > 0) sliced.components = components;
171 else delete sliced.components;
172 if (document.webhooks) sliced.webhooks = keptWebhooks;
173
174 return sliced as T;
175 }
176
177 /**
178 * Applies {@link sliceDocumentForPage} to fumadocs' page props, leaving any
179 * other props shape (for example the preloaded variant) untouched.
180 */
181 export function sliceApiPageProps<T extends OpenAPIPageProps>(props: T): T {
182 if (!('payload' in props)) return props;
183
184 return {
185 ...props,
186 payload: {
187 ...props.payload,
188 bundled: sliceDocumentForPage(props.payload.bundled, props.operations, props.webhooks),
189 },
190 } as T;
191 }